Modern Apps git

← Modern-Apps.git

cast: fit the TV pairing code to the screen instead of clipping it (#919)

Commit
214ff71a34d9de2388eaf732e1835dab42d1d741
Author
Vayun Mathur <[email protected]>
When
2026-11-14 14:02 UTC (22 days ago)
Parents
104fa41
Symptom: on a Thomson Android TV 14 set (v2.6.11b), the receiver's
pairing card showed only "632" of the six-digit code, with the bottoms
of the digits cut off, so the user could not pair from their phone.

Root cause: PairingScreen drew the code as "632  145" in 96 sp
monospace with 4 sp tracking, on one tv-material Text with
maxLines = 1 and the default soft wrap. Most Android TVs report a
960x540 dp screen whatever their panel (720p tvdpi, 1080p xhdpi,
4K xxxhdpi); there the card is 0.62 x (960 - 2 x 48) - 2 x 32 =
~472 dp wide, but the code needs 8 x (0.6 em x 96 + 4) = ~493 dp
(Droid Sans Mono advance), and more at any font scale above 1.0.
So the text soft-wrapped at the gap and maxLines = 1 silently
dropped the second group. That overflow also turned on clipping, and
the line box was displayLarge's 64 sp line height (never adjusted
when the size was overridden to 96 sp), so the digits were clipped
at the bottom as well. Bigger TVs (1280+ dp wide) had room, which is
why it did not show everywhere.

Fix (cast/tv only; the phone side only has a code input field, it
never displays the code, so it is unchanged and nothing on the wire
changes):
- The code is a foundation BasicText with TextAutoSize.StepBased
  (24..96 sp, 2 sp steps): as large as before where it fits, shrunk
  until the whole code fits the card's width and the height left to
  it otherwise.
- softWrap = false, so the two groups can never be split onto a
  dropped second line.
- Line height (1.2 em) and tracking (0.04 em) are relative to the
  chosen size, so the line box is always taller than the digits.
- The code takes weight(1f, fill = false) in the card, so at large
  font scales the digits shrink instead of pushing the tries-left /
  new-code line off the card, and the sender line is capped at two
  lines (ellipsised) so a long device name cannot squeeze the code
  out.
Rejected: shrinking the fixed 96 sp size or widening the card -
either only moves the breakpoint to another resolution/font scale.

User-visible: the full code always shows on one line, inside the
overscan-safe margins, on every TV resolution and font scale; on
960x540 dp TVs it is ~92 sp instead of a clipped 96 sp.

