Modern Apps git

← Modern-Apps.git

cast/tv: fix all lint findings

Commit
0428bb8276e09c031ae94b27cbd882c7cd542ca8
Author
Vayun Mathur <[email protected]>
When
2026-11-17 05:20 UTC (19 days ago)
Parents
07d7c02
Fix every lint warning reported for the cast/tv module's own sources by :cast:tv:lintDev, now 0 errors / 0 warnings for cast/tv/** (remaining report entries are transitive library findings owned by other clusters).

RestrictedApi (11) + GestureBackNavigation: fixed for real in MirrorActivity — the dispatchKeyEvent override is gone; D-pad/media keys are handled in onKeyDown/onKeyUp, and BACK dismisses the overlay through an OnBackPressedCallback that is enabled only while dismissible controls are visible, otherwise finishing the activity as before. StaticFieldLeak: ContentPlayer no longer stores a Context at all — its constructor dropped the property and the application context is passed to the ExoPlayer builder only at build time, so the process-wide ReceiverController can never retain an activity or service context (call site and both ContentPlayer tests updated). PackageStructure: ReceiverNavigation renamed to Navigation, and receiverRouteFor moved out of Route.kt into platform/ReceiverRoute.kt.

No suppressions added; no lint config or baseline changed.

Verified: ./gradlew :cast:tv:lintDev (0 own-module errors/warnings) and :cast:tv:testDevUnitTest green (141 tests).

Diff

