Modern Apps git

← Modern-Apps.git

cast-tv: redesign receiver UI on library:tv

Commit
46ce2a8df89196f27f3b50d5be463bcca4720c1b
Author
vayun-mathur <[email protected]>
When
2026-10-25 21:35 UTC (1 month ago)
Parents
8cb6c96

Diff

cast/tv/build.gradle.kts
diff --git a/cast/tv/build.gradle.kts b/cast/tv/build.gradle.ktsindex cfe47b6cd0..cc74ea3847 100644--- a/cast/tv/build.gradle.kts+++ b/cast/tv/build.gradle.kts@@ -33,6 +33,9 @@ dependencies {     // The wire format, shared verbatim with the phone. Nothing in this app re-implements it.     implementation(project(":cast:protocol"))     implementation(project(":library:e2ee-p2p"))+    // The shared TV design system: theme, cards, controls, states, transport. Deliberately not+    // :library:image, so this offline receiver gains no INTERNET permission from its UI.+    implementation(project(":library:tv"))     // App content arrives as media rather than as pixels now, so the TV needs a player. Not     // `media3-session`: the TV already has a remote-control path through its own control channel,     // and a MediaSession would be a second one competing with it.
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.ktindex 923c6a62a2..0239efc632 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt@@ -270,6 +270,8 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {                         ) {                             NowPlayingScreen(                                 nowPlaying = nowPlaying,+                                snapshot = playback,+                                sourceName = mirroring?.sourceName.orEmpty(),                                 positionMs = positionMs,                                 artwork = state.artwork,                                 modifier = Modifier.weight(1f),
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/NetworkLabel.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/NetworkLabel.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/NetworkLabel.ktnew file mode 100644index 0000000000..a77bbf5717--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/NetworkLabel.kt@@ -0,0 +1,63 @@+package com.vayunmathur.cast.tv.platform++import android.content.Context+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import android.net.wifi.WifiManager+import com.vayunmathur.library.log.Log+import java.net.NetworkInterface++private const val TAG = "NetworkLabel"++/**+ * A best-effort "On HomeWi-Fi · 192.168.1.4" line for the idle screen, or empty when it cannot be+ * read.+ *+ * Two independent halves, joined only when both exist: the SSID comes from `WifiManager` (quoted+ * on older platforms, bare `<unknown ssid>` when the platform withholds it without location+ * access), and the IPv4 address is the first non-loopback site-local address on an up interface.+ * Reading fails open - no permission here is worth asking for, because the line is a nicety and+ * the screen is complete without it.+ */+object NetworkLabel {++    fun of(context: Context): String {+        val ssid = runCatching { wifiSsid(context) }.getOrNull()+        val ip = runCatching { lanIpv4() }.getOrNull()+        return when {+            ssid != null && ip != null -> "$ssid · $ip"+            ssid != null -> ssid+            ip != null -> ip+            else -> ""+        }+    }++    private fun wifiSsid(context: Context): String? {+        @Suppress("DEPRECATION")+        val info = (context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager)+            ?.connectionInfo+            ?: return null+        // On Wi-Fi only: an Ethernet-connected TV has no SSID to show rather than a wrong one.+        val manager = context.getSystemService(ConnectivityManager::class.java) ?: return null+        val active = manager.getNetworkCapabilities(manager.activeNetwork) ?: return null+        if (!active.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) return null+        return info.ssid+            ?.removeSurrounding("\"")+            ?.takeIf { it.isNotBlank() && !it.startsWith("<unknown") }+    }++    private fun lanIpv4(): String? {+        val interfaces = runCatching { NetworkInterface.getNetworkInterfaces()?.toList() }+            .getOrNull()+            ?: run {+                Log.status(TAG, "no network interfaces visible")+                return null+            }+        return interfaces.asSequence()+            .filter { runCatching { it.isUp && !it.isLoopback }.getOrDefault(false) }+            .flatMap { it.inetAddresses.asSequence() }+            .filter { it.address.size == 4 && !it.isLoopbackAddress && it.isSiteLocalAddress }+            .map { it.hostAddress.orEmpty() }+            .firstOrNull { it.isNotBlank() }+    }+}
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.ktindex 9d6ac4b2de..b986d19f1f 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt@@ -307,6 +307,7 @@ object ReceiverController {             phase = ReceiverPhase.Advertising,             deviceName = name,             localNetworkBlocked = nsd.localNetworkBlocked,+            networkLabel = NetworkLabel.of(context),         )         Log.status(TAG, "receiving as '$name' ($deviceId) on control port ${server.localPort}") 
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.ktindex 212b6d92ff..dbfafd63f3 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt@@ -114,6 +114,14 @@ data class ReceiverUiState(     val phase: ReceiverPhase = ReceiverPhase.Starting,     /** What the phone will show in its device list, and what the idle screen tells the user to pick. */     val deviceName: String = "",+    /**+     * "On HomeWi-Fi · 192.168.1.4", or empty when it could not be read.+     *+     * A best-effort footer for the idle screen: the SSID needs no permission to attempt, but the+     * platform withholds it without location access, and the IP falls back on its own. Empty is a+     * complete answer, not a loading state - the screen simply omits the line.+     */+    val networkLabel: String = "",     /**      * Android 16+ refused the mDNS registration. Distinct from "nothing has connected yet", because      * the fix is a permission rather than opening the app on the phone.
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Lyrics.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Lyrics.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Lyrics.ktnew file mode 100644index 0000000000..d84872b2d2--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Lyrics.kt@@ -0,0 +1,155 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+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.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.em+import androidx.compose.ui.unit.sp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.cast.protocol.LyricLine+import com.vayunmathur.cast.protocol.NowPlaying++/**+ * Timed lyrics that follow the clock, or untimed ones as a block.+ *+ * `userScrollEnabled = false` and no focus: this list is driven entirely from [positionMs].+ *+ * The index comes from a `derivedStateOf` over that lambda, which is what keeps the cost of a+ * per-frame clock off this column - it recomputes every frame but only *invalidates* when the+ * answer changes, which is a few dozen times a song rather than sixty times a second.+ *+ * **The current line is scrolled to the top, and what is below it fades out.** Upcoming lyrics+ * read downward, so the gradient falls in the direction the eye is already travelling and the+ * line being sung is the most legible thing on the panel. It is a mask over the whole column+ * rather than a per-line alpha, because a line half in and half out of the fade should fade by+ * the same amount as the pixels around it.+ */+@Composable+fun Lyrics(nowPlaying: NowPlaying, positionMs: () -> Long, modifier: Modifier = Modifier) {+    if (nowPlaying.lyrics.isEmpty()) {+        // Nothing to highlight and nothing to scroll to, so it is a block the user reads at+        // their own pace. Scrollable would be a lie: there is no input for it.+        LazyColumn(modifier = modifier.fadingEdge(), userScrollEnabled = false) {+            item {+                Text(+                    text = nowPlaying.plainLyrics,+                    fontSize = LYRIC_SIZE_SP.sp,+                    lineHeight = LYRIC_LINE_HEIGHT_EM.em,+                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),+                )+            }+        }+        return+    }++    val lines = nowPlaying.lyrics+    // `rememberUpdatedState`, and it is load-bearing. `PlaybackClock` builds a fresh lambda per+    // recomposition that closes over *that* composition's snapshot; a `remember` keyed only on+    // the lines would pin the first one for the whole track, so the highlight would keep+    // extrapolating from the first anchor and never see a pause, a seek or a scrub. Only+    // `frameNowMs` is live inside that lambda - everything else in it is captured by value.+    val clock by rememberUpdatedState(positionMs)+    val current by remember(lines) {+        derivedStateOf { currentLyricIndex(lines, clock()) }+    }+    val listState = rememberLazyListState()+    LaunchedEffect(current, lines) {+        if (current >= 0) runCatching { listState.animateScrollToItem(current) }+    }++    LazyColumn(+        state = listState,+        modifier = modifier.fadingEdge(),+        userScrollEnabled = false,+        // **Between items, and [LYRIC_LINE_HEIGHT_EM] within one.** A long lyric wraps, and+        // spacing alone leaves the wrapped halves of one line closer together than the default+        // leading allows - so two lines of one lyric collide while the gap to the next lyric+        // looks generous.+        verticalArrangement = Arrangement.spacedBy(LYRIC_GAP_DP.dp),+        // Room to scroll the last lyric up to where the current one is read, instead of it+        // stopping part-way and leaving the highlight pinned at the bottom for the outro.+        contentPadding = PaddingValues(bottom = 240.dp),+    ) {+        itemsIndexed(lines) { index, line ->+            val isCurrent = index == current+            Text(+                text = line.text,+                fontSize = if (isCurrent) LYRIC_CURRENT_SIZE_SP.sp else LYRIC_SIZE_SP.sp,+                lineHeight = LYRIC_LINE_HEIGHT_EM.em,+                fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,+                color = if (isCurrent) {+                    MaterialTheme.colorScheme.primary+                } else {+                    MaterialTheme.colorScheme.onSurface.copy(alpha = 0.55f)+                },+            )+        }+    }+}++/**+ * Fades the bottom of a column out to nothing.+ *+ * `DstIn` over an offscreen layer, which is the one way to make a *mask* rather than a scrim:+ * a gradient drawn in the background colour would be opaque over whatever sits beside the+ * column, and one drawn in black would be a grey wash. Offscreen compositing is required for+ * the blend to have the column's own alpha to work against.+ */+private fun Modifier.fadingEdge(): Modifier = this+    .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }+    .drawWithContent {+        drawContent()+        drawRect(+            brush = Brush.verticalGradient(+                FADE_START to Color.White,+                1f to Color.Transparent,+            ),+            blendMode = BlendMode.DstIn,+        )+    }++/**+ * Which line is current at [positionMs], or -1 before the first one.+ *+ * The same rule the phone applies, deliberately written out rather than shared: `:music` and+ * this module have no common dependency, and one `indexOfLast` is a smaller thing to duplicate+ * than a module boundary is to move. The boundary is inclusive - a line whose timestamp is+ * exactly the position is the line being sung.+ */+private fun currentLyricIndex(lines: List<LyricLine>, positionMs: Long): Int =+    lines.indexOfLast { it.atMs <= positionMs }++/**+ * Lyric sizes, for a panel that reports 960x540dp.+ *+ * Legible across a room and small enough that half a dozen lines fit beside the cover, which+ * is what makes the highlight look like it is moving through a song rather than replacing the+ * screen.+ */+private const val LYRIC_CURRENT_SIZE_SP = 28+private const val LYRIC_SIZE_SP = 22+private const val LYRIC_GAP_DP = 20++/** Leading within one wrapped lyric, as a multiple of its own size. */+private const val LYRIC_LINE_HEIGHT_EM = 1.35f++/** Where the fade begins, as a fraction of the column's height. */+private const val FADE_START = 0.55f
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.ktindex eed717d65a..eed58d4c1b 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/NowPlaying.kt@@ -1,87 +1,75 @@ package com.vayunmathur.cast.tv.ui +import android.text.format.DateUtils import androidx.compose.foundation.Image import androidx.compose.foundation.background+import androidx.compose.foundation.border 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.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.itemsIndexed-import androidx.compose.foundation.lazy.rememberLazyListState-import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip-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.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap-import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale 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 androidx.compose.ui.unit.em-import androidx.compose.ui.unit.sp import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text-import com.vayunmathur.cast.protocol.LyricLine import com.vayunmathur.cast.protocol.NowPlaying import com.vayunmathur.cast.tv.R import com.vayunmathur.cast.tv.platform.ArtworkFetcher+import com.vayunmathur.cast.tv.platform.PlaybackSnapshot+import com.vayunmathur.library.tv.TvBadge+import com.vayunmathur.library.tv.TvDimens+import com.vayunmathur.library.tv.TvIcon+import com.vayunmathur.library.tv.TvSeekRow+import com.vayunmathur.library.ui.IconMusicNote import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext  /**- * The cover and the lyrics, for a session with no picture.+ * The cover, the track, and the lyrics, for a session with no picture.  *- * **Not part of `ReceiverContent`.** For an audio-only session `MirrorActivity` adds no `SurfaceView`- * at all and fills its window with a `ComposeView`, so `ReceiverContent`'s mirroring arm is on screen- * for a few milliseconds and then never again. This is drawn by `MirrorActivity.overlayView()`, above- * the transport overlay that is already pinned permanently visible for audio.+ * **Not part of `ReceiverContent`.** For an audio-only session `MirrorActivity` adds no+ * `SurfaceView` at all and fills its window with this beside the transport overlay, so+ * `ReceiverContent`'s mirroring arm is on screen for a few milliseconds and then never again.  *- * **The title, author and album are deliberately not here.** They live in [TransportOverlay]'s- * headline, where they serve a video session too and where the space is already reserved for a line of- * text. Drawing them in both places spent this screen's whole vertical budget on saying twice what the- * bar underneath says once - which is what pushed the cover off the top of the panel.+ * Artwork-led: a big card on the left, title/artist/source on the right with the seek row and+ * the play state, lyrics below the title block when the phone sent any. The backdrop is the+ * cover itself dimmed under scrims (or an accent gradient with no cover) - local pixels only,+ * never anything fetched off the network beyond the phone's own proxy.  *- * **Nothing on it is focusable, and the reason is not `TransportOverlay`'s.** That overlay avoids- * focus so the compositor is never asked to redraw a video layer underneath it; an audio-only session- * has no video layer, so that argument does not apply here. The reason here is simply that there is- * no input model on this screen - the lyrics scroll from the clock, so a scrollable focus target would- * be a thing the remote could move that changes nothing and takes the D-pad away from seeking.+ * **Nothing on it is focusable.** There is no input model on this screen - the lyrics scroll+ * from the clock, so a scrollable focus target would be a thing the remote could move that+ * changes nothing and takes the D-pad away from seeking.  *- * It does **not** paint a background. `MirrorActivity` paints the window once, behind both this and- * the transport bar beneath it, so that the two are one continuous surface rather than a sheet of- * colour with a differently-coloured strip under it. Painting here as well would be a second owner of- * the same pixels and would put the seam back the moment either colour changed.- *- * [positionMs] is a lambda rather than a `Long` on purpose. It is read sixty times a second, and- * passing the value would recompose the artwork and the entire lyrics column every frame on hardware- * with no headroom to spare. Only the small subtree that derives the lyric index from it recomposes,- * and that a few dozen times a song.+ * [positionMs] is a lambda rather than a `Long` on purpose. It is read sixty times a second,+ * and passing the value would recompose the artwork and the entire lyrics column every frame+ * on hardware with no headroom to spare. Only the small progress subtree reads it, and the+ * lyrics index derives from it a few dozen times a song.  */ @Composable fun NowPlayingScreen(     nowPlaying: NowPlaying,+    snapshot: PlaybackSnapshot,+    /** Who is casting: the app label, or the phone's name for a screen mirror. */+    sourceName: String,     /** Where playback is right now, read per frame. See the note above about why it is a lambda. */     positionMs: () -> Long,     artwork: ArtworkFetcher?,@@ -90,34 +78,87 @@ fun NowPlayingScreen(     val cover = rememberArtwork(nowPlaying.artworkResourceId, artwork)     val hasLyrics = nowPlaying.lyrics.isNotEmpty() || nowPlaying.plainLyrics.isNotEmpty() -    Box(-        modifier = modifier-            .fillMaxSize()-            .padding(horizontal = 48.dp, vertical = 32.dp),-    ) {-        if (hasLyrics) {-            Row(-                modifier = Modifier.fillMaxSize(),-                horizontalArrangement = Arrangement.spacedBy(48.dp),+    Box(modifier = modifier.fillMaxSize()) {+        NowPlayingBackdrop(cover)+        Row(+            modifier = Modifier+                .fillMaxSize()+                .padding(+                    start = TvDimens.SafeHorizontal,+                    end = TvDimens.SafeHorizontal,+                    top = TvDimens.SafeVertical,+                    bottom = 16.dp,+                ),+            horizontalArrangement = Arrangement.spacedBy(48.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            // **Sized from the height it is given, never from a constant.** Squaring a filled+            // height cannot overflow whatever the window turns out to be.+            ArtworkCard(cover, Modifier.fillMaxHeight())+            Column(+                modifier = Modifier.weight(1f).fillMaxHeight(),+                verticalArrangement = Arrangement.spacedBy(12.dp),             ) {-                // **Sized from the height it is given, never from a constant.** This panel is 540dp-                // tall, so a cover with a fixed edge overflows and - centred - runs off the top of the-                // screen rather than being clipped at the bottom where it would at least be obvious.-                // Squaring a filled height cannot overflow whatever the window turns out to be.-                Cover(cover, Modifier.fillMaxHeight())-                Lyrics(nowPlaying, positionMs, Modifier.weight(1f).fillMaxHeight())+                // **The title replaces the app's name rather than sitting beside it.** A user+                // looking at a track already knows which app they started; the source survives+                // as the eyebrow above it.+                TitleBlock(+                    title = nowPlaying.title,+                    author = nowPlaying.author,+                    album = nowPlaying.album,+                    sourceName = sourceName,+                    snapshot = snapshot,+                )+                NowPlayingProgress(positionMs = positionMs, snapshot = snapshot)+                if (hasLyrics) {+                    Lyrics(+                        nowPlaying = nowPlaying,+                        positionMs = positionMs,+                        modifier = Modifier.weight(1f).fillMaxWidth(),+                    )+                }             }+        }+    }+}++/**+ * The cover dimmed under scrims, or an accent gradient with no cover.+ *+ * A mask-free scrim rather than a second background owner: `MirrorActivity` paints the window+ * once behind both this and the transport bar, so the two stay one continuous surface.+ */+@Composable+private fun NowPlayingBackdrop(cover: ImageBitmap?) {+    val scheme = MaterialTheme.colorScheme+    Box(Modifier.fillMaxSize()) {+        if (cover != null) {+            Image(+                bitmap = cover,+                contentDescription = null,+                modifier = Modifier.fillMaxSize(),+                contentScale = ContentScale.Crop,+                alpha = BACKDROP_ALPHA,+            )         } else {-            // The common case, not the exception - every MP3 reaches here, because the phone's lyrics-            // reader handles Vorbis and MP4 tags and not ID3. A centred cover with the bar naming it-            // looks deliberate; the split layout with one half empty looks unfinished.             Box(-                modifier = Modifier.fillMaxSize(),-                contentAlignment = Alignment.Center,-            ) {-                Cover(cover, Modifier.fillMaxHeight())-            }+                Modifier.fillMaxSize().background(+                    Brush.verticalGradient(+                        0f to scheme.primaryContainer.copy(alpha = 0.35f),+                        1f to Color.Transparent,+                    ),+                ),+            )         }+        Box(+            Modifier.fillMaxSize().background(+                Brush.verticalGradient(+                    0f to scheme.background.copy(alpha = 0.45f),+                    0.5f to scheme.background.copy(alpha = 0.72f),+                    1f to scheme.background,+                ),+            ),+        )     } } @@ -125,16 +166,19 @@ fun NowPlayingScreen(  * The cover, or a drawn stand-in for one.  *  * **Never a broken image.** No artwork is by far the most likely outcome for a library of loose- * files, and it is also what a failed fetch and a fetch still in flight look like - so all three land- * on a tonal surface that says so in words rather than on anything that reads as an error.+ * files, and it is also what a failed fetch and a fetch still in flight look like - so all three+ * land on a tonal surface that says so in words rather than on anything that reads as an error.  */ @Composable-private fun Cover(cover: ImageBitmap?, modifier: Modifier) {+private fun ArtworkCard(cover: ImageBitmap?, modifier: Modifier) {+    val scheme = MaterialTheme.colorScheme+    val shape = MaterialTheme.shapes.large     Box(         modifier = modifier             .aspectRatio(1f)-            .clip(RoundedCornerShape(16.dp))-            .background(MaterialTheme.colorScheme.surfaceVariant),+            .clip(shape)+            .background(scheme.surfaceVariant)+            .border(2.dp, scheme.primary.copy(alpha = 0.5f), shape),         contentAlignment = Alignment.Center,     ) {         if (cover != null) {@@ -145,130 +189,99 @@ private fun Cover(cover: ImageBitmap?, modifier: Modifier) {                 contentScale = ContentScale.Crop,             )         } else {-            Text(-                text = stringResource(R.string.tv_now_playing_no_artwork),-                style = MaterialTheme.typography.titleMedium,-                color = MaterialTheme.colorScheme.onSurfaceVariant,-                textAlign = TextAlign.Center,-            )-        }-    }-}--/**- * Timed lyrics that follow the clock, or untimed ones as a block.- *- * `userScrollEnabled = false` and no focus: this list is driven entirely from [positionMs].- *- * The index comes from a `derivedStateOf` over that lambda, which is what keeps the cost of a per-frame- * clock off this column - it recomputes every frame but only *invalidates* when the answer changes,- * which is a few dozen times a song rather than sixty times a second.- *- * **The current line is scrolled to the top, and what is below it fades out.** Upcoming lyrics read- * downward, so the gradient falls in the direction the eye is already travelling and the line being- * sung is the most legible thing on the panel. It is a mask over the whole column rather than a- * per-line alpha, because a line half in and half out of the fade should fade by the same amount as- * the pixels around it.- */-@Composable-private fun Lyrics(nowPlaying: NowPlaying, positionMs: () -> Long, modifier: Modifier) {-    if (nowPlaying.lyrics.isEmpty()) {-        // Nothing to highlight and nothing to scroll to, so it is a block the user reads at their own-        // pace. Scrollable would be a lie: there is no input for it.-        LazyColumn(modifier = modifier.fadingEdge(), userScrollEnabled = false) {-            item {+            Column(+                horizontalAlignment = Alignment.CenterHorizontally,+                verticalArrangement = Arrangement.spacedBy(8.dp),+            ) {+                Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {+                    TvIcon { IconMusicNote() }+                }                 Text(-                    text = nowPlaying.plainLyrics,-                    fontSize = LYRIC_SIZE_SP.sp,-                    lineHeight = LYRIC_LINE_HEIGHT_EM.em,-                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),+                    text = stringResource(R.string.tv_now_playing_no_artwork),+                    style = MaterialTheme.typography.titleMedium,+                    color = scheme.onSurfaceVariant,                 )             }         }-        return-    }--    val lines = nowPlaying.lyrics-    // `rememberUpdatedState`, and it is load-bearing. `PlaybackClock` builds a fresh lambda per-    // recomposition that closes over *that* composition's snapshot; a `remember` keyed only on the-    // lines would pin the first one for the whole track, so the highlight would keep extrapolating-    // from the first anchor and never see a pause, a seek or a scrub. Only `frameNowMs` is live-    // inside that lambda - everything else in it is captured by value.-    val clock by rememberUpdatedState(positionMs)-    val current by remember(lines) {-        derivedStateOf { currentLyricIndex(lines, clock()) }-    }-    val listState = rememberLazyListState()-    LaunchedEffect(current, lines) {-        if (current >= 0) runCatching { listState.animateScrollToItem(current) }     }+} -    LazyColumn(-        state = listState,-        modifier = modifier.fadingEdge(),-        userScrollEnabled = false,-        // **Between items, and [LYRIC_LINE_HEIGHT_EM] within one.** A long lyric wraps, and spacing-        // alone leaves the wrapped halves of one line closer together than the default leading allows-        // - so two lines of one lyric collide while the gap to the next lyric looks generous.-        verticalArrangement = Arrangement.spacedBy(LYRIC_GAP_DP.dp),-        // Room to scroll the last lyric up to where the current one is read, instead of it stopping-        // part-way and leaving the highlight pinned at the bottom for the outro.-        contentPadding = PaddingValues(bottom = 240.dp),-    ) {-        itemsIndexed(lines) { index, line ->-            val isCurrent = index == current+@Composable+private fun TitleBlock(+    title: String,+    author: String,+    album: String,+    sourceName: String,+    snapshot: PlaybackSnapshot,+) {+    val scheme = MaterialTheme.colorScheme+    val state = snapshot.state+    Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+        if (sourceName.isNotBlank()) {             Text(-                text = line.text,-                fontSize = if (isCurrent) LYRIC_CURRENT_SIZE_SP.sp else LYRIC_SIZE_SP.sp,-                lineHeight = LYRIC_LINE_HEIGHT_EM.em,-                fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,-                color = if (isCurrent) {-                    MaterialTheme.colorScheme.primary-                } else {-                    MaterialTheme.colorScheme.onSurface.copy(alpha = 0.55f)-                },+                text = sourceName.uppercase(),+                style = MaterialTheme.typography.labelLarge,+                color = scheme.primary,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,             )         }-    }-}--/**- * Fades the bottom of a column out to nothing.- *- * `DstIn` over an offscreen layer, which is the one way to make a *mask* rather than a scrim: a- * gradient drawn in the background colour would be opaque over the cover beside it, and one drawn in- * black would be a grey wash on any theme but this one. Offscreen compositing is required for the- * blend to have the column's own alpha to work against.- */-private fun Modifier.fadingEdge(): Modifier = this-    .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }-    .drawWithContent {-        drawContent()-        drawRect(-            brush = Brush.verticalGradient(-                FADE_START to Color.White,-                1f to Color.Transparent,-            ),-            blendMode = BlendMode.DstIn,+        Text(+            text = title.ifBlank { sourceName },+            style = MaterialTheme.typography.displaySmall,+            color = scheme.onSurface,+            maxLines = 2,+            overflow = TextOverflow.Ellipsis,         )+        if (author.isNotBlank()) {+            Text(+                text = author,+                style = MaterialTheme.typography.titleLarge,+                color = scheme.onSurface.copy(alpha = 0.85f),+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+            )+        }+        if (album.isNotBlank()) {+            Text(+                text = album,+                style = MaterialTheme.typography.titleMedium,+                color = scheme.onSurfaceVariant,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+            )+        }+        // The state, not a button: a stall and a pause look identical on a still screen, and+        // only one of them is the user's own doing.+        when {+            state.buffering -> TvBadge(text = stringResource(R.string.tv_now_playing_buffering))+            !state.playing -> TvBadge(text = stringResource(R.string.tv_now_playing_paused))+        }     }+}  /**- * Which line is current at [positionMs], or -1 before the first one.- *- * The same rule the phone applies, deliberately written out rather than shared: `:music` and this- * module have no common dependency, and one `indexOfLast` is a smaller thing to duplicate than a- * module boundary is to move. The boundary is inclusive - a line whose timestamp is exactly the- * position is the line being sung.+ * The seek row. Reads the per-frame clock in this small subtree only, so the artwork and the+ * lyrics column above it are not in a scope that invalidates sixty times a second.  */-private fun currentLyricIndex(lines: List<LyricLine>, positionMs: Long): Int =-    lines.indexOfLast { it.atMs <= positionMs }+@Composable+private fun NowPlayingProgress(positionMs: () -> Long, snapshot: PlaybackSnapshot) {+    val position = positionMs()+    val duration = snapshot.state.durationMs+    if (duration <= 0) return+    TvSeekRow(+        elapsed = DateUtils.formatElapsedTime((position / 1_000).coerceAtLeast(0)),+        total = DateUtils.formatElapsedTime((duration / 1_000).coerceAtLeast(0)),+        progress = (position.toFloat() / duration).coerceIn(0f, 1f),+    )+}  /**  * The decoded cover for [resourceId], or null while it is being fetched and if it never arrives.  *- * Keyed on the resource id, so a track change starts a fresh fetch and - more importantly - drops the- * previous cover the instant the id changes rather than leaving it on screen over the next track.+ * Keyed on the resource id, so a track change starts a fresh fetch and - more importantly - drops+ * the previous cover the instant the id changes rather than leaving it on screen over the next+ * track.  */ @Composable private fun rememberArtwork(resourceId: String, artwork: ArtworkFetcher?): ImageBitmap? {@@ -279,18 +292,4 @@ private fun rememberArtwork(resourceId: String, artwork: ArtworkFetcher?): Image     return bitmap } -/**- * Lyric sizes, for a panel that reports 960x540dp.- *- * Legible across a room and small enough that half a dozen lines fit beside the cover, which is what- * makes the highlight look like it is moving through a song rather than replacing the screen.- */-private const val LYRIC_CURRENT_SIZE_SP = 28-private const val LYRIC_SIZE_SP = 22-private const val LYRIC_GAP_DP = 20--/** Leading within one wrapped lyric, as a multiple of its own size. */-private const val LYRIC_LINE_HEIGHT_EM = 1.35f--/** Where the fade begins, as a fraction of the column's height. */-private const val FADE_START = 0.55f+private const val BACKDROP_ALPHA = 0.22f
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PairingScreen.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PairingScreen.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PairingScreen.ktnew file mode 100644index 0000000000..725d2eca2b--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PairingScreen.kt@@ -0,0 +1,124 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.cast.tv.R+import com.vayunmathur.library.tv.TvDimens++/**+ * The pairing code, as huge individual digit tiles.+ *+ * The one thing on this screen the user reads from across a room and copies exactly, so each+ * digit gets its own accent-bordered box in `displayLarge` with a monospaced feel - chunks and+ * spacing carry over from the old layout, which grouped the same way for the same reason. Above+ * it, who is asking; below it, how many tries are left, or the notice that the code was replaced+ * after three wrong attempts.+ *+ * Nothing is focusable: there is no input on this screen (the typing happens on the phone), so+ * a focus target would be a thing the D-pad could reach that does nothing.+ */+@Composable+fun PairingScreen(+    senderName: String,+    code: String,+    attemptsLeft: Int,+    codeChanged: Boolean,+    modifier: Modifier = Modifier,+) {+    val scheme = MaterialTheme.colorScheme+    Column(+        modifier = modifier+            .fillMaxSize()+            .background(scheme.background)+            .padding(+                start = TvDimens.SafeHorizontal,+                end = TvDimens.SafeHorizontal,+                top = TvDimens.SafeVertical,+                bottom = TvDimens.SafeVertical,+            ),+        verticalArrangement = Arrangement.spacedBy(28.dp, Alignment.CenterVertically),+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        Text(+            text = stringResource(R.string.tv_pair_from, senderName),+            style = MaterialTheme.typography.headlineSmall,+            color = scheme.onSurfaceVariant,+            textAlign = TextAlign.Center,+        )+        Text(+            text = stringResource(R.string.tv_pair_title),+            style = MaterialTheme.typography.headlineMedium,+            color = scheme.onSurface,+            textAlign = TextAlign.Center,+        )+        DigitTiles(code)+        if (codeChanged) {+            Text(+                text = stringResource(R.string.tv_pair_new_code),+                style = MaterialTheme.typography.titleMedium,+                color = scheme.error,+                textAlign = TextAlign.Center,+            )+        } else {+            Text(+                text = pluralStringResource(R.plurals.tv_pair_attempts, attemptsLeft, attemptsLeft),+                style = MaterialTheme.typography.titleMedium,+                color = scheme.onSurfaceVariant,+                textAlign = TextAlign.Center,+            )+        }+    }+}++@Composable+private fun DigitTiles(code: String) {+    val scheme = MaterialTheme.colorScheme+    val shape = MaterialTheme.shapes.medium+    Row(+        horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterHorizontally),+    ) {+        code.chunked(3).forEachIndexed { chunkIndex, chunk ->+            Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {+                chunk.forEach { digit ->+                    Box(+                        modifier = Modifier+                            .size(width = 112.dp, height = 148.dp)+                            .background(scheme.surface, shape)+                            .border(3.dp, scheme.primary, shape),+                        contentAlignment = Alignment.Center,+                    ) {+                        Text(+                            text = digit.toString(),+                            style = MaterialTheme.typography.displayLarge.copy(+                                fontFamily = FontFamily.Monospace,+                            ),+                            color = scheme.onSurface,+                            textAlign = TextAlign.Center,+                        )+                    }+                }+            }+            // A breath between the two halves of the code, matching the old "123  456" grouping.+            if (chunkIndex == 0 && code.length > 3) {+                Box(Modifier.size(16.dp))+            }+        }+    }+}
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PlaybackClock.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PlaybackClock.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PlaybackClock.ktnew file mode 100644index 0000000000..66b069b17d--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/PlaybackClock.kt@@ -0,0 +1,44 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.withFrameMillis+import com.vayunmathur.cast.tv.platform.PlaybackSnapshot++/**+ * Owns the one per-frame clock a served session needs, and hands it down as a lambda.+ *+ * The now-playing screen's lyrics need the same interpolated position and the same+ * scrub-preview override as the transport bar, and two tickers would be two answers to one+ * question.+ *+ * **Hoisted as a lambda, not as a value, and the distinction is the whole point.** Passing the+ * number down would put every reader of it in the recomposition scope that invalidates sixty+ * times a second - which on TV-class hardware means redrawing a bitmap and a full lyrics column+ * per frame. Passing a lambda leaves the invalidation here, where the state is read, and lets+ * each reader decide how much of itself depends on it.+ *+ * Keyed on the snapshot so every fresh one re-anchors, and the ticker stops while playback is+ * paused: a frame callback per frame for a still bar would keep the panel awake for nothing.+ */+@Composable+fun PlaybackClock(+    snapshot: PlaybackSnapshot,+    /** A scrub the user is composing, which overrides the clock entirely. Null when not scrubbing. */+    scrubPreviewMs: Long?,+    content: @Composable (positionMs: () -> Long) -> Unit,+) {+    var frameNowMs by remember { mutableLongStateOf(System.currentTimeMillis()) }+    LaunchedEffect(snapshot) {+        frameNowMs = System.currentTimeMillis()+        if (!snapshot.state.playing) return@LaunchedEffect+        while (true) {+            withFrameMillis { frameNowMs = System.currentTimeMillis() }+        }+    }+    content { scrubPreviewMs ?: snapshot.positionAt(frameNowMs) }+}
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReadyScreen.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReadyScreen.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReadyScreen.ktnew file mode 100644index 0000000000..329767f6e8--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReadyScreen.kt@@ -0,0 +1,264 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.shadow+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.cast.tv.R+import com.vayunmathur.library.tv.TvButton+import com.vayunmathur.library.tv.TvDimens+import com.vayunmathur.library.tv.TvIcon+import com.vayunmathur.library.tv.TvInitialFocus+import com.vayunmathur.library.ui.IconCast+import com.vayunmathur.library.ui.IconDialpad+import com.vayunmathur.library.ui.IconLock+import com.vayunmathur.library.ui.IconTv+import com.vayunmathur.library.ui.SpecialAccess++/**+ * The ambient idle screen: what the TV shows while it waits for a phone.+ *+ * Calm rather than empty. The device name is the headline (it is what the phone's device list+ * shows, so matching it is the whole task), a cast glyph with an accent glow anchors the middle,+ * and three step cards say how to cast. The footer states the privacy facts the product is built+ * on - offline, E2EE, no account - plus the network name/IP when the receiver could read it.+ *+ * Paints its own background: the theme deliberately paints nothing, because the same theme wraps+ * an overlay above a decoder surface that must stay transparent.+ */+@Composable+fun ReadyScreen(deviceName: String, networkLabel: String, modifier: Modifier = Modifier) {+    val scheme = MaterialTheme.colorScheme+    Column(+        modifier = modifier+            .fillMaxSize()+            .background(scheme.background)+            .padding(+                start = TvDimens.SafeHorizontal,+                end = TvDimens.SafeHorizontal,+                top = TvDimens.SafeVertical,+                bottom = TvDimens.SafeVertical,+            ),+        verticalArrangement = Arrangement.SpaceBetween,+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        Column(+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(20.dp),+            modifier = Modifier.padding(top = 24.dp),+        ) {+            CastGlyph()+            Text(+                text = deviceName,+                style = MaterialTheme.typography.displayMedium,+                color = scheme.onSurface,+                textAlign = TextAlign.Center,+                maxLines = 1,+            )+            Text(+                text = stringResource(R.string.tv_ready_title),+                style = MaterialTheme.typography.titleLarge,+                color = scheme.onSurfaceVariant,+                textAlign = TextAlign.Center,+            )+        }++        HowToSteps(deviceName = deviceName)++        Column(+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            AutoOpenHintCard()+            Text(+                text = stringResource(R.string.tv_privacy_facts),+                style = MaterialTheme.typography.bodyMedium,+                color = scheme.onSurfaceVariant,+                textAlign = TextAlign.Center,+            )+            if (networkLabel.isNotBlank()) {+                Text(+                    text = stringResource(R.string.tv_network_line, networkLabel),+                    style = MaterialTheme.typography.bodyMedium,+                    color = scheme.onSurfaceVariant.copy(alpha = 0.75f),+                    textAlign = TextAlign.Center,+                )+            }+        }+    }+}++/**+ * The cast glyph with a soft accent glow: the visual anchor of the idle screen, echoing the+ * phone app's cast mark without any of its touch chrome.+ */+@Composable+private fun CastGlyph() {+    val scheme = MaterialTheme.colorScheme+    Box(+        modifier = Modifier+            .size(120.dp)+            .shadow(32.dp, CircleShape, ambientColor = scheme.primary, spotColor = scheme.primary)+            .background(scheme.primaryContainer, CircleShape),+        contentAlignment = Alignment.Center,+    ) {+        Box(Modifier.size(56.dp), contentAlignment = Alignment.Center) {+            TvIcon { IconCast() }+        }+    }+}++/** The three "how to cast" steps, as a row of cards readable from across the room. */+@Composable+private fun HowToSteps(deviceName: String) {+    Row(+        modifier = Modifier.fillMaxWidth(),+        horizontalArrangement = Arrangement.spacedBy(20.dp, Alignment.CenterHorizontally),+    ) {+        StepCard(+            number = "1",+            title = stringResource(R.string.tv_howto_step1_title),+            body = stringResource(R.string.tv_howto_step1_body),+            icon = { IconTv() },+            modifier = Modifier.weight(1f),+        )+        StepCard(+            number = "2",+            title = stringResource(R.string.tv_howto_step2_title, deviceName),+            body = stringResource(R.string.tv_howto_step2_body),+            icon = { IconCast() },+            modifier = Modifier.weight(1f),+        )+        StepCard(+            number = "3",+            title = stringResource(R.string.tv_howto_step3_title),+            body = stringResource(R.string.tv_howto_step3_body),+            icon = { IconDialpad() },+            modifier = Modifier.weight(1f),+        )+    }+}++@Composable+private fun StepCard(+    number: String,+    title: String,+    body: String,+    icon: @Composable () -> Unit,+    modifier: Modifier = Modifier,+) {+    val scheme = MaterialTheme.colorScheme+    Column(+        modifier = modifier+            .background(scheme.surface, MaterialTheme.shapes.medium)+            .padding(24.dp),+        verticalArrangement = Arrangement.spacedBy(10.dp),+    ) {+        Row(+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            Box(+                modifier = Modifier+                    .size(44.dp)+                    .background(scheme.primaryContainer, CircleShape),+                contentAlignment = Alignment.Center,+            ) {+                Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {+                    TvIcon(icon)+                }+            }+            Text(+                text = number,+                style = MaterialTheme.typography.headlineSmall,+                color = scheme.primary,+            )+        }+        Text(+            text = title,+            style = MaterialTheme.typography.titleMedium,+            color = scheme.onSurface,+        )+        Text(+            text = body,+            style = MaterialTheme.typography.bodyMedium,+            color = scheme.onSurfaceVariant,+        )+    }+}++/**+ * The one-tap grant for auto-open, styled as a dismissible-looking hint card rather than a+ * blocking wall: the TV has two things to ask for at most, and a permissions gate would sit+ * between a user and a screen whose job is to wait.+ *+ * Reprobed on every resume so a grant made in Settings clears this without reopening the app.+ * Nothing here is focusable until the grant button appears, so initial focus goes there.+ */+@Composable+private fun AutoOpenHintCard() {+    val context = LocalContext.current+    val lifecycleOwner = LocalLifecycleOwner.current+    var canAutoOpen by remember { mutableStateOf(SpecialAccess.hasFullScreenIntent(context)) }+    DisposableEffect(lifecycleOwner) {+        val observer = LifecycleEventObserver { _, event ->+            if (event == Lifecycle.Event.ON_RESUME) {+                canAutoOpen = SpecialAccess.hasFullScreenIntent(context)+            }+        }+        lifecycleOwner.lifecycle.addObserver(observer)+        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+    }+    if (canAutoOpen) return+    val focusRequester = remember { FocusRequester() }+    Row(+        modifier = Modifier+            .background(MaterialTheme.colorScheme.surface, MaterialTheme.shapes.medium)+            .padding(horizontal = 20.dp, vertical = 12.dp),+        verticalAlignment = Alignment.CenterVertically,+        horizontalArrangement = Arrangement.spacedBy(16.dp),+    ) {+        Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {+            TvIcon { IconLock() }+        }+        Text(+            text = stringResource(R.string.tv_auto_open_hint),+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+            modifier = Modifier.weight(1f, fill = false),+        )+        TvButton(+            text = stringResource(R.string.tv_auto_open_grant),+            onClick = { SpecialAccess.requestFullScreenIntent(context) },+            primary = true,+            modifier = Modifier.focusRequester(focusRequester),+        )+    }+    TvInitialFocus(focusRequester)+}
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.ktindex 1dd3dc81a8..2bee3f8a6c 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt@@ -1,190 +1,157 @@ package com.vayunmathur.cast.tv.ui -import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column+import android.content.Intent+import android.provider.Settings import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable-import androidx.compose.runtime.DisposableEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp-import androidx.lifecycle.Lifecycle-import androidx.lifecycle.LifecycleEventObserver-import androidx.lifecycle.compose.LocalLifecycleOwner-import androidx.tv.material3.MaterialTheme-import androidx.tv.material3.Text import com.vayunmathur.cast.tv.R import com.vayunmathur.cast.tv.platform.ReceiverFailure import com.vayunmathur.cast.tv.platform.ReceiverPhase import com.vayunmathur.cast.tv.platform.ReceiverUiState-import com.vayunmathur.library.ui.SpecialAccess-import androidx.tv.material3.Button+import com.vayunmathur.library.tv.TvButton+import com.vayunmathur.library.tv.TvEmptyState+import com.vayunmathur.library.tv.TvInitialFocus+import com.vayunmathur.library.tv.TvLoading+import com.vayunmathur.library.ui.IconCastConnected+import com.vayunmathur.library.ui.IconScreenShare+import com.vayunmathur.library.ui.IconWarning  /**- * The idle and pairing screen.+ * Every full-screen state of the receiver that is not the picture itself.  *- * **On `androidx.tv`, and this paragraph used to argue the opposite.** The old reasoning was that- * nothing here is focusable - no list to move a D-pad through, no button to press - so Material 3's- * missing focus handling never came up, and the repo's rule that Material arrives only through- * `:library:ui` could stay intact. That held for exactly as long as this app had no controls. It now- * has a transport overlay driven from the television's remote, and building *that* on touch-first- * components while this screen stayed on a third design system would leave one app with two.- *- * So the whole of `cast:tv` is on `androidx.tv`: the same Material design language, with focus as a- * first-class concern rather than an afterthought. `:library:ui` remains on the compile classpath- * because the app convention plugin puts it there, and R8 strips what nothing references.- *- * The `AppScaffold` went with it, and is not replaced. A title bar reading "Cast TV" above a screen- * whose entire job is to show one sentence was furniture; the ten-foot rule is that everything on- * screen should be worth reading from a sofa.- *- * The background is painted here rather than in `CastTvTheme`, because the other thing that theme wraps- * is an overlay above a decoder surface and must stay transparent.- *- * Sizes are deliberately large: this is read from across a room, and a pair code the user has to walk- * up to the TV to make out is a pair code that makes the feature feel broken.+ * A dispatcher, not a layout: each arm is its own screen in its own file, sharing only the+ * theme. The picture gets `MirrorActivity`; the now-playing artwork screen lives there too,+ * beside the surface it accompanies. Nothing here paints a base background - the overlay case+ * above a decoder surface needs transparency, so screens that want colour say so themselves.  */ @Composable fun ReceiverContent(state: ReceiverUiState, modifier: Modifier = Modifier) {-    Column(-        modifier = modifier-            .fillMaxSize()-            .background(MaterialTheme.colorScheme.background)-            .padding(48.dp),-        verticalArrangement = Arrangement.spacedBy(24.dp, Alignment.CenterVertically),-        horizontalAlignment = Alignment.CenterHorizontally,-    ) {-        if (state.localNetworkBlocked) {-            Headline(stringResource(R.string.tv_local_network_blocked), isError = true)-            Detail(stringResource(R.string.tv_local_network_blocked_hint))-            return@Column-        }-        when (val phase = state.phase) {-            ReceiverPhase.Starting -> Headline(stringResource(R.string.tv_starting))+    if (state.localNetworkBlocked) {+        NetworkBlockedScreen(modifier)+        return+    }+    when (val phase = state.phase) {+        ReceiverPhase.Starting -> StartingScreen(modifier) -            ReceiverPhase.Advertising -> {-                Headline(stringResource(R.string.tv_ready_title))-                Detail(-                    stringResource(-                        R.string.tv_ready_hint,-                        state.deviceName.ifBlank { stringResource(R.string.tv_name_unknown) },-                    ),-                )-                AutoOpenPrompt()-            }+        ReceiverPhase.Advertising -> ReadyScreen(+            deviceName = state.deviceName.ifBlank { stringResource(R.string.tv_name_unknown) },+            networkLabel = state.networkLabel,+            modifier = modifier,+        ) -            is ReceiverPhase.Pairing -> {-                Detail(stringResource(R.string.tv_pair_from, phase.senderName))-                Headline(stringResource(R.string.tv_pair_title))-                // The code itself, as large as the type scale goes: it is the one thing on this-                // screen the user has to read from across a room and copy exactly.-                Text(-                    text = phase.code.chunked(3).joinToString("  "),-                    style = MaterialTheme.typography.displayLarge,-                    textAlign = TextAlign.Center,-                )-                if (phase.codeChanged) {-                    Detail(stringResource(R.string.tv_pair_new_code), isError = true)-                } else {-                    Detail(-                        pluralStringResource(-                            R.plurals.tv_pair_attempts,-                            phase.attemptsLeft,-                            phase.attemptsLeft,-                        ),-                    )-                }-            }+        is ReceiverPhase.Pairing -> PairingScreen(+            senderName = phase.senderName,+            code = phase.code,+            attemptsLeft = phase.attemptsLeft,+            codeChanged = phase.codeChanged,+            modifier = modifier,+        ) -            is ReceiverPhase.Connected ->-                Headline(stringResource(R.string.tv_paired, phase.senderName))+        // Paired; the stream is being set up. `MainActivity` moves on to `MirrorActivity` the+        // moment frames arrive, so this is a held breath rather than a destination.+        is ReceiverPhase.Connected -> ConnectedScreen(senderName = phase.senderName, modifier = modifier) -            // The mirror has its own full-screen Activity, so this is only ever seen for the-            // moment between the stream starting and that Activity coming up.-            is ReceiverPhase.Mirroring ->-                Headline(stringResource(R.string.tv_mirroring, phase.sourceName))+        // The mirror has its own full-screen Activity, so this is only ever seen for the+        // moment between the stream starting and that Activity coming up.+        is ReceiverPhase.Mirroring ->+            ConnectedScreen(senderName = phase.sourceName, mirroring = true, modifier = modifier) -            is ReceiverPhase.Failed -> Headline(-                stringResource(-                    when (phase.reason) {-                        ReceiverFailure.NoDecoder -> R.string.tv_no_decoder-                        ReceiverFailure.NoAudioDecoder -> R.string.tv_no_audio_decoder-                        ReceiverFailure.MissingCodecConfig ->-                            R.string.tv_missing_codec_config-                        ReceiverFailure.Handshake -> R.string.tv_stream_failed-                        ReceiverFailure.StreamEnded -> R.string.tv_stream_failed-                    },-                ),-                isError = true,-            )-        }+        is ReceiverPhase.Failed -> FailedScreen(reason = phase.reason, modifier = modifier)     } }  @Composable-private fun Headline(text: String, isError: Boolean = false) {-    Text(-        text = text,-        style = MaterialTheme.typography.headlineLarge,-        textAlign = TextAlign.Center,-        color = if (isError) {-            MaterialTheme.colorScheme.error-        } else {-            MaterialTheme.colorScheme.onSurface-        },+private fun StartingScreen(modifier: Modifier = Modifier) {+    TvLoading(+        modifier = modifier.fillMaxSize(),+        label = stringResource(R.string.tv_starting),     ) }  @Composable-private fun Detail(text: String, isError: Boolean = false) {-    Text(-        text = text,-        style = MaterialTheme.typography.titleMedium,-        textAlign = TextAlign.Center,-        color = if (isError) {-            MaterialTheme.colorScheme.error-        } else {-            MaterialTheme.colorScheme.onSurfaceVariant-        },+private fun ConnectedScreen(senderName: String, modifier: Modifier = Modifier, mirroring: Boolean = false) {+    val focusRequester = remember { FocusRequester() }+    TvInitialFocus(focusRequester)+    TvEmptyState(+        title = stringResource(+            if (mirroring) R.string.tv_mirroring else R.string.tv_paired,+            senderName,+        ),+        icon = { if (mirroring) IconScreenShare() else IconCastConnected() },+        modifier = modifier+            .fillMaxSize()+            .padding(horizontal = 48.dp),     ) }  /**- * The one-tap grant for auto-open, shown on the idle screen until full-screen-intent access is- * held.- *- * A `Button` rather than the phone-style permissions gate: the TV has two things to ask for- * at most and a blocking wall would sit between a user and a screen whose whole job is one- * sentence. Reprobed on every resume so a grant made in Settings clears this without reopening- * the app.+ * The receiver could not advertise itself: Android refused the mDNS registration, so no phone+ * will ever list this TV. Distinct from "nothing has connected yet" - the fix is a permission,+ * not opening the app on the phone.  */ @Composable-private fun AutoOpenPrompt() {+private fun NetworkBlockedScreen(modifier: Modifier = Modifier) {     val context = LocalContext.current-    val lifecycleOwner = LocalLifecycleOwner.current-    var canAutoOpen by remember { mutableStateOf(SpecialAccess.hasFullScreenIntent(context)) }-    DisposableEffect(lifecycleOwner) {-        val observer = LifecycleEventObserver { _, event ->-            if (event == Lifecycle.Event.ON_RESUME) {-                canAutoOpen = SpecialAccess.hasFullScreenIntent(context)-            }-        }-        lifecycleOwner.lifecycle.addObserver(observer)-        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }-    }-    if (canAutoOpen) return-    Detail(stringResource(R.string.tv_auto_open_hint))-    Button(onClick = { SpecialAccess.requestFullScreenIntent(context) }) {-        Text(stringResource(R.string.tv_auto_open_grant))-    }+    val focusRequester = remember { FocusRequester() }+    TvEmptyState(+        title = stringResource(R.string.tv_local_network_blocked),+        body = stringResource(R.string.tv_local_network_blocked_hint),+        icon = { IconWarning() },+        isError = true,+        action = {+            TvButton(+                text = stringResource(R.string.tv_local_network_open_settings),+                onClick = {+                    context.startActivity(+                        Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {+                            data = android.net.Uri.fromParts("package", context.packageName, null)+                        },+                    )+                },+                primary = true,+                modifier = Modifier.focusRequester(focusRequester),+            )+            TvInitialFocus(focusRequester)+        },+        modifier = modifier+            .fillMaxSize()+            .padding(horizontal = 48.dp),+    )+}++/**+ * Something the user has to know about, already a sentence rather than a code. Each failure has+ * a different answer, which is why the contract distinguishes them; the screen keeps the shared+ * shape and varies the copy.+ */+@Composable+private fun FailedScreen(reason: ReceiverFailure, modifier: Modifier = Modifier) {+    val message = stringResource(+        when (reason) {+            ReceiverFailure.NoDecoder -> R.string.tv_no_decoder+            ReceiverFailure.NoAudioDecoder -> R.string.tv_no_audio_decoder+            ReceiverFailure.MissingCodecConfig -> R.string.tv_missing_codec_config+            ReceiverFailure.Handshake -> R.string.tv_stream_failed+            ReceiverFailure.StreamEnded -> R.string.tv_stream_failed+        },+    )+    // No retry button to offer: every one of these is fixed by the phone trying again (a new+    // session) or by nothing the TV can do (no decoder). A button that re-runs nothing would+    // be the cruellest control on the screen.+    TvEmptyState(+        title = message,+        icon = { IconWarning() },+        isError = true,+        modifier = modifier+            .fillMaxSize()+            .padding(horizontal = 48.dp),+    ) }
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.ktindex 2bb11c1bc7..60fac93ac0 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/Theme.kt@@ -1,23 +1,22 @@ package com.vayunmathur.cast.tv.ui  import androidx.compose.runtime.Composable-import androidx.tv.material3.MaterialTheme-import androidx.tv.material3.darkColorScheme+import com.vayunmathur.library.tv.MaTvTheme+import com.vayunmathur.library.tv.TvAccent  /**  * The theme for every screen in this app.  *- * **Always dark, and not dynamic.** `DynamicTheme` was the wrong shape here twice over: a television- * has no wallpaper to derive a colour scheme from, and there is no light mode to offer because nobody- * has ever wanted a white screen filling a wall in a dim room. The old call site passed- * `darkTheme = true` unconditionally, which was that conclusion reached one argument short.+ * Always dark, keyed off the Cast blue accent, and shared with the other TV apps through+ * `:library:tv` rather than a local colour scheme.  *- * **Paints nothing.** Deliberately not `Surface`, and not a `Box` with the scheme's background either:+ * **Paints nothing.** Deliberately not `Surface`, and not a `Box` with the scheme's background:  * one of the two things wrapped in this theme is an overlay above a decoder surface, and anything- * opaque here would be a solid rectangle over the video for the whole session. Screens that want a- * background say so themselves - see `ReceiverContent`.+ * opaque here would be a solid rectangle over the video for the whole session. `MaTvTheme` only+ * installs the colour scheme and content colours (verified in `library/tv/TvTheme.kt`), so that+ * property carries over. Screens that want a background say so themselves.  */ @Composable fun CastTvTheme(content: @Composable () -> Unit) {-    MaterialTheme(colorScheme = darkColorScheme(), content = content)+    MaTvTheme(accent = TvAccent.Blue, content = content) }
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.ktindex bb9ce1c80d..2c2f0983d0 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt@@ -3,26 +3,13 @@ package com.vayunmathur.cast.tv.ui import android.text.format.DateUtils import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.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.size-import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableLongStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.runtime.withFrameMillis 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@@ -31,65 +18,32 @@ import androidx.compose.ui.unit.dp import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text import com.vayunmathur.cast.protocol.NowPlaying+import com.vayunmathur.cast.protocol.PlaybackAction+import com.vayunmathur.cast.protocol.PlaybackCommand import com.vayunmathur.cast.tv.R import com.vayunmathur.cast.tv.platform.PlaybackSnapshot+import com.vayunmathur.cast.tv.platform.ReceiverController+import com.vayunmathur.library.tv.TvIconButton+import com.vayunmathur.library.tv.TvSeekRow+import com.vayunmathur.library.ui.IconPause+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.IconSkipNext+import com.vayunmathur.library.ui.IconSkipPrevious  /**- * Owns the one per-frame clock a served session needs, and hands it down as a lambda.+ * The transport controls: a title block and seek row over a bottom gradient scrim, with icon+ * buttons for the actions the remote can take.  *- * [TransportOverlay] used to own its own `withFrameMillis` ticker, which was right while it was the- * only thing on screen that moved. The now-playing screen's lyrics need the same interpolated- * position and the same scrub-preview override, and two tickers would be two answers to one question.+ * **Transparent where it is not painted.** The scrim is the only background, a vertical gradient+ * that fades the picture through the controls; over audio (`scrim = false`) there is no paint+ * at all, because the caller already painted the window and the bar belongs to the same sheet+ * of colour as the cover and the lyrics above it.  *- * **Hoisted as a lambda, not as a value, and the distinction is the whole point.** Passing the number- * down would put every reader of it in the recomposition scope that invalidates sixty times a second -- * which on TV-class hardware means redrawing a bitmap and a full lyrics column per frame. Passing a- * lambda leaves the invalidation here, where the state is read, and lets each reader decide how much- * of itself depends on it.- *- * Keyed on the snapshot so every fresh one re-anchors, and the ticker stops while playback is paused:- * a frame callback per frame for a still bar would keep the panel awake for nothing.- */-@Composable-fun PlaybackClock(-    snapshot: PlaybackSnapshot,-    /** A scrub the user is composing, which overrides the clock entirely. Null when not scrubbing. */-    scrubPreviewMs: Long?,-    content: @Composable (positionMs: () -> Long) -> Unit,-) {-    var frameNowMs by remember { mutableLongStateOf(System.currentTimeMillis()) }-    LaunchedEffect(snapshot) {-        frameNowMs = System.currentTimeMillis()-        if (!snapshot.state.playing) return@LaunchedEffect-        while (true) {-            withFrameMillis { frameNowMs = System.currentTimeMillis() }-        }-    }-    content { scrubPreviewMs ?: snapshot.positionAt(frameNowMs) }-}--/**- * The transport controls: a bar at the bottom of whatever it is given.- *- * **Nothing here is focusable, and that is deliberate rather than an omission.** A media overlay is- * driven by the remote's dedicated keys and its D-pad as *gestures* - left seeks, up is volume - not by- * moving a focus ring between buttons. `MirrorActivity.dispatchKeyEvent` is therefore the whole input- * path, and this file is a read-only view of state. It is the one shape of TV UI where `androidx.tv`'s- * focus machinery has nothing to contribute, which is also why it is safe to draw over a decoder- * surface: no focus means no chance of the compositor being asked to redraw the video layer.- *- * Only mounted while the phone is reporting playback, so it cannot appear over a mirrored phone screen- * - there would be no transport to control.- *- * **It sizes itself to its content and lets the caller place it, rather than filling the window.** Over- * video it is aligned to the bottom of a `Box` and overlays the picture, which is the whole point of a- * scrim. For audio there is no picture, so `MirrorActivity` stacks it under the now-playing screen in a- * `Column` instead - and then the lyrics get exactly the height that is left, rather than the height- * left over from a constant somebody guessed at. Filling the window made that impossible to express.- *- * **The clock is not its own any more.** [positionMs] is read per frame and supplied by- * [PlaybackClock], which owns the ticker so that this and the now-playing screen's lyrics move against- * one number. A lambda rather than a `Long` for the reason [PlaybackClock] gives.+ * Key and focus semantics are unchanged from the old overlay: the remote's dedicated keys and+ * its D-pad as *gestures* are the whole input path (`MirrorActivity.dispatchKeyEvent`), and the+ * icon buttons here mirror those same commands for a remote whose `Media*` keys never arrive.+ * They are focusable tv-material targets, and focusing one must not move the seek preview - it+ * only shows where playback is.  */ @Composable fun TransportOverlay(@@ -102,17 +56,16 @@ fun TransportOverlay(     positionMs: () -> Long,     /** Whether a scrub is in progress, which thickens the bar. */     scrubbing: Boolean,+    modifier: Modifier = Modifier,     /**      * Whether to darken behind itself.      *-     * True over a picture, where the gradient is what keeps the frame visible through the controls and-     * the numbers legible against whatever happens to be behind them. **False for audio**, where there-     * is no picture to see through and the scrim would be a black band across the bottom of an-     * otherwise continuous surface - the caller has already painted the window, and the bar belongs to-     * the same sheet of colour as the cover and the lyrics above it.+     * True over a picture, where the gradient is what keeps the frame visible through the+     * controls and the numbers legible against whatever happens to be behind them. **False for+     * audio**, where there is no picture to see through and the scrim would be a black band+     * across the bottom of an otherwise continuous surface.      */     scrim: Boolean = true,-    modifier: Modifier = Modifier, ) {     val state = snapshot.state     val position = positionMs()@@ -132,60 +85,48 @@ fun TransportOverlay(                 },             )             .padding(horizontal = 48.dp, vertical = 24.dp),-        verticalArrangement = Arrangement.spacedBy(10.dp),+        verticalArrangement = Arrangement.spacedBy(12.dp),     ) {-        Row(-            modifier = Modifier.fillMaxWidth(),-            horizontalArrangement = Arrangement.SpaceBetween,-            verticalAlignment = Alignment.CenterVertically,-        ) {-            Headline(-                nowPlaying = nowPlaying,-                sourceName = sourceName,-                modifier = Modifier.weight(1f),+        TitleBlock(+            nowPlaying = nowPlaying,+            sourceName = sourceName,+            speed = state.speed,+        )++        if (state.durationMs > 0) {+            TvSeekRow(+                elapsed = DateUtils.formatElapsedTime((position / 1_000).coerceAtLeast(0)),+                total = DateUtils.formatElapsedTime((state.durationMs / 1_000).coerceAtLeast(0)),+                progress = (position.toFloat() / state.durationMs).coerceIn(0f, 1f),+                active = scrubbing,             )-            if (state.speed != 1f) {-                Text(-                    text = stringResource(R.string.tv_transport_speed, formatSpeed(state.speed)),-                    style = MaterialTheme.typography.titleMedium,-                    color = Color.White.copy(alpha = 0.8f),-                )-            }         } -        SeekBar(-            positionMs = position,-            durationMs = state.durationMs,-            scrubbing = scrubbing,-        )-         Row(             modifier = Modifier.fillMaxWidth(),-            horizontalArrangement = Arrangement.SpaceBetween,+            horizontalArrangement = Arrangement.spacedBy(12.dp),+            verticalAlignment = Alignment.CenterVertically,         ) {-            Text(-                text = elapsed(position),-                style = MaterialTheme.typography.bodyLarge,-                color = Color.White,+            // **The action the centre key will take.** Read as a status it would be the other+            // way round - which is exactly why it has to match the button it sits next to.+            // Buffering is its own case: a stall and a pause look identical on a frozen+            // picture, and only one of them is the user's own doing.+            TvIconButton(+                onClick = { ReceiverController.send(PlaybackCommand(PlaybackAction.Previous)) },+                icon = { IconSkipPrevious() },+                enabled = state.hasPrevious,             )-            // **The action the centre key will take, not a description of the state.** Read as a-            // status it would be the other way round, and both readings are defensible - which is-            // exactly why it has to match the button it sits next to. Buffering is its own case:-            // a stall and a pause look identical on a frozen picture, and only one of them is the-            // user's own doing.-            Text(-                text = when {-                    state.buffering -> "…"-                    state.playing -> "❚❚"-                    else -> "▶"-                },-                style = MaterialTheme.typography.bodyLarge,-                color = Color.White,+            // Always enabled, like the centre key it mirrors: the gesture path sends Toggle+            // unconditionally, and the button must never disagree with it.+            TvIconButton(+                onClick = { ReceiverController.send(PlaybackCommand(PlaybackAction.Toggle)) },+                icon = { if (state.playing) IconPause() else IconPlay() },+                size = 64.dp,             )-            Text(-                text = if (state.durationMs > 0) elapsed(state.durationMs) else "",-                style = MaterialTheme.typography.bodyLarge,-                color = Color.White,+            TvIconButton(+                onClick = { ReceiverController.send(PlaybackCommand(PlaybackAction.Next)) },+                icon = { IconSkipNext() },+                enabled = state.hasNext,             )         } @@ -200,20 +141,21 @@ fun TransportOverlay( /**  * What is playing, or who is casting when that is all the television knows.  *- * **The title replaces the app's name rather than sitting beside it.** "Receiving from YouPipe" was- * the most the receiver could say when nothing crossed the protocol but pixels; with a title in hand- * it is the less useful of the two, and a user looking at a video already knows which app they- * started. The fallback keeps it for an old phone, an app that sends no metadata, and the moment- * before the first snapshot lands.+ * **The title replaces the app's name rather than sitting beside it.** "Receiving from YouPipe"+ * was the most the receiver could say when nothing crossed the protocol but pixels; with a+ * title in hand it is the less useful of the two, and a user looking at a video already knows+ * which app they started. The fallback keeps it for an old phone, an app that sends no+ * metadata, and the moment before the first snapshot lands.  *- * **Every field it has, and no field it does not**, which is why there is no video-shaped branch here:- * a track fills all three lines and a video fills two, because `album` is what a video has nothing to- * put in. Stacked rather than joined onto one line - a video title is long and a channel name is- * short, and one line holding both would truncate the title to fit something that is not the title.+ * **Every field it has, and no field it does not**, which is why there is no video-shaped+ * branch here: a track fills all three lines and a video fills two, because `album` is what a+ * video has nothing to put in. Stacked rather than joined onto one line - a video title is long+ * and a channel name is short, and one line holding both would truncate the title to fit+ * something that is not the title.  */ @Composable-private fun Headline(nowPlaying: NowPlaying?, sourceName: String, modifier: Modifier) {-    Column(modifier = modifier) {+private fun TitleBlock(nowPlaying: NowPlaying?, sourceName: String, speed: Float) {+    Column {         Text(             text = nowPlaying?.title.orEmpty().ifBlank { sourceName },             style = MaterialTheme.typography.titleLarge,@@ -221,14 +163,21 @@ private fun Headline(nowPlaying: NowPlaying?, sourceName: String, modifier: Modi             maxLines = 1,             overflow = TextOverflow.Ellipsis,         )-        Subtitle(nowPlaying?.author.orEmpty(), alpha = 0.7f)-        Subtitle(nowPlaying?.album.orEmpty(), alpha = 0.5f)+        TransportSubtitle(nowPlaying?.author.orEmpty(), alpha = 0.7f)+        TransportSubtitle(nowPlaying?.album.orEmpty(), alpha = 0.5f)+        if (speed != 1f) {+            Text(+                text = stringResource(R.string.tv_transport_speed, formatSpeed(speed)),+                style = MaterialTheme.typography.titleMedium,+                color = Color.White.copy(alpha = 0.8f),+            )+        }     } }  /** One line beneath the title, or nothing at all when there is nothing to put on it. */ @Composable-private fun Subtitle(text: String, alpha: Float) {+private fun TransportSubtitle(text: String, alpha: Float) {     if (text.isBlank()) return     Text(         text = text,@@ -239,52 +188,6 @@ private fun Subtitle(text: String, alpha: Float) {     ) } -/**- * The bar, drawn as nested boxes rather than as a `Slider`.- *- * A `Slider` is a touch control: it wants a drag gesture and a focusable thumb, and on a television it- * would offer both to a device that has neither. What is actually needed is a progress indicator that- * happens to be movable by the remote, and the remote handling lives in the Activity.- *- * A stream with no known duration gets no bar at all, rather than an empty one that looks broken.- */-@Composable-private fun SeekBar(positionMs: Long, durationMs: Long, scrubbing: Boolean) {-    if (durationMs <= 0) return-    val progress = (positionMs.toFloat() / durationMs).coerceIn(0f, 1f)-    Box(-        modifier = Modifier-            .fillMaxWidth()-            .height(if (scrubbing) 10.dp else 6.dp)-            .clip(RoundedCornerShape(50))-            .background(Color.White.copy(alpha = 0.25f)),-        contentAlignment = Alignment.CenterStart,-    ) {-        Box(-            modifier = Modifier-                .fillMaxHeight()-                .fillMaxWidth(progress)-                .background(MaterialTheme.colorScheme.primary),-        )-        // The thumb rides the end of the filled track, which needs no measured width to place.-        Box(-            modifier = Modifier.fillMaxWidth(progress),-            contentAlignment = Alignment.CenterEnd,-        ) {-            Box(-                modifier = Modifier-                    .size(if (scrubbing) 20.dp else 14.dp)-                    .clip(RoundedCornerShape(50))-                    .background(MaterialTheme.colorScheme.primary),-            )-        }-    }-}--/** `H:MM:SS` past an hour, `M:SS` below it - which is what every other player on the panel does. */-private fun elapsed(positionMs: Long): String =-    DateUtils.formatElapsedTime((positionMs / 1_000).coerceAtLeast(0))- /** "2" rather than "2.0", "1.5" rather than "1.50". Matches YouPipe's own speed readout. */ private fun formatSpeed(speed: Float): String {     val rounded = Math.round(speed * 100f) / 100f
cast/tv/src/main/res/values/strings.xml
diff --git a/cast/tv/src/main/res/values/strings.xml b/cast/tv/src/main/res/values/strings.xmlindex 184bd3c320..252ea3ba59 100644--- a/cast/tv/src/main/res/values/strings.xml+++ b/cast/tv/src/main/res/values/strings.xml@@ -35,6 +35,8 @@     <!-- Now playing, for an audio-only session where there is no picture -->     <string name="tv_now_playing_no_artwork">No cover art</string>     <string name="tv_now_playing_artwork">Cover art</string>+    <string name="tv_now_playing_paused">Paused</string>+    <string name="tv_now_playing_buffering">Buffering…</string>      <!-- Foreground service -->     <string name="tv_notification_channel_name">Receiving</string>@@ -50,4 +52,18 @@     <!-- Auto-open prompt on the idle screen, until full-screen-intent access is granted. -->     <string name="tv_auto_open_hint">This TV can open itself when a phone starts casting. Allow it in Settings to turn that on.</string>     <string name="tv_auto_open_grant">Allow auto-open</string>++    <!-- Ready screen: the three how-to steps. Step 2 names this TV. -->+    <string name="tv_howto_step1_title">Open Cast on your phone</string>+    <string name="tv_howto_step1_body">Join the same Wi-Fi network as this TV.</string>+    <string name="tv_howto_step2_title">Pick %1$s</string>+    <string name="tv_howto_step2_body">Choose this TV from the device list.</string>+    <string name="tv_howto_step3_title">Enter the code shown here</string>+    <string name="tv_howto_step3_body">Type the six digits into your phone to connect.</string>+    <!-- Ready screen footer: privacy facts, plus the network the receiver could read. -->+    <string name="tv_privacy_facts">Encrypted end-to-end · Stays on your Wi-Fi · No account</string>+    <string name="tv_network_line">On %1$s</string>++    <!-- The receiver could not advertise itself: open the app Settings page to grant access. -->+    <string name="tv_local_network_open_settings">Open Settings</string> </resources>