Verified: new Robolectric PairingCodeFitTest (native graphics, real
text measurement) renders the pairing screen at 960x540 dp (tvdpi,
xhdpi, xxxhdpi), 1280x720 dp hdpi and 1920x1080 dp mdpi, each at
font scale 1.0/1.15/1.3/1.5/2.0 (linear, the harsher case), plus a
long sender name with the new-code notice at 2.0, and asserts one
unclipped line containing every digit, a line box at least the
glyph height, a legible size, the code inside the 48/28 dp safe
area and the line below it still visible.
On the unfixed PairingScreen all three tests fail at the first
960x540 dp case at font scale 1.0 ("code dropped a line or
overflowed its height"), reproducing the report; with the fix,
:cast:tv:testDevUnitTest (89 tests, 0 failures) and :cast:tv:lint
pass in the toolchain container.

Diff

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.ktindex e42c897f9d..79dce7262d 100644--- 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.kt@@ -6,6 +6,8 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.BasicText+import androidx.compose.foundation.text.TextAutoSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -13,7 +15,9 @@ 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.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@@ -30,6 +34,12 @@ import com.vayunmathur.library.tv.TvDimens  *  * 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.+ *+ * The code is measured to fit, never assumed to (#919): most Android TVs, whatever their panel,+ * report a 960x540 dp screen, and the card is only ~470 dp wide there. The code takes whatever+ * height the other lines leave (so a large font scale shrinks the digits instead of pushing the+ * tries-left line off the card), and the sender line is capped at two lines so a long device+ * name cannot squeeze the code out.  */ @Composable fun PairingScreen(@@ -66,6 +76,8 @@ fun PairingScreen(                 style = MaterialTheme.typography.titleLarge,                 color = scheme.onSurface,                 textAlign = TextAlign.Center,+                maxLines = SENDER_MAX_LINES,+                overflow = TextOverflow.Ellipsis,             )             Text(                 text = stringResource(R.string.tv_pair_title),@@ -73,7 +85,7 @@ fun PairingScreen(                 color = scheme.onSurfaceVariant,                 textAlign = TextAlign.Center,             )-            Code(code)+            Code(code, Modifier.weight(1f, fill = false))             if (codeChanged) {                 Text(                     text = stringResource(R.string.tv_pair_new_code),@@ -93,25 +105,45 @@ fun PairingScreen(     } } -/** The six digits, huge and monospaced, grouped the way they are read out. */+/**+ * The six digits, huge and monospaced, grouped the way they are read out.+ *+ * Auto-sized: as large as [CODE_MAX_SIZE_SP] allows, shrunk until the whole code fits the card's+ * width and the height left to it. Never wrapped: `softWrap = false` keeps "123  456" on one line,+ * where the old `maxLines = 1` with soft wrap on broke at the gap and silently dropped the second+ * group (#919). Line height and tracking are in `em` so they follow the chosen size, and the line+ * box is taller than the glyphs, so nothing is clipped at the baseline either (the old 64 sp+ * `displayLarge` line height under 96 sp digits cut their bottoms off once the text overflowed).+ */ @Composable private fun Code(code: String, modifier: Modifier = Modifier) {-    Text(+    BasicText(         text = code.chunked(CODE_CHUNK).joinToString(separator = CODE_GAP),         style = MaterialTheme.typography.displayLarge.copy(             fontFamily = FontFamily.Monospace,-            fontSize = CODE_SIZE_SP.sp,-            letterSpacing = CODE_LETTER_SPACING_SP.sp,+            fontSize = CODE_MAX_SIZE_SP.sp,+            lineHeight = CODE_LINE_HEIGHT_EM.em,+            letterSpacing = CODE_LETTER_SPACING_EM.em,+            color = MaterialTheme.colorScheme.onSurface,+            textAlign = TextAlign.Center,         ),-        color = MaterialTheme.colorScheme.onSurface,-        textAlign = TextAlign.Center,         maxLines = 1,+        softWrap = false,+        autoSize = TextAutoSize.StepBased(+            minFontSize = CODE_MIN_SIZE_SP.sp,+            maxFontSize = CODE_MAX_SIZE_SP.sp,+            stepSize = CODE_SIZE_STEP_SP.sp,+        ),         modifier = modifier,     ) }  private const val CODE_CHUNK = 3 private const val CODE_GAP = "  "-private const val CODE_SIZE_SP = 96-private const val CODE_LETTER_SPACING_SP = 4+private const val CODE_MAX_SIZE_SP = 96+private const val CODE_MIN_SIZE_SP = 24+private const val CODE_SIZE_STEP_SP = 2+private const val CODE_LINE_HEIGHT_EM = 1.2f+private const val CODE_LETTER_SPACING_EM = 0.04f private const val CODE_CARD_WIDTH_FRACTION = 0.62f+private const val SENDER_MAX_LINES = 2
cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PairingCodeFitTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PairingCodeFitTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PairingCodeFitTest.ktnew file mode 100644index 0000000000..4930e7e65e--- /dev/null+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/ui/PairingCodeFitTest.kt@@ -0,0 +1,153 @@+package com.vayunmathur.cast.tv.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.semantics.SemanticsActions+import androidx.compose.ui.semantics.SemanticsNode+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.text.TextLayoutResult+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.dp+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * #919: on a Thomson Android TV the pairing screen showed "632" instead of "632  145", with the+ * bottoms of the digits cut off.+ *+ * Real text measurement (native graphics), so these check what the TV actually draws rather than+ * the semantics text, which is the full code however much of it is visible. Every configuration+ * is a TV screen as Android reports it - most panels, 720p, 1080p and 4K alike, come out as+ * 960x540 dp at their density - times a font scale. Font scale is applied linearly (no+ * Android 14 non-linear curve), which is the harsher case for 96 sp digits.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@Config(application = android.app.Application::class, qualifiers = "w1920dp-h1080dp-mdpi")+class PairingCodeFitTest {+    @get:Rule val rule = createComposeRule()++    private data class Screen(val name: String, val widthDp: Int, val heightDp: Int, val density: Float)++    private data class Case(val screen: Screen, val fontScale: Float) {+        override fun toString() = "${screen.name} ${screen.widthDp}x${screen.heightDp}dp fontScale=$fontScale"+    }++    private val screens = listOf(+        Screen("720p tvdpi", 960, 540, 1.33125f),+        Screen("1080p xhdpi", 960, 540, 2f),+        Screen("4K xxxhdpi", 960, 540, 4f),+        Screen("1080p hdpi", 1280, 720, 1.5f),+        Screen("1080p mdpi", 1920, 1080, 1f),+    )+    private val fontScales = listOf(1f, 1.15f, 1.3f, 1.5f, 2f)++    private var case by mutableStateOf(Case(screens.first(), 1f))+    private var sender by mutableStateOf("Pixel 6 Pro")+    private var codeChanged by mutableStateOf(false)++    private fun show() {+        rule.setContent {+            val c = case+            CompositionLocalProvider(LocalDensity provides Density(c.screen.density, c.fontScale)) {+                Box(Modifier.requiredSize(c.screen.widthDp.dp, c.screen.heightDp.dp).testTag(SCREEN)) {+                    CastTvTheme { PairingScreen(sender, CODE, attemptsLeft = 2, codeChanged = codeChanged) }+                }+            }+        }+    }++    private fun SemanticsNode.textLayout(): TextLayoutResult {+        val results = mutableListOf<TextLayoutResult>()+        config[SemanticsActions.GetTextLayoutResult].action!!.invoke(results)+        return results.single()+    }++    /** The whole code is drawn on one unclipped line, inside the overscan-safe area, at a size readable across a room. */+    private fun assertCodeFits(minGlyphDp: Float) {+        rule.waitForIdle()+        val screen = rule.onNodeWithTag(SCREEN).fetchSemanticsNode()+        val node = rule.onNodeWithText(SHOWN).fetchSemanticsNode()+        val layout = node.textLayout()+        val d = case.screen.density+        assertEquals(1, layout.lineCount, "$case: code wrapped")+        assertFalse(layout.didOverflowWidth, "$case: code wider than its card (${layout.size.width}px)")+        assertFalse(layout.didOverflowHeight, "$case: code dropped a line or overflowed its height")+        assertFalse(layout.hasVisualOverflow, "$case: code is clipped")+        assertEquals(SHOWN.length, layout.getLineEnd(0, visibleEnd = true), "$case: not every digit is on the visible line")+        val glyphPx = with(layout.layoutInput.density) { layout.layoutInput.style.fontSize.toPx() }+        val linePx = layout.getLineBottom(0) - layout.getLineTop(0)+        assertTrue(linePx >= glyphPx, "$case: line box ${linePx}px shorter than the ${glyphPx}px digits, so they are cut off")+        assertTrue(glyphPx / d >= minGlyphDp, "$case: digits only ${glyphPx / d}dp tall")+        val safe = Rect(+            screen.boundsInRoot.left + SAFE_H_DP * d - 1,+            screen.boundsInRoot.top + SAFE_V_DP * d - 1,+            screen.boundsInRoot.right - SAFE_H_DP * d + 1,+            screen.boundsInRoot.bottom - SAFE_V_DP * d + 1,+        )+        val drawn = node.boundsInRoot+        assertTrue(+            drawn.left >= safe.left && drawn.right <= safe.right && drawn.top >= safe.top && drawn.bottom <= safe.bottom,+            "$case: code $drawn outside the overscan-safe area $safe",+        )+    }++    private fun assertBelowCodeVisible(text: String) {+        val screen = rule.onNodeWithTag(SCREEN).fetchSemanticsNode().boundsInRoot+        val node = rule.onNodeWithText(text).fetchSemanticsNode()+        assertTrue(node.boundsInRoot.height > 0f && node.boundsInRoot.bottom <= screen.bottom, "$case: \"$text\" pushed off screen")+        assertFalse(node.textLayout().hasVisualOverflow, "$case: \"$text\" clipped")+    }++    @Test fun codeFitsEveryTvScreenAndFontScale() {+        show()+        for (screen in screens) for (scale in fontScales) {+            case = Case(screen, scale)+            assertCodeFits(minGlyphDp = 48f)+            assertBelowCodeVisible("2 attempts left")+        }+    }++    @Test fun codeFitsTheIssueTvAtDefaultFontScale() {+        // The configuration the reporter's Thomson set most likely runs: 1080p panel, xhdpi.+        show()+        case = Case(screens[1], 1f)+        assertCodeFits(minGlyphDp = 80f)+    }++    @Test fun codeSurvivesLongSenderNameAndChangedCodeNoticeAtLargestFontScale() {+        sender = "Living room projector belonging to the whole family upstairs (Pixel 6 Pro)"+        codeChanged = true+        show()+        for (screen in screens.filter { it.widthDp == 960 }) {+            case = Case(screen, 2f)+            assertCodeFits(minGlyphDp = 40f)+            assertBelowCodeVisible("That code was wrong three times, so here is a new one.")+        }+    }++    private companion object {+        const val CODE = "632145"+        const val SHOWN = "632  145"+        const val SCREEN = "screen"+        const val SAFE_H_DP = 48f+        const val SAFE_V_DP = 28f+    }+}