cast/tv/src/main/java/com/vayunmathur/cast/tv/MainActivity.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/MainActivity.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/MainActivity.ktindex f1b967f4a6..b11e2249cb 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/MainActivity.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/MainActivity.kt@@ -52,6 +52,6 @@ class MainActivity : MaActivity() {     @Composable     override fun Content() {         val state by ReceiverController.state.collectAsState()-        ReceiverNavigation(state)+        Navigation(state)     } }
cast/tv/src/main/java/com/vayunmathur/cast/tv/Navigation.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/Navigation.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/Navigation.ktindex 3ab2e43d6b..bcb5af7d12 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/Navigation.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/Navigation.kt@@ -5,6 +5,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.vayunmathur.cast.tv.platform.ReceiverUiState+import com.vayunmathur.cast.tv.platform.receiverRouteFor import com.vayunmathur.cast.tv.ui.ReceiverContent import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack@@ -25,7 +26,7 @@ import com.vayunmathur.library.util.rememberNavBackStack  * underneath it.  */ @Composable-fun ReceiverNavigation(state: ReceiverUiState, modifier: Modifier = Modifier) {+fun Navigation(state: ReceiverUiState, modifier: Modifier = Modifier) {     val target = receiverRouteFor(state.phase)     val backStack = rememberNavBackStack<Route>(target)     // The phase drives the destination. A mismatch also covers recreation,
cast/tv/src/main/java/com/vayunmathur/cast/tv/Route.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/Route.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/Route.ktindex 5d98ccba27..7b4fd2442b 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/Route.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/Route.kt@@ -1,21 +1,21 @@ package com.vayunmathur.cast.tv  import com.vayunmathur.cast.tv.platform.ReceiverFailure-import com.vayunmathur.cast.tv.platform.ReceiverPhase import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable  /**  * The receiver's screens as typed destinations.  *- * [ReceiverPhase] stays the session engine's state: `ReceiverController`- * and its media loops write phases as sockets and decoders move, and this- * graph is only their projection onto the screen. The stack is always one- * deep (see Navigation.kt) — there is no back behaviour between receiver- * states, nobody navigates a TV back from Paired to Pairing — but typed- * destinations buy arguments that cannot drift from the phase that produced- * them, and a stack that restores the right screen on recreation instead- * of restarting from [Starting].+ * `ReceiverPhase` (in platform/) stays the session engine's state:+ * `ReceiverController` and its media loops write phases as sockets and+ * decoders move, and this graph is only their projection onto the screen+ * (see `receiverRouteFor` in platform/ReceiverRoute.kt). The stack is+ * always one deep (see Navigation.kt) — there is no back behaviour between+ * receiver states, nobody navigates a TV back from Paired to Pairing — but+ * typed destinations buy arguments that cannot drift from the phase that+ * produced them, and a stack that restores the right screen on recreation+ * instead of restarting from [Starting].  */ @Serializable sealed interface Route : NavKey {@@ -45,25 +45,3 @@ sealed interface Route : NavKey {     data class Failed(val reason: ReceiverFailure) : Route } -/**- * The phase-to-destination projection.- *- * [ReceiverPhase.Mirroring] has no destination of its own: the picture- * lives in `MirrorActivity`, launched by `MainActivity` the moment frames- * arrive. Underneath it the stack holds [Route.Connected] naming the- * source, which is also the held-breath screen seen in the moment between- * the stream starting and that Activity coming up.- */-fun receiverRouteFor(phase: ReceiverPhase): Route = when (phase) {-    ReceiverPhase.Starting -> Route.Starting-    ReceiverPhase.Advertising -> Route.Ready-    is ReceiverPhase.Pairing -> Route.Pairing(-        senderName = phase.senderName,-        code = phase.code,-        attemptsLeft = phase.attemptsLeft,-        codeChanged = phase.codeChanged,-    )-    is ReceiverPhase.Connected -> Route.Connected(phase.senderName)-    is ReceiverPhase.Mirroring -> Route.Connected(phase.sourceName)-    is ReceiverPhase.Failed -> Route.Failed(phase.reason)-}
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.ktindex 231bf3ca93..e2c6a57817 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ContentPlayer.kt@@ -45,7 +45,6 @@ private const val TAG = "ContentPlayer"  */ @OptIn(UnstableApi::class) class ContentPlayer(-    private val context: Context,     private val session: ContentSession, ) { @@ -135,7 +134,7 @@ class ContentPlayer(      * and an expired resource that produces no error and no picture is the hardest kind of fault to      * attribute.      */-    fun start(onError: (String) -> Unit): Boolean {+    fun start(context: Context, onError: (String) -> Unit): Boolean {         val fingerprint = ProtocolBase64.decode(session.certificateFingerprint)         if (fingerprint == null || fingerprint.size != FINGERPRINT_BYTES) {             Log.status(TAG, "the phone sent an unusable certificate fingerprint")@@ -155,7 +154,7 @@ class ContentPlayer(             // get one. A redirect is never legitimate here.             .setAllowCrossProtocolRedirects(false) -        val built = ExoPlayer.Builder(context)+        val built = ExoPlayer.Builder(context.applicationContext)             .setMediaSourceFactory(DefaultMediaSourceFactory(http))             .build()         built.addListener(object : Player.Listener {
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 0239efc632..783add42b8 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@@ -8,6 +8,7 @@ import android.view.SurfaceView import android.view.ViewGroup import android.widget.FrameLayout import androidx.activity.ComponentActivity+import androidx.activity.OnBackPressedCallback import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -56,13 +57,13 @@ private const val TAG = "MirrorActivity"  * `scaling: "sender"` and will not pad for you. Owning the receiver means the phone can send its own  * aspect ratio at full resolution and the TV pads it - so none of the encoded frame is wasted.  *- * **This is also the app's whole input surface.** [dispatchKeyEvent] handles the remote directly rather+ * **This is also the app's whole input surface.** [onKeyDown]/[onKeyUp] handle the remote directly rather  * than moving a focus ring between buttons, because a media overlay's D-pad presses are gestures -  * left seeks, up is volume - and there is nothing to focus. Keys are only claimed while a phone is  * actually reporting playback, so screen mirroring keeps the ordinary behaviour of every key.  *  * **A press while the controls are hidden wakes them rather than toggling playback.** See- * [dispatchKeyEvent]; an audio-only session never has hidden controls at all, because there is no+ * [onKeyDown]; an audio-only session never has hidden controls at all, because there is no  * picture for them to get out of the way of.  */ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {@@ -130,8 +131,23 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {      private var hideJob: Job? = null +    /**+     * Back dismisses the controls before it leaves the session (see+     * [onKeyDown]). Registered as a callback rather than intercepted+     * as a raw KEYCODE_BACK in the key dispatch, so predictive-back handling+     * stays with the framework; enabled only while dismissible controls are+     * on screen, otherwise back finishes the Activity as usual.+     */+    private val backPressedCallback = object : OnBackPressedCallback(false) {+        override fun handleOnBackPressed() {+            hideOverlay()+        }+    }+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        onBackPressedDispatcher.addCallback(this, backPressedCallback)+        updateBackCallback()         surfaceView = SurfaceView(this).apply { holder.addCallback(this@MirrorActivity) }         // An audio-only session has nothing to draw. The surface is not merely hidden but never         // added: an unattached SurfaceView creates no surface, so `surfaceCreated` never fires and@@ -180,6 +196,7 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {                     // Activity is built, and this is the first moment the session is known for certain.                     overlayPinned = !state.phase.hasVideo                     if (overlayPinned) overlayVisible = true+                    updateBackCallback()                     // Before the letterbox, because switching the panel changes the size the                     // letterbox is computed against - and the layout listener installed above will                     // recompute it once the switch lands.@@ -293,26 +310,27 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {      * The remote, in full.      *      * Only claims a key while the phone is reporting playback - otherwise every one of these falls-     * through to the system, which is what a mirrored phone screen needs. `BACK` is the exception worth-     * pointing at: it dismisses the controls before it will leave the session, because a user who has-     * just brought up a seek bar and presses back means "put that away", not "stop watching".+     * through to the system, which is what a mirrored phone screen needs. `BACK` is not handled+     * in the key handlers at all: [backPressedCallback] dismisses the controls before back will leave the+     * session, because a user who has just brought up a seek bar and presses back means+     * "put that away", not "stop watching".      *      * Left and right accumulate into [scrubPreviewMs] and commit on release; everything else is one      * message per press. `ACTION_MULTIPLE` is not handled: a held D-pad repeats as `ACTION_DOWN`.      */-    override fun dispatchKeyEvent(event: KeyEvent): Boolean {-        val playback = ReceiverController.state.value.playback-            ?: return super.dispatchKeyEvent(event)--        if (event.keyCode == KeyEvent.KEYCODE_BACK) return handleBack(event)--        // Committing the scrub is the *release*, so it is handled before the reveal below - a release-        // must not be mistaken for a fresh press.-        if (event.action == KeyEvent.ACTION_UP && isScrubKey(event.keyCode)) {+    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {+        ReceiverController.state.value.playback ?: return super.onKeyUp(keyCode, event)+        // Committing the scrub is the *release*: the key-up half of a scrub press.+        if (isScrubKey(keyCode)) {             commitScrub()             return true         }-        if (event.action != KeyEvent.ACTION_DOWN) return super.dispatchKeyEvent(event)+        return super.onKeyUp(keyCode, event)+    }++    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {+        val playback = ReceiverController.state.value.playback+            ?: return super.onKeyDown(keyCode, event)          // Any press at all brings the controls up, and re-arms the timer that takes them away.         val waking = !overlayVisible@@ -328,21 +346,6 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {         return handleKeyDown(event, playback)     } -    /**-     * `BACK` dismisses the controls before it will leave the session, because a user who has just-     * brought up a seek bar and presses back means "put that away", not "stop watching".-     *-     * Pinned controls cannot be dismissed, so back means what it always means rather than needing-     * two presses to leave a screen that never changes.-     */-    private fun handleBack(event: KeyEvent): Boolean {-        if (event.action == KeyEvent.ACTION_UP && overlayVisible && !overlayPinned) {-            hideOverlay()-            return true-        }-        return super.dispatchKeyEvent(event)-    }-     /** One press while the controls are up: toggles, seeks, skips, tracks or volume. */     private fun handleKeyDown(event: KeyEvent, playback: PlaybackSnapshot): Boolean {         when (event.keyCode) {@@ -377,7 +380,7 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {             KeyEvent.KEYCODE_VOLUME_DOWN,             -> return pressVolume(event, up = false) -            else -> return super.dispatchKeyEvent(event)+            else -> return super.onKeyDown(event.keyCode, event)         }         return true     }@@ -388,7 +391,7 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {      */     private fun pressVolume(event: KeyEvent, up: Boolean): Boolean {         if (ReceiverController.nudgeVolume(up = up)) return true-        return super.dispatchKeyEvent(event)+        return super.onKeyDown(event.keyCode, event)     }      private fun isScrubKey(keyCode: Int): Boolean =@@ -429,13 +432,17 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {      private fun revealOverlay() {         overlayVisible = true+        updateBackCallback()         hideJob?.cancel()         hideJob = null         if (overlayPinned) return         hideJob = lifecycleScope.launch {             delay(OVERLAY_AUTO_HIDE_MS)             // A scrub in progress is an interaction, however long the user has been holding the key.-            if (scrubPreviewMs == NO_SCRUB) overlayVisible = false+            if (scrubPreviewMs == NO_SCRUB) {+                overlayVisible = false+                updateBackCallback()+            }         }     } @@ -445,6 +452,12 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback {         scrubPreviewMs = NO_SCRUB         scrubCommittedAtMs = 0L         overlayVisible = false+        updateBackCallback()+    }++    /** Back only dismisses controls that are showing and can be dismissed. */+    private fun updateBackCallback() {+        backPressedCallback.isEnabled = overlayVisible && !overlayPinned     }      override fun surfaceCreated(holder: SurfaceHolder) {
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverContentSession.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverContentSession.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverContentSession.ktindex 3ea69a3c59..7cc9a7a20a 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverContentSession.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverContentSession.kt@@ -130,9 +130,9 @@ private suspend fun ReceiverController.prepareContentPlayer(     channel: ControlChannel,     session: ContentSession, ): ContentPlayer? {-    val player = withContext(Dispatchers.Main) { ContentPlayer(context, session) }+    val player = withContext(Dispatchers.Main) { ContentPlayer(session) }     val started = withContext(Dispatchers.Main) {-        player.start { detail -> Log.status(TAG, "the served stream failed: $detail") }+        player.start(context) { detail -> Log.status(TAG, "the served stream failed: $detail") }     }     if (started) return player     channel.send(ContentReady(accepted = false, detail = "the player could not be built"))
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverRoute.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverRoute.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverRoute.ktnew file mode 100644index 0000000000..d802e42eef--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverRoute.kt@@ -0,0 +1,26 @@+package com.vayunmathur.cast.tv.platform++import com.vayunmathur.cast.tv.Route++/**+ * The phase-to-destination projection.+ *+ * [ReceiverPhase.Mirroring] has no destination of its own: the picture+ * lives in `MirrorActivity`, launched by `MainActivity` the moment frames+ * arrive. Underneath it the stack holds [Route.Connected] naming the+ * source, which is also the held-breath screen seen in the moment between+ * the stream starting and that Activity coming up.+ */+fun receiverRouteFor(phase: ReceiverPhase): Route = when (phase) {+    ReceiverPhase.Starting -> Route.Starting+    ReceiverPhase.Advertising -> Route.Ready+    is ReceiverPhase.Pairing -> Route.Pairing(+        senderName = phase.senderName,+        code = phase.code,+        attemptsLeft = phase.attemptsLeft,+        codeChanged = phase.codeChanged,+    )+    is ReceiverPhase.Connected -> Route.Connected(phase.senderName)+    is ReceiverPhase.Mirroring -> Route.Connected(phase.sourceName)+    is ReceiverPhase.Failed -> Route.Failed(phase.reason)+}
cast/tv/src/test/java/com/vayunmathur/cast/tv/RouteTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/RouteTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/RouteTest.ktindex 3436eff3d4..178a96e479 100644--- a/cast/tv/src/test/java/com/vayunmathur/cast/tv/RouteTest.kt+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/RouteTest.kt@@ -2,6 +2,7 @@ package com.vayunmathur.cast.tv  import com.vayunmathur.cast.tv.platform.ReceiverFailure import com.vayunmathur.cast.tv.platform.ReceiverPhase+import com.vayunmathur.cast.tv.platform.receiverRouteFor import com.vayunmathur.library.util.NavKey import kotlin.test.Test import kotlin.test.assertEquals
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.ktindex 9784e06c7a..b24c4fa6d7 100644--- a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.kt+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerDeepTest.kt@@ -54,8 +54,8 @@ class ContentPlayerDeepTest {     @Test fun applyEveryActionOnIdlePlayer() { runBlocking {         val errors = mutableListOf<String>()         onMainPumped {-            val player = ContentPlayer(ctx, session())-            assertTrue(player.start { detail -> errors += detail })+            val player = ContentPlayer(session())+            assertTrue(player.start(ctx) { detail -> errors += detail })             assertTrue(player.apply(PlaybackCommand(PlaybackAction.Play)))             assertTrue(player.apply(PlaybackCommand(PlaybackAction.Pause)))             assertTrue(player.apply(PlaybackCommand(PlaybackAction.Toggle)))@@ -84,8 +84,8 @@ class ContentPlayerDeepTest {      @Test fun startRefusesUnusableFingerprint() { runBlocking {         onMainPumped {-            val player = ContentPlayer(ctx, session(fingerprint = ByteArray(8)))-            assertFalse(player.start { })+            val player = ContentPlayer(session(fingerprint = ByteArray(8)))+            assertFalse(player.start(ctx) { })             player.release()         }         Unit
cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerTest.kt
diff --git a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerTest.kt b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerTest.ktindex 87ecc2e5d7..e2fde45836 100644--- a/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerTest.kt+++ b/cast/tv/src/test/java/com/vayunmathur/cast/tv/platform/ContentPlayerTest.kt@@ -24,7 +24,7 @@ class ContentPlayerTest {     private fun session(fp: String) = ContentSession(host = "127.0.0.1", port = 9, certificateFingerprint = fp, token = "tok", video = false, appLabel = "App")      @Test fun unstartedPlayerIsInert() {-        val p = ContentPlayer(ctx, session("!!!"))+        val p = ContentPlayer(session("!!!"))         assertEquals(0L, p.position); assertEquals(0L, p.duration); assertEquals(false, p.isPlaying); assertEquals(false, p.isBuffering); assertEquals(false, p.isEnded)         assertEquals(1f, p.speed); assertEquals(1f, p.volume)         val snap = p.snapshot(); assertEquals(0L, snap.positionMs); assertEquals(false, snap.playing)@@ -37,15 +37,15 @@ class ContentPlayerTest {         p.play(PlayMedia(resourceId = "r1", mimeType = "audio/mp4")); p.setSurface(null); p.play(); p.pause(); p.seekTo(100); p.setSpeed(2f); p.setVolume(2f); p.release(); p.release()     }     @Test fun startRejectsBadFingerprint() {-        val p = ContentPlayer(ctx, session("not-base64!!"))-        assertEquals(false, p.start { })-        val p2 = ContentPlayer(ctx, session(Base64.encode(byteArrayOf(1, 2, 3))))-        assertEquals(false, p2.start { }) // wrong size+        val p = ContentPlayer(session("not-base64!!"))+        assertEquals(false, p.start(ctx) { })+        val p2 = ContentPlayer(session(Base64.encode(byteArrayOf(1, 2, 3))))+        assertEquals(false, p2.start(ctx) { }) // wrong size     }     @Test fun startBuildsPlayerWithValidFingerprint() {         shadowOf(Looper.getMainLooper()).idle()-        val p = ContentPlayer(ctx, session(Base64.encode(ByteArray(32) { it.toByte() })))-        val started = runCatching { p.start { } }.getOrDefault(false)+        val p = ContentPlayer(session(Base64.encode(ByteArray(32) { it.toByte() })))+        val started = runCatching { p.start(ctx) { } }.getOrDefault(false)         if (started) {             p.play(PlayMedia(resourceId = "r1", mimeType = "audio/mp4", durationMs = 123_000, startPositionMs = 1000))             shadowOf(Looper.getMainLooper()).idle()