Modern Apps git

← Modern-Apps.git

file splits

Commit
6404d0616542094a4002247d2e259ec769614a72
Author
vayun-mathur <[email protected]>
When
2026-09-14 00:39 UTC (2 months ago)
Parents
905478e

Diff

auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.ktnew file mode 100644index 0000000000..cfda873ba2--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.kt@@ -0,0 +1,198 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.graphics.Color+import android.view.Gravity+import android.view.View+import android.widget.LinearLayout+import android.widget.TextView+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.CarUiMetrics.BUTTON_DISABLED_ALPHA+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_SUBTITLE+import com.vayunmathur.auto.platform.CarUiMetrics.MATCH+import com.vayunmathur.auto.platform.CarUiMetrics.WRAP++/**+ * The projected call card (`UnCallView` parity): incoming vs active+ * rows with the 44dp (`un_ar_icon_size`) action buttons, the end-call+ * FAB focusable, and the `PHONE_FACET` content description. Held calls+ * disable the row with the button-disabled alpha. GONE with no live+ * call; the duration ticks every second like `postDelayed(l, 1000)`.+ *+ * Owns its views; the presentation drives state through [update] (null+ * hides) and ticks duration through [tickDuration]. Actions route to the+ * bound InCallService through the constructor callbacks. Views, not+ * Compose (private display, no lifecycle owner).+ */+internal class CarCallCardView(+    private val context: Context,+    private val onAnswer: () -> Unit,+    private val onEnd: () -> Unit,+    private val onHold: () -> Unit,+    private val onMute: () -> Unit,+) {+    private fun dp(value: Int): Int = context.carDp(value)++    private var callCardView: LinearLayout? = null+    private var callName: TextView? = null+    private var callState: TextView? = null+    private var callActions: LinearLayout? = null++    /**+     * Inner active-call snapshot: set by [update], read by [tickDuration],+     * so duration ticks against the card's own state.+     */+    private var innerActiveCall: ActiveCallInfo? = null++    /** Late-wired actions (service wires after `show()` starts the build). */+    var tapAnswer: () -> Unit = onAnswer+    var tapEnd: () -> Unit = onEnd+    var tapHold: () -> Unit = onHold+    var tapMute: () -> Unit = onMute++    /** The assembled card; add once above the nav/media split. */+    val view: LinearLayout = callCard()++    /** Clears view refs; call from `onStop`. */+    fun clear() {+        callCardView = null+        callName = null+        callState = null+        callActions = null+        innerActiveCall = null+    }++    /**+     * Pushes one active-call snapshot into the card. Main thread only;+     * null hides the card. Incoming shows answer/decline; active shows+     * end/mute/hold with the hold-disabled alpha; the duration ticks on+     * the 1Hz ticker while active.+     */+    fun update(info: ActiveCallInfo?) {+        innerActiveCall = info+        val card = callCardView ?: return+        if (info == null) {+            card.visibility = View.GONE+            return+        }+        card.visibility = View.VISIBLE+        val name = callName ?: return+        name.text = info.number ?: context.getString(R.string.car_call_unknown)+        val state = callState+        if (state != null) {+            state.text = if (info.isIncoming) {+                context.getString(R.string.car_call_incoming)+            } else {+                context.getString(R.string.car_call_active)+            }+        }+        val row = callActions ?: return+        row.removeAllViews()+        if (info.isIncoming) {+            row.addView(callActionButton(context.getString(R.string.car_call_answer)) { tapAnswer() })+            row.addView(callActionButton(context.getString(R.string.car_call_decline)) { tapEnd() })+        } else {+            val end = callActionButton(context.getString(R.string.car_call_end)) { tapEnd() }+            end.isFocusable = true+            row.addView(end)+            val mute = callActionButton(+                if (info.muted) context.getString(R.string.car_call_unmute)+                else context.getString(R.string.car_call_mute),+            ) { tapMute() }+            val hold = callActionButton(+                if (info.held) context.getString(R.string.car_call_resume)+                else context.getString(R.string.car_call_hold),+            ) { tapHold() }+            if (info.held) {+                // Held: row disabled with the button-disabled alpha.+                mute.isEnabled = false+                hold.isEnabled = false+                mute.alpha = BUTTON_DISABLED_ALPHA+                hold.alpha = BUTTON_DISABLED_ALPHA+            }+            row.addView(mute)+            row.addView(hold)+        }+    }++    /**+     * Ticks the active-call duration once per second. Main thread only;+     * called from the 1Hz ticker. Incoming (ringing) shows no duration;+     * active shows mm:ss since accept; held freezes on the held snapshot.+     */+    fun tickDuration() {+        val info = innerActiveCall ?: return+        val state = callState ?: return+        if (info.isIncoming || info.acceptedMs <= 0L) return+        val elapsed = ((System.currentTimeMillis() - info.acceptedMs) / 1000).coerceAtLeast(0)+        state.text = context.getString(+            R.string.car_call_duration,+            elapsed / 60,+            elapsed % 60,+        )+    }++    private fun callCard(): LinearLayout {+        return LinearLayout(context).apply {+            orientation = LinearLayout.VERTICAL+            gravity = Gravity.CENTER+            setBackgroundColor(Color.parseColor(COLOR_CARD_DAY))+            setPadding(dp(16), dp(16), dp(16), dp(16))+            visibility = View.GONE+            layoutParams = LinearLayout.LayoutParams(MATCH, WRAP).apply {+                topMargin = dp(8)+            }+            contentDescription = "phone"+            addView(+                TextView(context).apply {+                    textSize = 24f+                    setTextColor(Color.WHITE)+                    gravity = Gravity.CENTER+                    maxLines = 1+                    callName = this+                },+            )+            addView(+                TextView(context).apply {+                    textSize = 18f+                    setTextColor(Color.parseColor(COLOR_SUBTITLE))+                    gravity = Gravity.CENTER+                    callState = this+                },+            )+            addView(+                LinearLayout(context).apply {+                    orientation = LinearLayout.HORIZONTAL+                    gravity = Gravity.CENTER+                    layoutParams = LinearLayout.LayoutParams(MATCH, WRAP).apply {+                        topMargin = dp(12)+                    }+                    callActions = this+                },+            )+            callCardView = this+        }+    }++    /** One 44dp (`un_ar_icon_size`) call action button. */+    private fun callActionButton(label: String, onTap: () -> Unit): TextView {+        return TextView(context).apply {+            text = label+            setTextColor(Color.WHITE)+            textSize = 18f+            gravity = Gravity.CENTER+            background = context.carFocusRingBackground()+            isClickable = true+            isFocusable = true+            minWidth = dp(44)+            minHeight = dp(44)+            setPadding(dp(12), dp(8), dp(12), dp(8))+            layoutParams = LinearLayout.LayoutParams(WRAP, WRAP).apply {+                marginStart = dp(8)+                marginEnd = dp(8)+            }+            setOnClickListener { onTap() }+        }+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.ktindex 197e2407bf..beb7fbc0f6 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt@@ -4,6 +4,7 @@ import android.app.Presentation import android.content.Context import android.graphics.Color import android.graphics.Outline+import android.graphics.SurfaceTexture import android.hardware.display.DisplayManager import android.hardware.display.VirtualDisplay import android.os.Bundle@@ -11,16 +12,25 @@ import android.os.Handler import android.os.Looper import android.util.Log import android.view.Gravity+import android.view.KeyEvent+import android.view.MotionEvent import android.view.Surface+import android.view.TextureView import android.view.View+import android.view.ViewConfiguration import android.view.ViewGroup import android.view.ViewOutlineProvider+import android.widget.FrameLayout import android.widget.GridLayout import android.widget.ImageView import android.widget.LinearLayout+import android.widget.ProgressBar+import android.widget.ScrollView+import android.widget.Space import android.widget.TextView import com.vayunmathur.auto.BuildConfig import com.vayunmathur.auto.R+import com.vayunmathur.auto.protocol.NavSnapshot import java.text.DateFormat import java.util.Date import java.util.concurrent.ExecutionException@@ -35,12 +45,15 @@ import java.util.concurrent.FutureTask  * owned by this app renders onto a private display perfectly well, which is enough to  * get pixels onto a head unit and prove the video path end to end — so the DHU  * loopback path never needs the flag.+ *+ * Views, not Compose: a `Presentation` on a private virtual display has no Compose+ * lifecycle owner, and Views render into the encoder surface with no extra plumbing.  */ class CarDisplay(     private val context: Context,-    private val width: Int,-    private val height: Int,-    private val densityDpi: Int,+    private var width: Int,+    private var height: Int,+    private var densityDpi: Int,     /**      * Phase 9 display-route hook: true requests `VIRTUAL_DISPLAY_FLAG_TRUSTED` so      * other apps' activities may be launched onto the car screen. Driven by@@ -58,6 +71,71 @@ class CarDisplay(      * via [handleCarTap]. Wired to the media monitor's transport toggle.      */     var onMediaTap: (() -> Unit)? = null+        set(value) {+            field = value+            value?.let { v -> mainHandler.post { presentation?.setOnMediaTap(v) } }+        }++    /** Fires when the media card's previous-track button is tapped. Null until wired. */+    var onPreviousTap: (() -> Unit)? = null+        set(value) {+            field = value+            value?.let { v -> mainHandler.post { presentation?.setOnPreviousTap(v) } }+        }++    /** Fires when the media card's next-track button is tapped. Null until wired. */+    var onNextTap: (() -> Unit)? = null+        set(value) {+            field = value+            value?.let { v -> mainHandler.post { presentation?.setOnNextTap(v) } }+        }++    /**+     * Optional night hook for the session's map mirror: invoked from+     * [setNight] on the calling thread (the mirror marshals to main itself).+     * The service sets this to `CarMapsMirror.setDark`; unset means the+     * mirror keeps its own last palette.+     */+    var mapDarkApplier: ((Boolean) -> Unit)? = null++    /** Phone status feed for the rail cluster; the service sets its monitor. */+    var phoneStatusSource: (() -> PhoneStatus)? = null+        set(value) {+            field = value+            // Late wiring must reach an already-up presentation too: the+            // ticker pulls through the inner field, never this one.+            mainHandler.post { presentation?.setInnerPhoneStatusSource(value) }+        }++    /** Card call actions; the service wires these to the bound InCallService. */+    var onAnswerCall: (() -> Unit)? = null+        set(value) {+            field = value+            value?.let { v -> mainHandler.post { presentation?.setOnAnswerCall(v) } }+        }+    var onEndCall: (() -> Unit)? = null+        set(value) {+            field = value+            value?.let { v -> mainHandler.post { presentation?.setOnEndCall(v) } }+        }+    var onHoldToggle: (() -> Unit)? = null+        set(value) {+            field = value+            value?.let { v -> mainHandler.post { presentation?.setOnHoldToggle(v) } }+        }+    var onMuteToggle: (() -> Unit)? = null+        set(value) {+            field = value+            value?.let { v -> mainHandler.post { presentation?.setOnMuteToggle(v) } }+        }++    /**+     * Active-call feed for the projected call card; the service sets the+     * latest [ActiveCallInfo] (null with no live call). Cached for+     * presentations created later.+     */+    @Volatile+    var activeCall: ActiveCallInfo? = null      /**      * Latest now-playing snapshot: applied to the card when set, and to any@@ -66,6 +144,21 @@ class CarDisplay(      */     @Volatile private var nowPlaying: NowPlayingInfo? = null +    /**+     * Latest driving-restriction gate: applied to the card when set, and to+     * any presentation created afterwards. Cached like [nowPlaying].+     */+    @Volatile private var drivingRestricted: Boolean = false++    /**+     * Latest night palette: applied to the car UI when set, and to any+     * presentation created afterwards. Cached like [nowPlaying].+     */+    @Volatile private var nightDark: Boolean = false++    /** The encoder input surface [show] was last called with; kept for [updateConfig]. */+    private var cachedSurface: Surface? = null+     /** Last-known now-playing card bounds in display pixels; null until laid out. */     @Volatile private var mediaCardBounds: TapBounds? = null @@ -87,6 +180,7 @@ class CarDisplay(      * hops to the main thread and waits, keeping the video bring-up order unchanged.      */     fun show(surface: Surface) {+        cachedSurface = surface         val displayManager = context.getSystemService(DisplayManager::class.java)         // PRESENTATION alone is a private display: no permission needed. TRUSTED         // additionally requires ADD_TRUSTED_DISPLAY (the MAOS role); requesting it@@ -106,14 +200,53 @@ class CarDisplay(         presentation = showPresentation(             display.display,             initialNowPlaying = nowPlaying,+            initialDrivingRestricted = drivingRestricted,+            initialNight = nightDark,+            initialActiveCall = activeCall,+            initialPhoneStatusSource = phoneStatusSource,             onMediaTap = { onMediaTap?.invoke() },+            onPreviousTap = { onPreviousTap?.invoke() },+            onNextTap = { onNextTap?.invoke() },+            onAnswerCall = { onAnswerCall?.invoke() },+            onEndCall = { onEndCall?.invoke() },+            onHoldToggle = { onHoldToggle?.invoke() },+            onMuteToggle = { onMuteToggle?.invoke() },             onCardBounds = { left, top, right, bottom ->                 mediaCardBounds = TapBounds(left, top, right, bottom)             },-        )+        ).also { shown ->+            mapSurfaceForwarder?.let { forward ->+                shown.mapSurfaceListener = { s, w, h -> forward(s, w, h) }+            }+        }         dumpVirtualDisplay(display.display, surface)     } +    /**+     * Rebuilds the virtual display when the negotiated size changes.+     *+     * The car path has no `onConfigurationChanged` of its own (phone config+     * lives in `MainActivity`); whoever observes a new video config calls+     * here. Same size is a no-op; otherwise the display and presentation are+     * torn down and re-shown on the cached surface, which rebuilds every+     * programmatic view (including the alpha-jump keyboard) at the new size.+     * Density and encoder settings are untouched. Safe from any thread.+     */+    fun updateConfig(width: Int, height: Int, densityDpi: Int) {+        mainHandler.post {+            if (width == this.width && height == this.height && densityDpi == this.densityDpi) return@post+            val surface = cachedSurface ?: return@post+            this.width = width+            this.height = height+            this.densityDpi = densityDpi+            presentation?.dismiss()+            presentation = null+            virtualDisplay?.release()+            virtualDisplay = null+            show(surface)+        }+    }+     /**      * Refreshes the car now-playing card. Safe from any thread: the snapshot is      * cached for presentations created later, and the view update hops to main.@@ -134,6 +267,96 @@ class CarDisplay(         mainHandler.post { presentation?.hideNowPlaying() }     } +    /**+     * Gates driving-restricted pixels. Safe from any thread.+     *+     * Hides the media card's action row (gearhead `MediaPlaybackView.n()`+     * auto-hide) and raises the drawer lockout scrim when the drawer is+     * open. There is no `nrd` truth table in MA: the service drives this+     * from the sensor DRIVING_STATUS stream / `NavSnapshot.parked`, and the+     * cached value replays onto presentations created later.+     */+    fun setDrivingRestricted(restricted: Boolean) {+        drivingRestricted = restricted+        mainHandler.post { presentation?.setDrivingRestricted(restricted) }+    }++    /**+     * Closes the drawer at trip end. Parked is the motion heuristic from+     * `NavSnapshot.parked`, not a gear reading; the parked-browsing exit+     * header covers the parked-browsing affordance separately. Safe from any+     * thread.+     */+    fun setParked(parked: Boolean) {+        if (parked) mainHandler.post { presentation?.closeDrawer() }+    }++    /**+     * Pushes parked state into the driving-restriction gate. The parked bit+     * is the `NavSnapshot.parked` motion heuristic: parked clears the gate+     * (media row visible, lockout down); not-parked raises it. Separated from+     * [setParked] (which closes the drawer at trip end) so both consumers of+     * the same snapshot field stay explicit. Safe from any thread.+     */+    fun setParkedBrowsingGate(parked: Boolean) {+        setDrivingRestricted(!parked)+    }++    /**+     * Switches the car UI between day and night palettes. Safe from any thread.+     *+     * Recolors root/rail/cards/drawer per the §2.3 night deltas and forwards+     * to the session mirror through [mapDarkApplier] (the service wires it+     * to `CarMapsMirror.setDark`; the mirror marshals to main itself). Night+     * sources already in the tree: `ProjectionService.isNightNow` and the+     * `SensorChannel` `NightSource` -- the service picks one and calls here,+     * and the cached value replays onto presentations created later.+     */+    fun setNight(dark: Boolean) {+        nightDark = dark+        mapDarkApplier?.invoke(dark)+        mainHandler.post { presentation?.setNight(dark) }+    }++    /**+     * Pushes one active-call snapshot into the car card; null hides it.+     * Safe from any thread; cached for presentations created later.+     */+    fun setActiveCall(info: ActiveCallInfo?) {+        activeCall = info+        mainHandler.post { presentation?.updateCallCard(info) }+    }++    /**+     * Pushes one guidance snapshot to the nav banner, if the render pair is+     * up. The service calls this on every guidance-monitor update; the banner+     * itself decides show vs GONE.+     */+    fun setNavSnapshot(snapshot: NavSnapshot) {+        mainHandler.post { presentation?.updateNavSnapshot(snapshot) }+    }++    /**+     * Forwards nav-card map surfaces to the session mirror when the render+     * pair comes up after this was set. Cached like [nowPlaying] for+     * presentations created later.+     */+    @Volatile private var mapSurfaceForwarder: ((Surface?, Int, Int) -> Unit)? = null++    /**+     * Wires the nav-card map surface to the session mirror. The surface+     * arrives when the TextureView is ready (or null on destroy); unset means+     * no map backend and the nav card stays a launch tile.+     */+    fun setMapSurfaceListener(listener: (Surface?, Int, Int) -> Unit) {+        mapSurfaceForwarder = listener+        mainHandler.post {+            presentation?.mapSurfaceListener = { surface, w, h ->+                listener(surface, w, h)+            }+        }+    }+     /**      * Starts continuously invalidating the car UI at [fps] frames per second.      * Safe from any thread; hops to main like [setNowPlaying].@@ -193,8 +416,8 @@ class CarDisplay(     fun injectKey(keycode: Int, down: Boolean): Boolean {         if (presentation == null) return false         mainHandler.post {-            val event = android.view.KeyEvent(-                if (down) android.view.KeyEvent.ACTION_DOWN else android.view.KeyEvent.ACTION_UP,+            val event = KeyEvent(+                if (down) KeyEvent.ACTION_DOWN else KeyEvent.ACTION_UP,                 keycode,             )             presentation?.window?.decorView?.dispatchKeyEvent(event)@@ -210,14 +433,14 @@ class CarDisplay(         if (presentation == null) return false         mainHandler.post {             val now = android.os.SystemClock.uptimeMillis()-            val coords = android.view.MotionEvent.PointerCoords().apply {-                setAxisValue(android.view.MotionEvent.AXIS_VSCROLL, delta.toFloat())+            val coords = MotionEvent.PointerCoords().apply {+                setAxisValue(MotionEvent.AXIS_VSCROLL, delta.toFloat())             }-            val event = android.view.MotionEvent.obtain(+            val event = MotionEvent.obtain(                 now, now,-                android.view.MotionEvent.ACTION_SCROLL,+                MotionEvent.ACTION_SCROLL,                 1,-                arrayOf(android.view.MotionEvent.PointerProperties().apply { id = 0 }),+                arrayOf(MotionEvent.PointerProperties().apply { id = 0 }),                 arrayOf(coords),                 0, 0, 1f, 1f, 0, 0,                 android.view.InputDevice.SOURCE_MOUSE, 0,@@ -239,43 +462,43 @@ class CarDisplay(         // coordinates are display pixels and the card bounds are too, so a         // DOWN inside them is an unambiguous card hit. Other gestures (and         // taps elsewhere) still dispatch normally so app tiles stay tappable.-        if (action == android.view.MotionEvent.ACTION_DOWN && pointers.size == 1) {+        if (action == MotionEvent.ACTION_DOWN && pointers.size == 1) {             val (x, y, _) = pointers[0]             if (handleCarTap(x, y)) return         }         val now = android.os.SystemClock.uptimeMillis()-        val downTime = if (action == android.view.MotionEvent.ACTION_DOWN) {+        val downTime = if (action == MotionEvent.ACTION_DOWN) {             gestureDownTime = now             now         } else {             gestureDownTime         }         val fullAction = when (action) {-            android.view.MotionEvent.ACTION_POINTER_DOWN,-            android.view.MotionEvent.ACTION_POINTER_UP,+            MotionEvent.ACTION_POINTER_DOWN,+            MotionEvent.ACTION_POINTER_UP,             -> action or (actionIndex.coerceIn(0, pointers.size - 1) shl-                android.view.MotionEvent.ACTION_POINTER_INDEX_SHIFT)+                MotionEvent.ACTION_POINTER_INDEX_SHIFT)             else -> action         }         val props = pointers.map { (_, _, id) ->-            android.view.MotionEvent.PointerProperties().apply { this.id = id }+            MotionEvent.PointerProperties().apply { this.id = id }         }.toTypedArray()         val coords = pointers.map { (x, y, _) ->-            android.view.MotionEvent.PointerCoords().apply {+            MotionEvent.PointerCoords().apply {                 this.x = x                 this.y = y                 pressure = 1f             }         }.toTypedArray()-        val event = android.view.MotionEvent.obtain(+        val event = MotionEvent.obtain(             downTime, now, fullAction, pointers.size, props, coords,             0, 0, 1f, 1f, 0, 0,             android.view.InputDevice.SOURCE_TOUCHSCREEN, 0,         )         view.dispatchTouchEvent(event)         event.recycle()-        if (action == android.view.MotionEvent.ACTION_UP ||-            action == android.view.MotionEvent.ACTION_CANCEL+        if (action == MotionEvent.ACTION_UP ||+            action == MotionEvent.ACTION_CANCEL         ) {             gestureDownTime = 0         }@@ -300,16 +523,56 @@ class CarDisplay(     private fun showPresentation(         display: android.view.Display,         initialNowPlaying: NowPlayingInfo?,+        initialDrivingRestricted: Boolean,+        initialNight: Boolean,+        initialActiveCall: ActiveCallInfo?,+        initialPhoneStatusSource: (() -> PhoneStatus?)?,         onMediaTap: () -> Unit,+        onPreviousTap: () -> Unit,+        onNextTap: () -> Unit,+        onAnswerCall: () -> Unit,+        onEndCall: () -> Unit,+        onHoldToggle: () -> Unit,+        onMuteToggle: () -> Unit,         onCardBounds: (Int, Int, Int, Int) -> Unit,     ): CarPresentation {         if (isMainThread) {-            return CarPresentation(context, display, initialNowPlaying, onMediaTap, onCardBounds)-                .also { it.show() }+            return CarPresentation(+                context,+                display,+                initialNowPlaying,+                initialDrivingRestricted,+                initialNight,+                initialActiveCall,+                initialPhoneStatusSource,+                onMediaTap,+                onPreviousTap,+                onNextTap,+                onAnswerCall,+                onEndCall,+                onHoldToggle,+                onMuteToggle,+                onCardBounds,+            ).also { it.show() }         }         val show = FutureTask<CarPresentation> {-            CarPresentation(context, display, initialNowPlaying, onMediaTap, onCardBounds)-                .also { it.show() }+            CarPresentation(+                context,+                display,+                initialNowPlaying,+                initialDrivingRestricted,+                initialNight,+                initialActiveCall,+                initialPhoneStatusSource,+                onMediaTap,+                onPreviousTap,+                onNextTap,+                onAnswerCall,+                onEndCall,+                onHoldToggle,+                onMuteToggle,+                onCardBounds,+            ).also { it.show() }         }         mainHandler.post(show)         try {@@ -325,668 +588,12 @@ class CarDisplay(             throw e.cause ?: e         }     }--    /**-     * The car launcher: a driving-safe home screen with a status bar and big app tiles.-     *-     * Deliberately Views, not Compose: a `Presentation` on a private virtual display has-     * no Compose lifecycle owner, and Views render into the encoder surface with no-     * extra plumbing. Large tiles, high contrast, and nothing that needs reading at-     * a glance beyond a label.-     */-    private class CarPresentation(-        context: Context,-        display: android.view.Display,-        initialNowPlaying: NowPlayingInfo?,-        private val onMediaTap: () -> Unit,-        private val onCardBounds: (Int, Int, Int, Int) -> Unit,-    ) : Presentation(context, display) {--        /**-         * Snapshot that arrived before `onCreate` built the card views.-         * Consumed once in `onCreate`; after that the card exists and updates-         * apply directly.-         */-        private var pendingNowPlaying: NowPlayingInfo? = initialNowPlaying--        private var clockView: TextView? = null-        private val timeFormat: DateFormat = DateFormat.getTimeInstance(DateFormat.SHORT)-        private var mediaTitle: TextView? = null-        private var mediaSubtitle: TextView? = null-        private var mediaState: TextView? = null-        private var mediaProgress: View? = null-        private var mediaCard: LinearLayout? = null-        private var drawerView: View? = null--        // Real wall-clock time, ticking every second. The old placeholder showed a-        // session counter here; a driver needs to know what time it is instead, and the-        // moving digits still prove frames are flowing rather than one stale image.-        private val ticker = object : Runnable {-            override fun run() {-                val view = clockView ?: return-                view.text = timeFormat.format(Date())-                view.postDelayed(this, 1000)-            }-        }--        /**-         * Continuous re-render at [fps] so the encoder surface produces frames-         * even when no view changes on its own. Main thread only. Backs off to-         * a Choreographer-frame chain when [fps] is at/above display cadence.-         */-        private var invalidator: Runnable? = null-        private var invalidatorFps = 0--        fun startFrameInvalidation(fps: Int) {-            stopFrameInvalidation()-            val decor = window?.decorView ?: return-            val intervalMs = (1000L / fps.coerceIn(1, MAX_INVALIDATE_FPS)).coerceAtLeast(0)-            invalidatorFps = fps-            val tick = object : Runnable {-                override fun run() {-                    decor.invalidate()-                    decor.postDelayed(this, intervalMs)-                }-            }-            invalidator = tick-            decor.post(tick)-        }--        fun stopFrameInvalidation() {-            val decor = window?.decorView-            invalidator?.let { decor?.removeCallbacks(it) }-            invalidator = null-            invalidatorFps = 0-        }--        override fun onCreate(savedInstanceState: Bundle?) {-            super.onCreate(savedInstanceState)-            // Coolwalk facet structure, matching gearhead's-            // `gh_coolwalk_facet_bar` + dashboard cards + drawer:-            // content area (split nav/media cards, drawer overlay) above a-            // bottom facet bar (dashboard button, hotseat dock, status).-            // Views, not Compose (see the class KDoc).-            val root = LinearLayout(context).apply {-                orientation = LinearLayout.VERTICAL-                setBackgroundColor(Color.parseColor("#101418"))-                layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)-            }-            val apps = CarApps.query(context)-            val content = android.widget.FrameLayout(context).apply {-                layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)-                addView(splitCards(apps))-                addView(appDrawer(apps).also { drawerView = it })-            }-            root.addView(content)-            root.addView(facetBar(apps))-            setContentView(root)--            pendingNowPlaying?.let { updateNowPlaying(it) }-            pendingNowPlaying = null--            clockView?.let {-                it.text = timeFormat.format(Date())-                it.post(ticker)-            }-        }--        /** Hides the now-playing card; the cached snapshot is untouched. Main thread only. */-        fun hideNowPlaying() {-            mediaCard?.visibility = View.GONE-        }--        override fun onStop() {-            clockView?.removeCallbacks(ticker)-            stopFrameInvalidation()-            clockView = null-            mediaTitle = null-            mediaSubtitle = null-            mediaState = null-            mediaProgress = null-            mediaCard = null-            drawerView = null-            super.onStop()-        }--        /**-         * Applies a snapshot to the now-playing card. Main thread only: called-         * from the posted update in [setNowPlaying], or from `onCreate` above-         * for a snapshot that arrived before the views existed.-         *-         * Also owns the card's visibility: `GONE` when idle (not playing and-         * no title to show) so the car display shows no card with nothing-         * playing; `VISIBLE` while playing, and while paused with a title so-         * resume keeps its context. GAL 11/12 stay unspoken by design, so no-         * head-unit contract drives this -- it is purely phone-side.-         */-        fun updateNowPlaying(info: NowPlayingInfo) {-            val card = mediaCard ?: return-            card.visibility = if (info.shouldShowCard()) View.VISIBLE else View.GONE-            val title = mediaTitle ?: return-            val subtitle = mediaSubtitle ?: return-            val state = mediaState ?: return-            title.text = info.title ?: context.getString(R.string.car_now_playing_unknown)-            subtitle.text = info.artist ?: context.getString(R.string.car_now_playing_unknown_artist)-            state.text = context.getString(-                if (info.playing) R.string.car_now_playing_playing-                else R.string.car_now_playing_paused,-            )-            val progress = mediaProgress ?: return-            val fraction = progressFraction(info.positionMs, info.durationMs)-            val bar = mediaCard ?: return-            // Resize the fill once laid out: the bar width is only known after-            // the layout pass, and the encoder surface picks the re-layout up on-            // the next frame.-            progress.post {-                val total = bar.width-                if (total > 0) {-                    progress.layoutParams = progress.layoutParams.apply {-                        width = (total * fraction).toInt().coerceIn(0, total)-                    }-                    progress.requestLayout()-                }-            }-        }--        /**-         * The single now-playing layout, matching `frag_dash_media` structure:-         * title (28sp, 1 line) + subtitle (24sp), 4dp progress bar, whole card-         * tappable to toggle playback. Album art and the prev/next button row-         * are omitted: no art backend exists, and transport beyond toggle has-         * no monitor path yet -- the card never shows what it cannot do.-         */-        private fun nowPlayingCard(): LinearLayout {-            val card = LinearLayout(context).apply {-                orientation = LinearLayout.VERTICAL-                setBackgroundColor(Color.parseColor("#1B2430"))-                setPadding(dp(24), dp(16), dp(24), dp(16))-                layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)-                isClickable = true-                isFocusable = true-                // Starts hidden: the first snapshot decides, and with nothing-                // playing there is nothing to show.-                visibility = View.GONE-            }-            card.addView(-                TextView(context).apply {-                    text = context.getString(R.string.car_now_playing)-                    setTextColor(Color.parseColor("#8AB4F8"))-                    textSize = 14f-                },-            )-            card.addView(-                TextView(context).apply {-                    textSize = 28f-                    maxLines = 1-                    setTextColor(Color.WHITE)-                    mediaTitle = this-                },-            )-            card.addView(-                TextView(context).apply {-                    textSize = 24f-                    setTextColor(Color.parseColor("#C7CFD9"))-                    mediaSubtitle = this-                },-            )-            card.addView(-                TextView(context).apply {-                    textSize = 14f-                    setTextColor(Color.parseColor("#8AB4F8"))-                    mediaState = this-                },-            )-            val track = View(context).apply {-                setBackgroundColor(Color.parseColor("#2A3138"))-                layoutParams = LinearLayout.LayoutParams(MATCH, dp(4)).apply {-                    topMargin = dp(12)-                }-            }-            card.addView(track)-            val fill = View(context).apply {-                setBackgroundColor(Color.parseColor("#8AB4F8"))-                layoutParams = LinearLayout.LayoutParams(0, dp(4)).apply {-                    topMargin = dp(-4)-                }-                mediaProgress = this-            }-            card.addView(fill)-            card.setOnClickListener { onMediaTap() }-            // Report layout bounds for ch8 tap routing once the view is placed.-            card.viewTreeObserver.addOnGlobalLayoutListener(-                object : android.view.ViewTreeObserver.OnGlobalLayoutListener {-                    override fun onGlobalLayout() {-                        val loc = IntArray(2)-                        card.getLocationOnScreen(loc)-                        onCardBounds(loc[0], loc[1], loc[0] + card.width, loc[1] + card.height)-                    }-                },-            )-            mediaCard = card-            return card-        }--        private fun statusBar(): LinearLayout {-            val bar = LinearLayout(context).apply {-                orientation = LinearLayout.HORIZONTAL-                gravity = Gravity.CENTER_VERTICAL-                setPadding(dp(24), dp(16), dp(24), dp(16))-            }-            val titles = LinearLayout(context).apply {-                orientation = LinearLayout.VERTICAL-                layoutParams = LinearLayout.LayoutParams(0, WRAP, 1f)-            }-            titles.addView(-                TextView(context).apply {-                    text = context.getString(R.string.app_name)-                    setTextColor(Color.WHITE)-                    textSize = 28f-                },-            )-            titles.addView(-                TextView(context).apply {-                    text = context.getString(R.string.car_connected)-                    setTextColor(Color.parseColor("#8AB4F8"))-                    textSize = 16f-                },-            )-            bar.addView(titles)-            val clock = TextView(context).apply {-                setTextColor(Color.WHITE)-                textSize = 24f-                gravity = Gravity.END-            }-            clockView = clock-            bar.addView(clock)-            return bar-        }--        private fun divider(): View = View(context).apply {-            setBackgroundColor(Color.parseColor("#2A3138"))-            layoutParams = LinearLayout.LayoutParams(MATCH, dp(1))-        }--        /**-         * The bottom facet bar (`gh_coolwalk_facet_bar`): dashboard button,-         * centered hotseat dock, and the status clock at the end. Touch-         * targets match gearhead (`facet_bar_touch_target_size` 68dp,-         * `coolwalk_launcher_dashboard_margin` 10dp, `rail_coolwalk_rail_margin`-         * 6dp). No assistant button: there is no assistant backend, and the-         * launcher never shows what the phone cannot open.-         */-        private fun facetBar(apps: List<CarApp>): LinearLayout {-            return LinearLayout(context).apply {-                orientation = LinearLayout.HORIZONTAL-                gravity = Gravity.CENTER_VERTICAL-                setBackgroundColor(Color.parseColor("#161C24"))-                layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)-                setPadding(dp(10), dp(6), dp(6), dp(6))-                addView(-                    facetButton(context.getString(R.string.car_home_glyph), "Home") {-                        drawerView?.visibility = View.GONE-                    },-                )-                addView(-                    LinearLayout(context).apply {-                        orientation = LinearLayout.HORIZONTAL-                        gravity = Gravity.CENTER-                        layoutParams = LinearLayout.LayoutParams(0, WRAP, 1f)-                        apps.take(MAX_DOCK_APPS).forEach { app ->-                            addView(hotseatCell(app))-                        }-                        addView(-                            hotseatCell(null) {-                                drawerView?.visibility = View.VISIBLE-                            },-                        )-                    },-                )-                addView(facetStatus())-            }-        }--        /** One 68dp facet-bar button with a decorative glyph label. */-        private fun facetButton(glyph: String, description: String, onTap: () -> Unit): TextView {-            return TextView(context).apply {-                text = glyph-                contentDescription = description-                setTextColor(Color.WHITE)-                textSize = 28f-                gravity = Gravity.CENTER-                layoutParams = LinearLayout.LayoutParams(dp(68), dp(68))-                isClickable = true-                isFocusable = true-                setOnClickListener { onTap() }-            }-        }--        /**-         * One hotseat cell (`sys_ui_rail_hotseat` item): a 68dp touch target-         * with the app icon at 56dp and 8dp padding, untinted, no label ---         * labels live in the drawer grid (`app_launcher_item`). A null app-         * renders the drawer glyph cell instead.-         */-        private fun hotseatCell(app: CarApp?, onDrawerTap: (() -> Unit)? = null): android.widget.FrameLayout {-            return android.widget.FrameLayout(context).apply {-                layoutParams = LinearLayout.LayoutParams(dp(68), dp(68))-                isClickable = true-                isFocusable = true-                if (app != null) {-                    addView(-                        ImageView(context).apply {-                            setImageDrawable(app.icon)-                            contentDescription = app.label.toString()-                            setPadding(dp(8), dp(8), dp(8), dp(8))-                            layoutParams = android.widget.FrameLayout.LayoutParams(dp(56), dp(56), Gravity.CENTER)-                        },-                    )-                    setOnClickListener { context.startActivity(app.launch) }-                } else {-                    addView(-                        TextView(context).apply {-                            text = context.getString(R.string.car_drawer_glyph)-                            setTextColor(Color.WHITE)-                            textSize = 28f-                            gravity = Gravity.CENTER-                            layoutParams = android.widget.FrameLayout.LayoutParams(dp(56), dp(56), Gravity.CENTER)-                        },-                    )-                    setOnClickListener { onDrawerTap?.invoke() }-                }-            }-        }--        /**-         * The facet status slot (`rail_statusbar`): clock only. Gearhead shows-         * signal/battery icons here; the phone cannot know the car's radio-         * state, so nothing is faked.-         */-        private fun facetStatus(): TextView {-            return TextView(context).apply {-                setTextColor(Color.WHITE)-                textSize = 24f-                gravity = Gravity.END or Gravity.CENTER_VERTICAL-                layoutParams = LinearLayout.LayoutParams(WRAP, dp(68))-                setPadding(dp(6), 0, dp(6), 0)-            }.also { clockView = it }-        }--        /**-         * The Coolwalk split: nav card beside the media card, sharing the-         * content area. The media card is the existing now-playing layout-         * (visibility-gated as before); the nav card deep-links Maps.-         */-        private fun splitCards(apps: List<CarApp>): LinearLayout {-            return LinearLayout(context).apply {-                orientation = LinearLayout.HORIZONTAL-                // Fills the content frame: weights only work in a LinearLayout-                // parent, and this lives in a FrameLayout (split + drawer-                // overlay), so MATCH/MATCH, not 0-weight.-                layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)-                setPadding(dp(16), dp(8), dp(16), dp(8))-                addView(-                    navCard(apps).apply {-                        layoutParams = LinearLayout.LayoutParams(0, MATCH, 1f).apply {-                            marginEnd = dp(8)-                        }-                    },-                )-                addView(-                    nowPlayingCard().apply {-                        layoutParams = LinearLayout.LayoutParams(0, MATCH, 1f).apply {-                            marginStart = dp(8)-                        }-                    },-                )-            }-        }--        /**-         * The nav half of the split: Maps icon + label, tapping launches it.-         * Without Maps installed this shows the empty state instead of a dead-         * tile, so the split never offers what the phone cannot open.-         */-        private fun navCard(apps: List<CarApp>): LinearLayout {-            val maps = apps.firstOrNull {-                it.launch.`package` == MAPS_PACKAGE ||-                    it.label.toString().contains(MAPS_LABEL, ignoreCase = true)-            }-            return LinearLayout(context).apply {-                orientation = LinearLayout.VERTICAL-                gravity = Gravity.CENTER-                setBackgroundColor(Color.parseColor("#1B2430"))-                setPadding(dp(24), dp(16), dp(24), dp(16))-                if (maps != null) {-                    maps.icon?.let { icon ->-                        addView(-                            ImageView(context).apply {-                                setImageDrawable(icon)-                                contentDescription = maps.label.toString()-                                layoutParams = LinearLayout.LayoutParams(dp(72), dp(72))-                            },-                        )-                    }-                    addView(-                        TextView(context).apply {-                            text = maps.label.toString()-                            setTextColor(Color.WHITE)-                            textSize = 20f-                            gravity = Gravity.CENTER-                            setPadding(0, dp(8), 0, 0)-                        },-                    )-                    isClickable = true-                    isFocusable = true-                    setOnClickListener { context.startActivity(maps.launch) }-                } else {-                    addView(-                        TextView(context).apply {-                            text = context.getString(R.string.car_no_apps)-                            setTextColor(Color.parseColor("#8AB4F8"))-                            textSize = 18f-                            gravity = Gravity.CENTER-                        },-                    )-                }-            }-        }--        /**-         * The app-drawer overlay (`drawer_contents`): full content-area sheet-         * with an "Apps" heading and the app grid in the gearhead launcher-         * item shape (84dp circular icons, 24sp centered single-line labels,-         * 156dp tiles). Starts GONE; the hotseat drawer cell opens it, the-         * dashboard facet button or a launch closes it.-         */-        private fun appDrawer(apps: List<CarApp>): View {-            return LinearLayout(context).apply {-                orientation = LinearLayout.VERTICAL-                setBackgroundColor(Color.parseColor("#101418"))-                layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)-                visibility = View.GONE-                setPadding(dp(16), dp(16), dp(16), dp(16))-                addView(-                    TextView(context).apply {-                        text = context.getString(R.string.car_drawer_apps)-                        setTextColor(Color.WHITE)-                        textSize = 28f-                        setPadding(0, 0, 0, dp(16))-                    },-                )-                if (apps.isEmpty()) {-                    addView(-                        TextView(context).apply {-                            text = context.getString(R.string.car_no_apps)-                            setTextColor(Color.parseColor("#8AB4F8"))-                            textSize = 24f-                            gravity = Gravity.CENTER-                            layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)-                        },-                    )-                } else {-                    addView(-                        GridLayout(context).apply {-                            columnCount = COLUMNS-                            layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)-                            apps.forEach { app ->-                                addView(-                                    launcherItem(app).apply {-                                        layoutParams = GridLayout.LayoutParams().apply {-                                            width = 0-                                            height = dp(156)-                                            columnSpec = GridLayout.spec(-                                                UNDEFINED_COLUMN,-                                                1,-                                                FILL,-                                                1f,-                                            )-                                        }-                                        setOnClickListener {-                                            context.startActivity(app.launch)-                                            drawerView?.visibility = View.GONE-                                        }-                                    },-                                )-                            }-                        },-                    )-                }-            }-        }--        /**-         * One launcher item (`app_launcher_item`): 84dp circular icon over a-         * 24sp centered single-line label. Circular crop via outline clipping-         * (no CardView dependency); focusable for rotary/dpad parity.-         */-        private fun launcherItem(app: CarApp): LinearLayout {-            return LinearLayout(context).apply {-                orientation = LinearLayout.VERTICAL-                gravity = Gravity.CENTER_HORIZONTAL-                setPadding(dp(8), dp(8), dp(8), dp(8))-                isClickable = true-                isFocusable = true-                addView(-                    ImageView(context).apply {-                        setImageDrawable(app.icon)-                        contentDescription = app.label.toString()-                        layoutParams = LinearLayout.LayoutParams(dp(84), dp(84))-                        clipToOutline = true-                        outlineProvider = object : ViewOutlineProvider() {-                            override fun getOutline(view: View, outline: Outline) {-                                outline.setOval(0, 0, view.width, view.height)-                            }-                        }-                    },-                )-                addView(-                    TextView(context).apply {-                        text = app.label.toString()-                        setTextColor(Color.WHITE)-                        textSize = 24f-                        gravity = Gravity.CENTER-                        maxLines = 1-                        layoutParams = LinearLayout.LayoutParams(MATCH, dp(28)).apply {-                            topMargin = dp(16)-                        }-                    },-                )-            }-        }--        private fun appGrid(apps: List<CarApp>): GridLayout {-            return GridLayout(context).apply {-                columnCount = COLUMNS-                setPadding(dp(16), dp(8), dp(16), dp(16))-                layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)-                apps.forEach { app ->-                    addView(-                        appCell(app).apply {-                            layoutParams = GridLayout.LayoutParams().apply {-                                width = 0-                                columnSpec = GridLayout.spec(UNDEFINED_COLUMN, 1, FILL, 1f)-                            }-                        },-                    )-                }-            }-        }--        private fun appCell(app: CarApp): LinearLayout {-            return LinearLayout(context).apply {-                orientation = LinearLayout.VERTICAL-                gravity = Gravity.CENTER-                setPadding(dp(8), dp(16), dp(8), dp(16))-                isClickable = true-                isFocusable = true-                addView(-                    ImageView(context).apply {-                        setImageDrawable(app.icon)-                        contentDescription = app.label.toString()-                        layoutParams = LinearLayout.LayoutParams(dp(72), dp(72))-                    },-                )-                addView(-                    TextView(context).apply {-                        text = app.label.toString()-                        setTextColor(Color.WHITE)-                        textSize = 16f-                        gravity = Gravity.CENTER-                        setPadding(0, dp(8), 0, 0)-                    },-                )-                setOnClickListener { context.startActivity(app.launch) }-            }-        }--        private fun emptyState(): TextView {-            return TextView(context).apply {-                text = context.getString(R.string.car_no_apps)-                setTextColor(Color.parseColor("#8AB4F8"))-                textSize = 20f-                gravity = Gravity.CENTER-                layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)-            }-        }--        private fun dp(value: Int): Int =-            (value * context.resources.displayMetrics.density).toInt()--        private companion object {-            const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT-            const val WRAP = ViewGroup.LayoutParams.WRAP_CONTENT-            const val COLUMNS = 3-            const val UNDEFINED_COLUMN = GridLayout.UNDEFINED-            val FILL: GridLayout.Alignment = GridLayout.FILL--            /** Hotseat shows this many apps before the drawer cell; the rest live in the drawer. */-            const val MAX_DOCK_APPS = 3--            /** Package + label fallback identifying the Maps slot for the nav card. */-            const val MAPS_PACKAGE = "com.vayunmathur.maps"-            const val MAPS_LABEL = "map"--            /**-             * Ceiling for the continuous frame invalidator: the encoder paces-             * output to its own configured rate, so invalidating faster only-             * burns CPU compositing frames the encoder drops.-             */-            const val MAX_INVALIDATE_FPS = 60--            /** Progress fraction in [0,1]; half (indeterminate-ish) with no duration. */-            fun progressFraction(positionMs: Long, durationMs: Long?): Float {-                val duration = durationMs?.takeIf { it > 0 } ?: return 0.5f-                return (positionMs.coerceAtLeast(0).toFloat() / duration).coerceIn(0f, 1f)-            }-        }-    }-     /**      * Now-playing card bounds in display pixels, for ch8 tap routing.      * Compared in presentation root-view coordinates, which are 1:1 with      * display pixels on a virtual display.      */-    private data class TapBounds(val left: Int, val top: Int, val right: Int, val bottom: Int) {+    internal data class TapBounds(val left: Int, val top: Int, val right: Int, val bottom: Int) {         fun contains(x: Float, y: Float): Boolean =             x >= left && x <= right && y >= top && y <= bottom     }
auto/src/main/java/com/vayunmathur/auto/platform/CarDrawerView.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarDrawerView.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarDrawerView.ktnew file mode 100644index 0000000000..0a1904e313--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDrawerView.kt@@ -0,0 +1,704 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.graphics.Color+import android.view.Gravity+import android.view.KeyEvent+import android.view.MotionEvent+import android.view.View+import android.view.ViewConfiguration+import android.view.ViewGroup+import android.widget.FrameLayout+import android.widget.GridLayout+import android.widget.ImageView+import android.widget.LinearLayout+import android.widget.ProgressBar+import android.widget.ScrollView+import android.widget.TextView+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.CarUiMetrics.COLUMNS+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_ACCENT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_NIGHT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_DRAWER_NIGHT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_LOCKOUT_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_LOCKOUT_NIGHT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_PARKED_HEADER+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_ROOT_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_SCRIM_ASSISTANT+import com.vayunmathur.auto.platform.CarUiMetrics.FILL+import com.vayunmathur.auto.platform.CarUiMetrics.MATCH+import com.vayunmathur.auto.platform.CarUiMetrics.UNDEFINED_COLUMN+import com.vayunmathur.auto.platform.CarUiMetrics.WRAP++/**+ * The app-drawer overlay (`drawer_contents`): full content-area sheet with+ * a 96dp header shadow, an "Apps" heading and the scrollable app list in+ * the gearhead launcher item shape (84dp circular icons, 24sp centered+ * single-line labels, 156dp tiles). Starts GONE; the hotseat drawer cell+ * opens it, the dashboard facet button, scrim tap, BACK, focus loss,+ * launcher taps or trip-end park closes it. Empty, loading, truncated,+ * lockout and parked-browsing states included, plus the alpha-jump+ * fast-scroll, the drawer scrim, voice plate, assistant scrim and AppDecor+ * header stubs.+ *+ * Owns its views; the presentation drives state through open/close and the+ * state setters, and recolors through [setNight]. Contents + alpha keys+ * inflate lazily on first open (the `drawer_stub` /+ * `alpha_jump_layout_stub` seams). Views, not Compose (private display, no+ * lifecycle owner).+ */+internal class CarDrawerView(+    private val context: Context,+    private val apps: List<CarApp>,+) {+    private fun dp(value: Int): Int = context.carDp(value)++    private var drawerPane: LinearLayout? = null+    private var drawerList: DrawerListView? = null+    private var drawerGrid: GridLayout? = null+    private var drawerEmpty: TextView? = null+    private var drawerProgress: ProgressBar? = null+    private var truncatedCard: LinearLayout? = null+    private var lockoutView: FrameLayout? = null+    private var lockoutScrim: View? = null+    private var parkedHeader: LinearLayout? = null+    private var alphaFab: TextView? = null+    private var alphaKeyboard: GridLayout? = null+    private var drawerShadow: View? = null+    /** Drawer contents (list + states) built on first open. */+    private var drawerContentsInflated = false+    /** Alpha-jump views built on first drawer open. */+    private var alphaJumpInflated = false+    /** Launcher labels for the night text-alpha delta (1 day / 0.88 night). */+    private val launcherLabels = mutableListOf<TextView>()++    /** Driving-restriction gate + night flag, pushed by the presentation. */+    var drivingRestricted: Boolean = false+    var nightDark: Boolean = false++    /** The assembled pane; add once to the content frame. */+    val pane: LinearLayout = appDrawer()++    /** The scrim; add once beside the pane. */+    val scrim: View = drawerScrimView()++    /** Voice-plate slot; add once. */+    val voicePlateView: View = voicePlate()++    /** Assistant scrim; add once. */+    val assistantScrimView: View = assistantScrimView()++    /** AppDecor header stub; add once to the root. */+    val decorHeader: LinearLayout = appDecorHeader()++    /** True while the pane is visible. */+    val isOpen: Boolean get() = drawerPane?.visibility == View.VISIBLE++    /** Clears view refs; call from `onStop`. */+    fun clear() {+        drawerPane = null+        drawerList = null+        drawerGrid = null+        drawerEmpty = null+        drawerProgress = null+        truncatedCard = null+        lockoutView = null+        lockoutScrim = null+        parkedHeader = null+        alphaFab = null+        alphaKeyboard = null+        drawerShadow = null+        launcherLabels.clear()+    }++    /**+     * Opens the drawer: lazy-inflates contents + alpha-jump on first+     * open, shows the 96dp-end-margin pane, and fades the scrim in from+     * transparent to the 0.8 dim. Main thread only.+     */+    fun openDrawer() {+        ensureDrawerContents()+        ensureAlphaJump()+        drawerPane?.visibility = View.VISIBLE+        applyLockout()+    }++    /**+     * Closes the drawer. Main thread only. Called from the scrim tap, the+     * BACK key, launcher taps, the Home facet button, focus loss, and+     * trip-end park.+     */+    fun closeDrawer() {+        drawerPane?.visibility = View.GONE+    }++    /** Shows the lockout scrim only when restricted AND the drawer is open. */+    fun applyLockout() {+        val pane = drawerPane ?: return+        val show = drivingRestricted && pane.visibility == View.VISIBLE+        lockoutView?.visibility = if (show) View.VISIBLE else View.GONE+        lockoutScrim?.setBackgroundColor(+            Color.parseColor(if (nightDark) COLOR_LOCKOUT_NIGHT else COLOR_LOCKOUT_DAY),+        )+    }++    /**+     * Shows or hides the drawer loading spinner (48dp indeterminate).+     * Main thread only.+     */+    fun setDrawerLoading(loading: Boolean) {+        drawerProgress?.visibility = if (loading) View.VISIBLE else View.GONE+    }++    /**+     * Shows or hides the truncated-list card (88dp, bottom). Main thread only.+     */+    fun setDrawerTruncated(truncated: Boolean) {+        truncatedCard?.visibility = if (truncated) View.VISIBLE else View.GONE+    }++    /**+     * Shows or hides the parked-browsing exit header (88dp). Main thread only.+     */+    fun setParkedBrowsing(active: Boolean) {+        parkedHeader?.visibility = if (active) View.VISIBLE else View.GONE+    }++    /**+     * Shows the alpha-jump fast-scroll entry points once the list is+     * long enough to need them; the FAB reveals the keyboard on tap.+     * Main thread only.+     */+    fun setAlphaJumpVisible(visible: Boolean) {+        ensureAlphaJump()+        alphaFab?.visibility = if (visible) View.VISIBLE else View.GONE+        if (!visible) alphaKeyboard?.visibility = View.GONE+    }++    /** Recolors pane + shadow + keyboard + labels for night. Main thread only. */+    fun setNight(dark: Boolean) {+        nightDark = dark+        drawerPane?.setBackgroundColor(+            Color.parseColor(if (dark) COLOR_DRAWER_NIGHT else COLOR_ROOT_DAY),+        )+        drawerShadow?.setBackgroundColor(+            Color.parseColor(if (dark) COLOR_CARD_NIGHT else COLOR_CARD_DAY),+        )+        alphaKeyboard?.setBackgroundColor(+            Color.parseColor(if (dark) COLOR_DRAWER_NIGHT else COLOR_ROOT_DAY),+        )+        launcherLabels.forEach { it.alpha = if (dark) 0.88f else 1f }+        applyLockout()+    }++    private fun appDrawer(): LinearLayout {+        return LinearLayout(context).apply {+            orientation = LinearLayout.VERTICAL+            setBackgroundColor(Color.parseColor(COLOR_ROOT_DAY))+            layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)+            visibility = View.GONE+            setPadding(dp(16), dp(16), dp(16), dp(16))+            layoutParams = (layoutParams as ViewGroup.LayoutParams).also {+                // 96dp end margin: the drawer never covers the full width+                // (`drawer_layout.xml` `layout_marginEnd="96dp"`).+                if (it is ViewGroup.MarginLayoutParams) it.marginEnd = dp(96)+            }+            // 96dp header shadow (`drawer_shadow`, card background).+            addView(+                View(context).apply {+                    setBackgroundColor(Color.parseColor(COLOR_CARD_DAY))+                    layoutParams = LinearLayout.LayoutParams(MATCH, dp(96))+                    isFocusable = false+                }.also { drawerShadow = it },+            )+            addView(+                TextView(context).apply {+                    text = context.getString(R.string.car_drawer_apps)+                    setTextColor(Color.WHITE)+                    textSize = 28f+                    setPadding(0, 0, 0, dp(16))+                },+            )+            // Parked-browsing exit header (88dp, `#ff37474f`, radius 2dp):+            // GONE unless unlimited browsing is active.+            addView(+                LinearLayout(context).apply {+                    orientation = LinearLayout.HORIZONTAL+                    gravity = android.view.Gravity.CENTER_VERTICAL+                    setBackgroundColor(Color.parseColor(COLOR_PARKED_HEADER))+                    visibility = View.GONE+                    layoutParams = LinearLayout.LayoutParams(MATCH, dp(88)).apply {+                        bottomMargin = dp(8)+                    }+                    addView(+                        TextView(context).apply {+                            text = context.getString(R.string.car_browsing_locked)+                            setTextColor(Color.WHITE)+                            textSize = 18f+                            layoutParams = LinearLayout.LayoutParams(0, WRAP, 1f).apply {+                                marginStart = dp(22)+                            }+                        },+                    )+                    addView(+                        TextView(context).apply {+                            text = context.getString(R.string.car_browsing_exit)+                            setTextColor(Color.WHITE)+                            textSize = 18f+                            gravity = Gravity.CENTER+                            isClickable = true+                            isFocusable = true+                            background = context.carFocusRingBackground()+                            layoutParams = LinearLayout.LayoutParams(WRAP, WRAP).apply {+                                marginStart = dp(24)+                                marginEnd = dp(16)+                            }+                            setPadding(dp(16), dp(8), dp(16), dp(8))+                            setOnClickListener { setParkedBrowsing(false) }+                        },+                    )+                    parkedHeader = this+                },+            )+            // Loading spinner (48dp indeterminate, centered, gone).+            addView(+                ProgressBar(context).apply {+                    visibility = View.GONE+                    layoutParams = LinearLayout.LayoutParams(dp(48), dp(48)).apply {+                        gravity = Gravity.CENTER+                    }+                    isIndeterminate = true+                    drawerProgress = this+                },+            )+            // Scrollable list (PagedListView parity: scrollbar, rotary+            // 50px steps / 15px drag, dpad 22/21/283/282). Contents+            // inflate on first open (the `drawer_stub` seam).+            addView(+                DrawerListView(context).apply {+                    layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)+                    setPadding(0, 0, dp(32), 0)+                    onDrawerLeft = { closeDrawer() }+                    drawerList = this+                },+            )+            // Empty state (Body1 32sp centered, gone unless no apps).+            addView(+                TextView(context).apply {+                    text = context.getString(R.string.car_drawer_empty)+                    setTextColor(Color.parseColor(COLOR_ACCENT))+                    textSize = 32f+                    gravity = Gravity.CENTER+                    visibility = if (apps.isEmpty()) View.VISIBLE else View.GONE+                    layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)+                    drawerEmpty = this+                },+            )+            // Truncated-list card (88dp bottom, gone).+            addView(+                LinearLayout(context).apply {+                    orientation = LinearLayout.HORIZONTAL+                    gravity = Gravity.CENTER_VERTICAL+                    setBackgroundColor(Color.parseColor(COLOR_PARKED_HEADER))+                    visibility = View.GONE+                    layoutParams = LinearLayout.LayoutParams(MATCH, dp(88)).apply {+                        topMargin = dp(8)+                    }+                    addView(+                        TextView(context).apply {+                            text = context.getString(R.string.car_drawer_empty)+                            setTextColor(Color.WHITE)+                            textSize = 18f+                            gravity = Gravity.CENTER_VERTICAL+                            layoutParams = LinearLayout.LayoutParams(MATCH, MATCH).apply {+                                marginStart = dp(22)+                                marginEnd = dp(22)+                            }+                        },+                    )+                    truncatedCard = this+                },+            )+            // Lockout overlay: scrim + 26sp text, gone unless+            // driving-restricted while open.+            addView(+                FrameLayout(context).apply {+                    visibility = View.GONE+                    layoutParams = LinearLayout.LayoutParams(MATCH, MATCH)+                    addView(+                        View(context).apply {+                            setBackgroundColor(Color.parseColor(COLOR_LOCKOUT_DAY))+                            layoutParams = FrameLayout.LayoutParams(MATCH, MATCH)+                            lockoutScrim = this+                        },+                    )+                    addView(+                        TextView(context).apply {+                            text = context.getString(R.string.car_drawer_lockout)+                            setTextColor(Color.WHITE)+                            textSize = 26f+                            gravity = Gravity.CENTER+                            layoutParams = FrameLayout.LayoutParams(WRAP, WRAP, Gravity.CENTER)+                        },+                    )+                    lockoutView = this+                },+            )+            // Alpha-jump FAB (96dp, end/top, margins 48/22dp, unfocusable)+            // + keyboard (marginTop 96dp, fixed mode, square keys, gone).+            addView(+                TextView(context).apply {+                    text = context.getString(R.string.car_alpha_jump_glyph)+                    setTextColor(Color.WHITE)+                    textSize = 20f+                    gravity = Gravity.CENTER+                    visibility = View.GONE+                    isClickable = true+                    isFocusable = false+                    layoutParams = LinearLayout.LayoutParams(dp(96), dp(96)).apply {+                        gravity = Gravity.END or Gravity.TOP+                        topMargin = dp(48)+                        marginEnd = dp(22)+                    }+                    setOnClickListener { alphaKeyboard?.visibility = View.VISIBLE }+                    alphaFab = this+                },+            )+            addView(+                GridLayout(context).apply {+                    columnCount = 6+                    visibility = View.GONE+                    setBackgroundColor(Color.parseColor(COLOR_CARD_DAY))+                    layoutParams = LinearLayout.LayoutParams(MATCH, MATCH).apply {+                        topMargin = dp(96)+                    }+                    alphaKeyboard = this+                },+            )+            drawerPane = this+        }+    }++    /** Builds drawer list contents on first open. Main thread only. */+    private fun ensureDrawerContents() {+        if (drawerContentsInflated) return+        drawerContentsInflated = true+        val list = drawerList ?: return+        val grid = GridLayout(context).apply {+            columnCount = COLUMNS+            layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)+        }+        apps.forEach { app ->+            grid.addView(+                launcherItem(app).apply {+                    layoutParams = GridLayout.LayoutParams().apply {+                        width = 0+                        height = dp(156)+                        columnSpec = GridLayout.spec(+                            UNDEFINED_COLUMN,+                            1,+                            FILL,+                            1f,+                        )+                    }+                    setOnClickListener {+                        context.startActivity(app.launch)+                        closeDrawer()+                    }+                },+            )+        }+        list.addView(grid)+        drawerGrid = grid+        drawerEmpty?.visibility = if (apps.isEmpty()) View.VISIBLE else View.GONE+        drawerProgress?.visibility = View.GONE+    }++    /** Builds A-Z + 0-9 alpha keys on first drawer open. Main thread only. */+    private fun ensureAlphaJump() {+        if (alphaJumpInflated) return+        alphaJumpInflated = true+        val keyboard = alphaKeyboard ?: return+        ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890").forEach { char ->+            keyboard.addView(+                SquareKey(context).apply {+                    text = char.toString()+                    setTextColor(Color.WHITE)+                    textSize = 20f+                    gravity = Gravity.CENTER+                    isClickable = true+                    isFocusable = true+                    layoutParams = GridLayout.LayoutParams().apply {+                        width = 0+                        columnSpec = GridLayout.spec(UNDEFINED_COLUMN, 1, FILL, 1f)+                    }+                    setOnClickListener { jumpToLetter(char) }+                },+            )+        }+    }++    /** Alpha-jump: focuses the first launcher whose label starts with [char]. */+    private fun jumpToLetter(char: Char) {+        val grid = drawerGrid ?: return+        for (i in 0 until grid.childCount) {+            val item = grid.getChildAt(i) as? LinearLayout ?: continue+            val label = (item.getChildAt(1) as? TextView)?.text?.toString() ?: continue+            if (label.startsWith(char, ignoreCase = true)) {+                item.requestFocus()+                item.parent?.let { parent ->+                    (parent.parent as? DrawerListView)?.smoothScrollTo(0, item.top)+                }+                return+            }+        }+    }++    /**+     * One launcher item (`app_launcher_item`): 84dp circular icon over a+     * 24sp centered single-line label with 16dp top margin and 28dp label+     * height, 10dp L/R + 14dp T/B cell padding, focus background, Roboto+     * label. Notification + badge slots (22dp / 34dp / 28dp) stubbed gone+     * with no unread source. Circular crop via outline clipping (no+     * CardView dependency); focusable for rotary/dpad parity.+     */+    private fun launcherItem(app: CarApp): LinearLayout {+        return LinearLayout(context).apply {+            orientation = LinearLayout.VERTICAL+            gravity = Gravity.CENTER_HORIZONTAL+            setPadding(dp(10), dp(14), dp(10), dp(14))+            background = context.carFocusRingBackground()+            isClickable = true+            isFocusable = true+            visibility = View.VISIBLE+            addView(+                android.widget.ImageView(context).apply {+                    setImageDrawable(app.icon)+                    contentDescription = app.label.toString()+                    layoutParams = LinearLayout.LayoutParams(dp(84), dp(84))+                    clipToOutline = true+                    outlineProvider = circularOutline()+                },+            )+            addView(+                TextView(context).apply {+                    text = app.label.toString()+                    setTextColor(Color.WHITE)+                    textSize = 24f+                    gravity = Gravity.CENTER+                    maxLines = 1+                    ellipsize = android.text.TextUtils.TruncateAt.END+                    layoutParams = LinearLayout.LayoutParams(MATCH, dp(28)).apply {+                        topMargin = dp(16)+                    }+                    launcherLabels.add(this)+                },+            )+        }+    }++    /**+     * The drawer scrim: full content-area dim at 0.8+     * (`CarDrawerLayout.k(color)` folds `alpha * 0.8` into the top byte)+     * with a transparent motion variant (the `MotionFilteringDrawerLayout`+     * seam). Starts transparent on open and posts to the dim, mirroring+     * the scrim fade; taps close the drawer. Starts GONE.+     */+    private fun drawerScrimView(): View {+        return View(context).apply {+            setBackgroundColor(Color.argb(204, 0x10, 0x14, 0x18))+            layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)+            visibility = View.GONE+            isClickable = true+            isFocusable = false+            setOnClickListener { closeDrawer() }+        }+    }++    /** Voice-plate slot (`voice_plate`): gone match/match bottom window. */+    private fun voicePlate(): View {+        return View(context).apply {+            setBackgroundColor(Color.TRANSPARENT)+            visibility = View.GONE+            layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)+        }+    }++    /**+     * Assistant overlay (`assistant_scrim`): match/match `#151616`+     * alpha 0.24, focusable. Shown while an assistant turn is active;+     * the service drives visibility (gone with no backend).+     */+    private fun assistantScrimView(): View {+        return View(context).apply {+            setBackgroundColor(Color.parseColor(COLOR_SCRIM_ASSISTANT))+            alpha = 0.24f+            visibility = View.GONE+            layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)+            isFocusable = true+            isClickable = true+        }+    }++    /**+     * The AppDecor header (`adu_status_bar_view`): 96dp underlay with+     * 32dp app icon + 26sp condensed title, 320dp search card and+     * 96dp drawer/mic/search buttons. Gone with no template host; kept+     * so the metrics exist when one arrives.+     */+    private fun appDecorHeader(): LinearLayout {+        return LinearLayout(context).apply {+            orientation = LinearLayout.HORIZONTAL+            gravity = Gravity.CENTER_VERTICAL+            visibility = View.GONE+            layoutParams = LinearLayout.LayoutParams(MATCH, dp(96))+            setPadding(dp(96), 0, 0, 0)+            addView(+                android.widget.ImageView(context).apply {+                    visibility = View.GONE+                    layoutParams = LinearLayout.LayoutParams(dp(32), MATCH)+                },+            )+            addView(+                TextView(context).apply {+                    textSize = 26f+                    setTextColor(Color.WHITE)+                    maxLines = 1+                    ellipsize = android.text.TextUtils.TruncateAt.END+                    layoutParams = LinearLayout.LayoutParams(0, MATCH, 1f)+                },+            )+            addView(+                FrameLayout(context).apply {+                    layoutParams = LinearLayout.LayoutParams(dp(320), MATCH).apply {+                        topMargin = dp(16)+                        bottomMargin = dp(16)+                    }+                    setBackgroundColor(Color.parseColor("#FFFAFAFA"))+                    addView(+                        TextView(context).apply {+                            text = context.getString(R.string.car_search_hint)+                            setTextColor(Color.parseColor("#8A000000"))+                            textSize = 26f+                            gravity = Gravity.CENTER_VERTICAL+                            layoutParams = FrameLayout.LayoutParams(MATCH, MATCH).apply {+                                marginStart = dp(16)+                            }+                        },+                    )+                },+            )+        }+    }+}++/**+ * The drawer container (`drawer_container`): unfocusable, with a+ * touchSlop-scaled X-axis intercept mirroring+ * `MotionFilteringDrawerLayout` -- DOWN/UP/CANCEL reset, in-slop MOVE+ * returns false, beyond-slop MOVE intercepts. BACK key-up while open+ * closes via [onDrawerBack].+ */+internal class DrawerContainer(context: Context) : FrameLayout(context) {+    var onDrawerBack: (() -> Unit)? = null+    private val slop: Int = ViewConfiguration.get(context).scaledTouchSlop+    private var downX = 0f++    init {+        isFocusable = View.NOT_FOCUSABLE+    }++    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {+        when (event.action) {+            MotionEvent.ACTION_DOWN -> downX = event.x+            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> downX = 0f+            MotionEvent.ACTION_MOVE ->+                if (kotlin.math.abs(event.x - downX) > slop) return true+        }+        return false+    }++    override fun dispatchKeyEvent(event: KeyEvent): Boolean {+        if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) {+            val close = onDrawerBack+            if (close != null) {+                close()+                return true+            }+        }+        return super.dispatchKeyEvent(event)+    }+}++/**+ * The scrollable drawer list (`PagedListView` parity): a ScrollView with+ * the scrollbar enabled, rotary scroll (50px focus steps, >=15px drag+ * consumes), and dpad routing -- 22 activates the focused item, 21+ * closes the drawer, 283/282 page down/up.+ */+internal class DrawerListView(context: Context) : ScrollView(context) {+    var onDrawerLeft: (() -> Unit)? = null+    private var rotaryRemainder = 0f++    init {+        isVerticalScrollBarEnabled = true+        isFocusable = true+        isClickable = true+    }++    override fun onGenericMotionEvent(event: MotionEvent): Boolean {+        if (event.action == MotionEvent.ACTION_SCROLL &&+            event.getAxisValue(MotionEvent.AXIS_VSCROLL) != 0f+        ) {+            val delta = event.getAxisValue(MotionEvent.AXIS_VSCROLL)+            if (kotlin.math.abs(delta) < 15) return false+            rotaryRemainder += delta+            while (rotaryRemainder >= 50) {+                rotaryRemainder -= 50+                focusSearch(View.FOCUS_DOWN)?.requestFocus()+                smoothScrollBy(0, 50)+            }+            while (rotaryRemainder <= -50) {+                rotaryRemainder += 50+                focusSearch(View.FOCUS_UP)?.requestFocus()+                smoothScrollBy(0, -50)+            }+            return true+        }+        return super.onGenericMotionEvent(event)+    }++    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {+        when (keyCode) {+            KeyEvent.KEYCODE_DPAD_RIGHT -> {+                findFocus()?.performClick()+                return true+            }+            KeyEvent.KEYCODE_DPAD_LEFT -> {+                onDrawerLeft?.invoke()+                return true+            }+            283 -> {+                smoothScrollBy(0, height)+                return true+            }+            282 -> {+                smoothScrollBy(0, -height)+                return true+            }+        }+        return super.onKeyUp(keyCode, event)+    }+}++/** Square alpha-jump key (`AlphaJumpKey.onMeasure(size, size)` parity). */+internal class SquareKey(context: Context) : TextView(context) {+    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {+        val size = getDefaultSize(suggestedMinimumWidth, widthMeasureSpec)+        super.onMeasure(+            MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY),+            MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY),+        )+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/CarMediaCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarMediaCard.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarMediaCard.ktnew file mode 100644index 0000000000..9482269217--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarMediaCard.kt@@ -0,0 +1,325 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.graphics.Color+import android.view.Gravity+import android.view.View+import android.widget.FrameLayout+import android.widget.ImageView+import android.widget.LinearLayout+import android.widget.Space+import android.widget.TextView+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.CarUiMetrics.BUTTON_DISABLED_ALPHA+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_ACCENT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_NIGHT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_SUBTITLE+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_TRACK+import com.vayunmathur.auto.platform.CarUiMetrics.MATCH+import com.vayunmathur.auto.platform.CarUiMetrics.WRAP++/**+ * The dash media card (`frag_dash_media` shape): full-bleed album art with+ * scrim + 24dp source badge, title (28sp, 1 line) + subtitle (24sp), 4dp+ * progress, and the 88dp prev/play/next row (Space weights 1/2/2/1, 12dp+ * insets). The whole text region taps to toggle; the row buttons fire+ * prev/play/next. Starts hidden: the first snapshot decides.+ *+ * Owns its views; the presentation drives state through [update]/[hide]+ * and recolors through [setNight]. Reports layout bounds for ch8 tap+ * routing through [onCardBounds]. Views, not Compose (private display, no+ * lifecycle owner).+ */+internal class CarMediaCardView(+    private val context: Context,+    private val onMediaTap: () -> Unit,+    private val onPreviousTap: () -> Unit,+    private val onNextTap: () -> Unit,+    private val onCardBounds: (Int, Int, Int, Int) -> Unit,+) {+    private fun dp(value: Int): Int = context.carDp(value)++    private var mediaTitle: TextView? = null+    private var mediaSubtitle: TextView? = null+    private var mediaState: TextView? = null+    private var mediaProgress: View? = null+    private var mediaCard: FrameLayout? = null+    private var albumArt: ImageView? = null+    private var sourceBadge: ImageView? = null+    private var mediaButtons: LinearLayout? = null+    private var prevButton: TextView? = null+    private var playButton: TextView? = null+    private var nextButton: TextView? = null++    /** The assembled card; add once to the split. */+    val view: FrameLayout = nowPlayingCard()++    /** Late-wired taps (service wires after `show()` starts the build). */+    var tapMedia: () -> Unit = onMediaTap+    var tapPrevious: () -> Unit = onPreviousTap+    var tapNext: () -> Unit = onNextTap++    /** Hides the card; the cached snapshot is untouched. Main thread only. */+    fun hide() {+        mediaCard?.visibility = View.GONE+    }++    /** Driving-restriction gate: hides the action row. Main thread only. */+    fun setButtonsVisible(visible: Boolean) {+        mediaButtons?.visibility = if (visible) View.VISIBLE else View.GONE+    }++    /** Recolors the card for night. Main thread only. */+    fun setNight(dark: Boolean) {+        mediaCard?.setBackgroundColor(+            Color.parseColor(if (dark) COLOR_CARD_NIGHT else COLOR_CARD_DAY),+        )+    }++    /** Clears view refs; call from `onStop`. */+    fun clear() {+        mediaTitle = null+        mediaSubtitle = null+        mediaState = null+        mediaProgress = null+        mediaCard = null+        albumArt = null+        sourceBadge = null+        mediaButtons = null+        prevButton = null+        playButton = null+        nextButton = null+    }++    /**+     * Applies a snapshot to the card. Main thread only.+     *+     * Visibility follows `shouldShowCard()`: `GONE` when idle so the car+     * shows no card with nothing playing; `VISIBLE` while playing, and+     * while paused with a title so resume keeps its context. Artwork and+     * prev/next enablement follow the snapshot (absent art hides the+     * art view rather than faking it).+     */+    fun update(info: NowPlayingInfo) {+        val card = mediaCard ?: return+        card.visibility = if (info.shouldShowCard()) View.VISIBLE else View.GONE+        mediaTitle?.text = info.title ?: context.getString(R.string.car_now_playing_unknown)+        mediaSubtitle?.text = info.artist ?: context.getString(R.string.car_now_playing_unknown_artist)+        mediaState?.text = context.getString(+            if (info.playing) R.string.car_now_playing_playing+            else R.string.car_now_playing_paused,+        )+        playButton?.text = context.getString(+            if (info.playing) R.string.car_media_pause_glyph else R.string.car_media_play_glyph,+        )+        playButton?.contentDescription = context.getString(+            if (info.playing) R.string.car_media_pause else R.string.car_media_play,+        )+        prevButton?.isEnabled = info.hasPrevious+        nextButton?.isEnabled = info.hasNext+        prevButton?.alpha = if (info.hasPrevious) 1f else BUTTON_DISABLED_ALPHA+        nextButton?.alpha = if (info.hasNext) 1f else BUTTON_DISABLED_ALPHA+        updateArtwork(info)+        val progress = mediaProgress ?: return+        val fraction = CarUiMetrics.progressFraction(info.positionMs, info.durationMs)+        val bar = mediaCard ?: return+        // Resize the fill once laid out: the bar width is only known after+        // the layout pass, and the encoder surface picks the re-layout up on+        // the next frame.+        progress.post {+            val total = bar.width+            if (total > 0) {+                progress.layoutParams = progress.layoutParams.apply {+                    width = (total * fraction).toInt().coerceIn(0, total)+                }+                progress.requestLayout()+            }+        }+    }++    /** Shows decoded artwork, the display icon, or hides the art view. Main thread only. */+    private fun updateArtwork(info: NowPlayingInfo) {+        val art = albumArt ?: return+        val bytes = info.artworkData+        if (bytes != null && bytes.isNotEmpty()) {+            val bitmap = runCatching {+                android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size)+            }.getOrNull()+            if (bitmap != null) {+                art.setImageBitmap(bitmap)+                art.visibility = View.VISIBLE+                return+            }+        }+        val icon = info.displayIcon+        if (icon != null) {+            art.setImageDrawable(icon)+            art.visibility = View.VISIBLE+            return+        }+        art.visibility = View.GONE+    }++    private fun nowPlayingCard(): FrameLayout {+        val card = FrameLayout(context).apply {+            setBackgroundColor(Color.parseColor(COLOR_CARD_DAY))+            layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)+            isClickable = true+            isFocusable = true+            // Starts hidden: the first snapshot decides, and with nothing+            // playing there is nothing to show.+            visibility = View.GONE+        }+        card.addView(+            ImageView(context).apply {+                scaleType = ImageView.ScaleType.CENTER_CROP+                layoutParams = FrameLayout.LayoutParams(MATCH, MATCH)+                visibility = View.GONE+                albumArt = this+            },+        )+        card.addView(+            View(context).apply {+                // Album-art scrim over the full bleed (tinted dark).+                setBackgroundColor(Color.argb(153, 0x10, 0x14, 0x18))+                layoutParams = FrameLayout.LayoutParams(MATCH, MATCH)+            },+        )+        card.addView(+            ImageView(context).apply {+                // Source badge: 24dp circle (`dashboard_media_badge_size`).+                layoutParams = FrameLayout.LayoutParams(dp(24), dp(24), Gravity.TOP or Gravity.END)+                clipToOutline = true+                outlineProvider = circularOutline()+                visibility = View.GONE+                sourceBadge = this+            },+        )+        val textColumn = LinearLayout(context).apply {+            orientation = LinearLayout.VERTICAL+            gravity = Gravity.START+            setPadding(dp(5), dp(4), dp(5), dp(7))+            layoutParams = FrameLayout.LayoutParams(MATCH, WRAP)+            background = context.carFocusRingBackground()+            isClickable = true+            isFocusable = true+            setOnClickListener { tapMedia() }+        }+        textColumn.addView(+            TextView(context).apply {+                setTextColor(Color.parseColor(COLOR_ACCENT))+                textSize = 14f+                text = context.getString(R.string.car_now_playing)+            },+        )+        textColumn.addView(+            TextView(context).apply {+                textSize = 28f+                maxLines = 1+                ellipsize = android.text.TextUtils.TruncateAt.END+                setTextColor(Color.WHITE)+                includeFontPadding = false+                setPadding(0, dp(5), 0, 0)+                mediaTitle = this+            },+        )+        textColumn.addView(+            TextView(context).apply {+                textSize = 24f+                maxLines = 1+                ellipsize = android.text.TextUtils.TruncateAt.END+                setTextColor(Color.parseColor(COLOR_SUBTITLE))+                setPadding(0, 0, 0, dp(5))+                mediaSubtitle = this+            },+        )+        textColumn.addView(+            TextView(context).apply {+                textSize = 14f+                setTextColor(Color.parseColor(COLOR_ACCENT))+                mediaState = this+            },+        )+        card.addView(textColumn)+        val track = View(context).apply {+            setBackgroundColor(Color.parseColor(COLOR_TRACK))+            layoutParams = FrameLayout.LayoutParams(MATCH, dp(4), Gravity.BOTTOM).apply {+                bottomMargin = dp(4)+            }+        }+        card.addView(track)+        val fill = View(context).apply {+            setBackgroundColor(Color.parseColor(COLOR_ACCENT))+            layoutParams = FrameLayout.LayoutParams(0, dp(4), Gravity.BOTTOM or Gravity.START).apply {+                bottomMargin = dp(4)+            }+            mediaProgress = this+        }+        card.addView(fill)+        val row = LinearLayout(context).apply {+            orientation = LinearLayout.HORIZONTAL+            gravity = Gravity.CENTER_VERTICAL+            layoutParams = FrameLayout.LayoutParams(MATCH, WRAP, Gravity.BOTTOM).apply {+                bottomMargin = dp(4)+            }+            mediaButtons = this+        }+        row.addView(Space(context).apply { layoutParams = LinearLayout.LayoutParams(0, 0, 1f) })+        row.addView(+            mediaActionButton(+                context.getString(R.string.car_media_prev_glyph),+                context.getString(R.string.car_media_previous),+            ) { tapPrevious() }.also { prevButton = it },+        )+        row.addView(Space(context).apply { layoutParams = LinearLayout.LayoutParams(0, 0, 2f) })+        row.addView(+            mediaActionButton(+                context.getString(R.string.car_media_play_glyph),+                context.getString(R.string.car_media_play),+            ) { tapMedia() }.also { playButton = it },+        )+        row.addView(Space(context).apply { layoutParams = LinearLayout.LayoutParams(0, 0, 2f) })+        row.addView(+            mediaActionButton(+                context.getString(R.string.car_media_next_glyph),+                context.getString(R.string.car_media_next),+            ) { tapNext() }.also { nextButton = it },+        )+        row.addView(Space(context).apply { layoutParams = LinearLayout.LayoutParams(0, 0, 1f) })+        card.addView(row)+        // Report layout bounds for ch8 tap routing once the view is placed.+        card.viewTreeObserver.addOnGlobalLayoutListener(+            object : android.view.ViewTreeObserver.OnGlobalLayoutListener {+                override fun onGlobalLayout() {+                    val loc = IntArray(2)+                    card.getLocationOnScreen(loc)+                    onCardBounds(loc[0], loc[1], loc[0] + card.width, loc[1] + card.height)+                }+            },+        )+        mediaCard = card+        return card+    }++    /** One 88dp (`dashboard_media_action_size`) media action button with 12dp insets. */+    private fun mediaActionButton(glyph: String, description: String, onTap: () -> Unit): TextView {+        return TextView(context).apply {+            text = glyph+            contentDescription = description+            setTextColor(Color.WHITE)+            textSize = 28f+            gravity = Gravity.CENTER+            background = context.carFocusRingBackground()+            layoutParams = LinearLayout.LayoutParams(dp(88), dp(88)).apply {+                leftMargin = dp(12)+                rightMargin = dp(12)+                topMargin = dp(12)+                bottomMargin = dp(12)+            }+            isClickable = true+            isFocusable = true+            setOnClickListener { onTap() }+        }+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/CarNavCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarNavCard.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarNavCard.ktnew file mode 100644index 0000000000..eeb7af79c3--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarNavCard.kt@@ -0,0 +1,249 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.graphics.Color+import android.graphics.SurfaceTexture+import android.view.Gravity+import android.view.Surface+import android.view.TextureView+import android.view.View+import android.view.ViewGroup+import android.widget.ImageView+import android.widget.LinearLayout+import android.widget.TextView+import com.vayunmathur.auto.R+import com.vayunmathur.auto.protocol.NavSnapshot+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_NIGHT+import com.vayunmathur.auto.platform.CarUiMetrics.MAPS_LABEL+import com.vayunmathur.auto.platform.CarUiMetrics.MAPS_PACKAGE+import com.vayunmathur.auto.platform.CarUiMetrics.MATCH+import com.vayunmathur.auto.platform.CarUiMetrics.WRAP++/**+ * The nav half of the split: live map (`CarMapsMirror` into a+ * `TextureView`) with the guidance step header only while guidance+ * is active. Without Maps data this still draws the basemap + puck+ * from phone GPS; the step views stay GONE idle (never faked), and+ * only when no map backend exists at all does the launch tile show.+ *+ * The step header maps `DetailedNavigationStepView` ++ * `NavigationTravelEstimateView`: turn symbol / distance /+ * description + lanes image / containers + arrival / time-distance,+ * every field GONE-if-empty. `NavSnapshot` carries no lane art, ETA,+ * or arrival time, so those slots stay GONE (stubbed, not guessed);+ * the banner + distance it does carry render live.+ *+ * Owns its views; the presentation drives state through [update] and+ * recolors through [setNight]. The map surface forwards to the session+ * mirror through [mapSurfaceListener]. Views, not Compose (private+ * display, no lifecycle owner).+ */+internal class CarNavCardView(+    private val context: Context,+    private val apps: List<CarApp>,+) {+    private fun dp(value: Int): Int = context.carDp(value)++    private var navCardView: LinearLayout? = null+    private var stepContainer: LinearLayout? = null+    private var navDistance: TextView? = null+    private var navBanner: TextView? = null++    /**+     * Receives the nav-card map surface: (surface, w, h), or (null, 0, 0)+     * when the TextureView is destroyed. The session's mirror attaches on+     * non-null and releases on null; unset means no map backend.+     */+    var mapSurfaceListener: ((Surface?, Int, Int) -> Unit)? = null++    /** The assembled card; add once to the split. */+    val view: LinearLayout = navCard()++    /** Recolors the card for night. Main thread only. */+    fun setNight(dark: Boolean) {+        navCardView?.setBackgroundColor(+            Color.parseColor(if (dark) COLOR_CARD_NIGHT else COLOR_CARD_DAY),+        )+    }++    /** Clears view refs; call from `onStop`. */+    fun clear() {+        navCardView = null+        stepContainer = null+        navDistance = null+        navBanner = null+    }++    /**+     * Pushes one guidance snapshot to the nav banner. Main thread only.+     * The banner shows only while guidance is active with a road or+     * maneuver to announce; otherwise GONE (idle map, no fake banner).+     * The step container mirrors the banner gate and additionally drives+     * the distance field from `nextTurnDistanceM`.+     */+    fun update(snapshot: NavSnapshot) {+        val banner = navBanner ?: return+        val road = snapshot.nextRoad?.takeIf { it.isNotBlank() }+        val turn = snapshot.maneuver?.takeIf { it.isNotBlank() }+        val text = when {+            turn != null && road != null -> "$turn · $road"+            turn != null -> turn+            road != null -> road+            else -> null+        }+        if (snapshot.guidanceActive && text != null) {+            banner.text = text+            banner.visibility = View.VISIBLE+        } else {+            banner.visibility = View.GONE+        }+        val distance = navDistance+        if (distance != null) {+            val meters = if (snapshot.guidanceActive) snapshot.nextTurnDistanceM else null+            if (meters != null) {+                distance.text = context.getString(R.string.car_nav_distance_meters, meters)+                distance.visibility = View.VISIBLE+            } else {+                distance.visibility = View.GONE+            }+        }+        stepContainer?.visibility =+            if (banner.visibility == View.VISIBLE || distance?.visibility == View.VISIBLE) {+                View.VISIBLE+            } else {+                View.GONE+            }+    }++    private fun navCard(): LinearLayout {+        val maps = apps.firstOrNull {+            it.launch.`package` == MAPS_PACKAGE ||+                it.label.toString().contains(MAPS_LABEL, ignoreCase = true)+        }+        return LinearLayout(context).apply {+            orientation = LinearLayout.VERTICAL+            gravity = Gravity.CENTER+            setBackgroundColor(Color.parseColor(COLOR_CARD_DAY))+            setPadding(dp(8), dp(8), dp(8), dp(8))+            addView(+                LinearLayout(context).apply {+                    orientation = LinearLayout.VERTICAL+                    gravity = Gravity.CENTER+                    visibility = View.GONE+                    layoutParams = LinearLayout.LayoutParams(MATCH, WRAP).apply {+                        bottomMargin = dp(8)+                    }+                    stepContainer = this+                    addView(+                        LinearLayout(context).apply {+                            orientation = LinearLayout.HORIZONTAL+                            gravity = Gravity.CENTER_VERTICAL+                            layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)+                            // Turn symbol (`turn_symbol`): no maneuver+                            // drawable exists in MA -- GONE stub.+                            addView(+                                ImageView(context).apply {+                                    visibility = View.GONE+                                    layoutParams = LinearLayout.LayoutParams(WRAP, WRAP)+                                },+                            )+                            addView(+                                LinearLayout(context).apply {+                                    orientation = LinearLayout.VERTICAL+                                    layoutParams = LinearLayout.LayoutParams(0, WRAP, 1f)+                                    addView(+                                        TextView(context).apply {+                                            textSize = 24f+                                            setTextColor(Color.WHITE)+                                            gravity = Gravity.CENTER+                                            visibility = View.GONE+                                            navBanner = this+                                        },+                                    )+                                    addView(+                                        TextView(context).apply {+                                            textSize = 24f+                                            setTextColor(Color.WHITE)+                                            gravity = Gravity.CENTER+                                            visibility = View.GONE+                                            navDistance = this+                                        },+                                    )+                                },+                            )+                        },+                    )+                    // Lanes (`lanes_image` + `lanes_container`): no lane+                    // data in `NavSnapshot` -- GONE stubs.+                    addView(+                        ImageView(context).apply {+                            visibility = View.GONE+                            layoutParams = LinearLayout.LayoutParams(WRAP, WRAP)+                        },+                    )+                    addView(+                        LinearLayout(context).apply {+                            orientation = LinearLayout.HORIZONTAL+                            visibility = View.GONE+                            layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)+                        },+                    )+                    // Travel estimate (`arrival_time_text` /+                    // `time_and_distance_text`): no ETA in `NavSnapshot`+                    // -- GONE stubs.+                    addView(+                        LinearLayout(context).apply {+                            orientation = LinearLayout.VERTICAL+                            visibility = View.GONE+                            layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)+                            addView(+                                TextView(context).apply {+                                    visibility = View.GONE+                                },+                            )+                            addView(+                                TextView(context).apply {+                                    visibility = View.GONE+                                },+                            )+                        },+                    )+                },+            )+            addView(+                TextureView(context).apply {+                    layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)+                    surfaceTextureListener = object : TextureView.SurfaceTextureListener {+                        override fun onSurfaceTextureAvailable(+                            surface: SurfaceTexture,+                            width: Int,+                            height: Int,+                        ) {+                            mapSurfaceListener?.invoke(Surface(surface), width, height)+                        }++                        override fun onSurfaceTextureSizeChanged(+                            surface: SurfaceTexture,+                            width: Int,+                            height: Int,+                        ) = Unit++                        override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {+                            mapSurfaceListener?.invoke(null, 0, 0)+                            return true+                        }++                        override fun onSurfaceTextureUpdated(surface: SurfaceTexture) = Unit+                    }+                },+            )+            if (maps != null) {+                isClickable = true+                isFocusable = true+                setOnClickListener { context.startActivity(maps.launch) }+            }+            navCardView = this+        }+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/CarPresentation.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarPresentation.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarPresentation.ktnew file mode 100644index 0000000000..7ee89d9a1b--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarPresentation.kt@@ -0,0 +1,441 @@+package com.vayunmathur.auto.platform++import android.app.Presentation+import android.content.Context+import android.graphics.Color+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.view.Gravity+import android.view.Surface+import android.view.View+import android.view.ViewGroup+import android.widget.FrameLayout+import android.widget.LinearLayout+import com.vayunmathur.auto.protocol.NavSnapshot+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_DRAWER_NIGHT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_RAIL_NIGHT+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_ROOT_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.MATCH+import com.vayunmathur.auto.platform.CarUiMetrics.MAX_INVALIDATE_FPS+import com.vayunmathur.auto.platform.CarUiMetrics.WRAP+import java.text.DateFormat+import java.util.Date++/**+ * The car launcher presentation: a driving-safe home screen with Coolwalk+ * split cards (nav + media + call), a facet rail, an app drawer,+ * template-decor stubs and scrims, composed from the `Car*View` components.+ *+ * The presentation owns assembly + lifecycle only: every surface lives in+ * its component (`CarRailView`, `CarMediaCardView`, `CarNavCardView`,+ * `CarCallCardView`, `CarDrawerView`), and every update fans out to the+ * owning component. Views, not Compose (private virtual display, no+ * lifecycle owner).+ */+internal class CarPresentation(+    private val context: Context,+    display: android.view.Display,+    initialNowPlaying: NowPlayingInfo?,+    initialDrivingRestricted: Boolean,+    initialNight: Boolean,+    initialActiveCall: ActiveCallInfo?,+    initialPhoneStatusSource: (() -> PhoneStatus?)?,+    onMediaTap: () -> Unit,+    onPreviousTap: () -> Unit,+    onNextTap: () -> Unit,+    onAnswerCallTap: () -> Unit,+    onEndCallTap: () -> Unit,+    onHoldToggleTap: () -> Unit,+    onMuteToggleTap: () -> Unit,+    private val onCardBounds: (Int, Int, Int, Int) -> Unit,+) : Presentation(context, display) {++    /**+     * Snapshot that arrived before `onCreate` built the card views.+     * Consumed once in `onCreate`; after that the card exists and updates+     * apply directly.+     */+    private var pendingNowPlaying: NowPlayingInfo? = initialNowPlaying++    /** Driving-restriction gate that arrived before `onCreate`. */+    private var pendingDrivingRestricted: Boolean = initialDrivingRestricted++    /** Night palette that arrived before `onCreate`. */+    private var pendingNight: Boolean = initialNight++    /** Active call that arrived before `onCreate` built the card. */+    private var pendingActiveCall: ActiveCallInfo? = initialActiveCall++    /**+     * Phone status feed captured from the outer display at construction:+     * [CarDisplay.phoneStatusSource] may be wired after `show()` starts+     * the presentation build, so the outer setter forwards late wiring+     * here. The ticker pulls through this, never the outer.+     */+    private var outerPhoneStatusSource: (() -> PhoneStatus?)? = initialPhoneStatusSource++    /**+     * Media/call callbacks captured from the outer display at+     * construction, with late-wiring setters below (the service may wire+     * them after `show()` starts the build).+     */+    private var outerOnMediaTap: () -> Unit = onMediaTap+    private var outerOnPreviousTap: () -> Unit = onPreviousTap+    private var outerOnNextTap: () -> Unit = onNextTap+    private var outerOnAnswerCall: () -> Unit = onAnswerCallTap+    private var outerOnEndCall: () -> Unit = onEndCallTap+    private var outerOnHoldToggle: () -> Unit = onHoldToggleTap+    private var outerOnMuteToggle: () -> Unit = onMuteToggleTap++    private var rootView: LinearLayout? = null+    private var rail: CarRailView? = null+    private var mediaCard: CarMediaCardView? = null+    private var navCard: CarNavCardView? = null+    private var callCard: CarCallCardView? = null+    private var drawer: CarDrawerView? = null+    private var assistantScrim: View? = null+    private val timeFormat: DateFormat = DateFormat.getTimeInstance(DateFormat.SHORT)+    private var drivingRestricted = false+    private var nightDark = false++    /**+     * Receives the nav-card map surface: (surface, w, h), or (null, 0, 0)+     * when the TextureView is destroyed. The session's mirror attaches on+     * non-null and releases on null; unset means no map backend.+     */+    var mapSurfaceListener: ((Surface?, Int, Int) -> Unit)? = null++    // Real wall-clock time, ticking every second. A driver needs to know+    // what time it is, and the moving digits still prove frames are+    // flowing rather than one stale image. The same tick refreshes the+    // phone status cluster (signal/battery/DND/badge) from the service+    // monitor and the call duration while active.+    private val ticker = object : Runnable {+        override fun run() {+            rail?.tickClock(outerPhoneStatusSource) ?: return+            callCard?.tickDuration()+            rail?.view?.postDelayed(this, 1000)+        }+    }++    /**+     * Continuous re-render at [fps] so the encoder surface produces frames+     * even when no view changes on its own. Main thread only. Backs off to+     * a Choreographer-frame chain when [fps] is at/above display cadence.+     */+    private var invalidator: Runnable? = null+    private var invalidatorFps = 0++    fun startFrameInvalidation(fps: Int) {+        stopFrameInvalidation()+        val decor = window?.decorView ?: return+        val intervalMs = (1000L / fps.coerceIn(1, MAX_INVALIDATE_FPS)).coerceAtLeast(0)+        invalidatorFps = fps+        val tick = object : Runnable {+            override fun run() {+                decor.invalidate()+                decor.postDelayed(this, intervalMs)+            }+        }+        invalidator = tick+        decor.post(tick)+    }++    fun stopFrameInvalidation() {+        val decor = window?.decorView+        invalidator?.let { decor?.removeCallbacks(it) }+        invalidator = null+        invalidatorFps = 0+    }++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        // Coolwalk facet structure, matching gearhead's+        // `gh_coolwalk_facet_bar` + dashboard cards + drawer:+        // content area (call card, split nav/media cards, scrims, drawer+        // pane, voice plate) above a bottom facet bar (dashboard button,+        // assistant slot, ongoing-widget slots, hotseat dock, status,+        // resize + native-rail stubs). Views, not Compose (see the class+        // KDoc).+        val root = LinearLayout(context).apply {+            orientation = LinearLayout.VERTICAL+            setBackgroundColor(Color.parseColor(COLOR_ROOT_DAY))+            layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)+        }+        rootView = root+        val apps = CarApps.query(context)+        val railView = CarRailView(+            context,+            apps,+            onOpenDrawer = { openDrawer() },+            onCloseDrawer = { closeDrawer() },+        )+        rail = railView+        val media = CarMediaCardView(+            context,+            onMediaTap = { outerOnMediaTap() },+            onPreviousTap = { outerOnPreviousTap() },+            onNextTap = { outerOnNextTap() },+            onCardBounds = onCardBounds,+        )+        mediaCard = media+        val nav = CarNavCardView(context, apps)+        navCard = nav+        nav.mapSurfaceListener = mapSurfaceListener+        val call = CarCallCardView(+            context,+            onAnswer = { outerOnAnswerCall() },+            onEnd = { outerOnEndCall() },+            onHold = { outerOnHoldToggle() },+            onMute = { outerOnMuteToggle() },+        )+        callCard = call+        val drawerView = CarDrawerView(context, apps)+        drawer = drawerView+        val content = DrawerContainer(context).apply {+            layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)+            onDrawerBack = { closeDrawer() }+            addView(+                LinearLayout(context).apply {+                    orientation = LinearLayout.VERTICAL+                    layoutParams = ViewGroup.LayoutParams(MATCH, MATCH)+                    setPadding(+                        context.carDp(16),+                        context.carDp(8),+                        context.carDp(16),+                        context.carDp(8),+                    )+                    addView(call.view)+                    addView(+                        LinearLayout(context).apply {+                            orientation = LinearLayout.HORIZONTAL+                            layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)+                            addView(+                                nav.view.apply {+                                    layoutParams = LinearLayout.LayoutParams(0, MATCH, 1f).apply {+                                        marginEnd = context.carDp(8)+                                    }+                                },+                            )+                            addView(+                                media.view.apply {+                                    layoutParams = LinearLayout.LayoutParams(0, MATCH, 1f).apply {+                                        marginStart = context.carDp(8)+                                    }+                                },+                            )+                        },+                    )+                },+            )+            addView(drawerView.scrim)+            addView(drawerView.pane)+            addView(drawerView.voicePlateView)+            addView(+                drawerView.assistantScrimView.also { assistantScrim = it },+            )+        }+        root.addView(content)+        root.addView(railView.view)+        // Template-decor structures (AppDecor header + app bar): exact+        // gearhead metrics, stubbed gone with no template host.+        root.addView(drawerView.decorHeader)+        root.addView(railView.appBarView())+        setContentView(root)++        pendingNowPlaying?.let { media.update(it) }+        pendingNowPlaying = null+        setDrivingRestricted(pendingDrivingRestricted)+        setNight(pendingNight)+        pendingActiveCall?.let { call.update(it) }+        pendingActiveCall = null++        railView.tickClock(outerPhoneStatusSource)+        window?.decorView?.viewTreeObserver?.addOnGlobalFocusChangeListener { _, newFocus ->+            // Focus-loss close: when the drawer is open and focus lands+            // outside the drawer subtree (and not on the hotseat drawer+            // cell that opened it), the drawer dismisses.+            val pane = drawerView.pane+            if (!drawerView.isOpen || newFocus == null) return@addOnGlobalFocusChangeListener+            var node: View? = newFocus+            while (node != null) {+                if (node === pane) return@addOnGlobalFocusChangeListener+                node = node.parent as? View+            }+            closeDrawer()+        }+    }++    /** Hides the now-playing card; the cached snapshot is untouched. Main thread only. */+    fun hideNowPlaying() {+        mediaCard?.hide()+    }++    /**+     * Applies a snapshot to the now-playing card. Main thread only: called+     * from the posted update in `CarDisplay.setNowPlaying`, or from+     * `onCreate` above for a snapshot that arrived before the views existed.+     */+    fun updateNowPlaying(info: NowPlayingInfo) {+        mediaCard?.update(info)+    }++    /**+     * Pushes one guidance snapshot to the nav card. Main thread only.+     * The card shows the banner only while guidance is active with a road+     * or maneuver to announce; otherwise GONE (idle map, no fake banner).+     */+    fun updateNavSnapshot(snapshot: NavSnapshot) {+        navCard?.update(snapshot)+    }++    /**+     * Pushes one active-call snapshot into the card. Main thread only;+     * null hides the card.+     */+    fun updateCallCard(info: ActiveCallInfo?) {+        callCard?.update(info)+    }++    /**+     * Opens the drawer: lazy scrim fade to the 0.8 dim. Main thread only.+     */+    fun openDrawer() {+        val scrim = drawer?.scrim+        if (scrim != null) {+            scrim.setBackgroundColor(Color.argb(0, 0x10, 0x14, 0x18))+            scrim.visibility = View.VISIBLE+            scrim.post { scrim.setBackgroundColor(Color.argb(204, 0x10, 0x14, 0x18)) }+        }+        drawer?.openDrawer()+    }++    /**+     * Closes the drawer and hides its scrim. Main thread only. Called+     * from the scrim tap, the BACK key (see [DrawerContainer]), launcher+     * taps, the Home facet button, focus loss, and trip-end park.+     */+    fun closeDrawer() {+        drawer?.closeDrawer()+        drawer?.scrim?.visibility = View.GONE+    }++    /**+     * Driving-restriction gate: hides the media action row and raises+     * the drawer lockout scrim while the drawer is open. Main thread only.+     */+    fun setDrivingRestricted(restricted: Boolean) {+        drivingRestricted = restricted+        mediaCard?.setButtonsVisible(!restricted)+        drawer?.drivingRestricted = restricted+        drawer?.applyLockout()+    }++    /**+     * Shows or hides the drawer loading spinner (48dp indeterminate).+     * Main thread only.+     */+    fun setDrawerLoading(loading: Boolean) {+        drawer?.setDrawerLoading(loading)+    }++    /**+     * Shows or hides the truncated-list card (88dp, bottom). Main thread only.+     */+    fun setDrawerTruncated(truncated: Boolean) {+        drawer?.setDrawerTruncated(truncated)+    }++    /**+     * Shows or hides the parked-browsing exit header (88dp). Main thread only.+     */+    fun setParkedBrowsing(active: Boolean) {+        drawer?.setParkedBrowsing(active)+    }++    /**+     * Shows the alpha-jump fast-scroll entry points. Main thread only.+     */+    fun setAlphaJumpVisible(visible: Boolean) {+        drawer?.setAlphaJumpVisible(visible)+    }++    /** Late-wired media tap; see the outer setter. Main thread only. */+    fun setOnMediaTap(tap: () -> Unit) {+        outerOnMediaTap = tap+    }++    /** Late-wired previous tap; see the outer setter. Main thread only. */+    fun setOnPreviousTap(tap: () -> Unit) {+        outerOnPreviousTap = tap+    }++    /** Late-wired next tap; see the outer setter. Main thread only. */+    fun setOnNextTap(tap: () -> Unit) {+        outerOnNextTap = tap+    }++    /** Late-wired answer action; see the outer setter. Main thread only. */+    fun setOnAnswerCall(tap: () -> Unit) {+        outerOnAnswerCall = tap+    }++    /** Late-wired end action; see the outer setter. Main thread only. */+    fun setOnEndCall(tap: () -> Unit) {+        outerOnEndCall = tap+    }++    /** Late-wired hold action; see the outer setter. Main thread only. */+    fun setOnHoldToggle(tap: () -> Unit) {+        outerOnHoldToggle = tap+    }++    /** Late-wired mute action; see the outer setter. Main thread only. */+    fun setOnMuteToggle(tap: () -> Unit) {+        outerOnMuteToggle = tap+    }++    /** Late-wired phone-status feed; see the outer setter. Main thread only. */+    fun setInnerPhoneStatusSource(source: () -> PhoneStatus?) {+        outerPhoneStatusSource = source+    }++    /**+     * Switches the day/night palette. Main thread only. Deltas follow+     * §2.3 exactly where gearhead tokens exist (see `CarDrawerView` /+     * `CarRailView` for the per-surface values). MA-only choices, reported+     * in PARITY.md: root/drawer day `#101418` (night takes the exact+     * `#ff172026` card token), rail day `#161C24` -> night `#101418`.+     */+    fun setNight(dark: Boolean) {+        nightDark = dark+        rootView?.setBackgroundColor(+            Color.parseColor(if (dark) COLOR_DRAWER_NIGHT else COLOR_ROOT_DAY),+        )+        rail?.setNight(dark)+        mediaCard?.setNight(dark)+        navCard?.setNight(dark)+        drawer?.setNight(dark)+    }++    override fun onStop() {+        rail?.view?.removeCallbacks(ticker)+        stopFrameInvalidation()+        rootView = null+        rail?.clear()+        rail = null+        mediaCard?.clear()+        mediaCard = null+        navCard?.clear()+        navCard = null+        callCard?.clear()+        callCard = null+        drawer?.clear()+        drawer = null+        assistantScrim = null+        super.onStop()+    }++    private fun dp(value: Int): Int = context.carDp(value)+}
auto/src/main/java/com/vayunmathur/auto/platform/CarRailView.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarRailView.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarRailView.ktnew file mode 100644index 0000000000..afcfd7c868--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarRailView.kt@@ -0,0 +1,601 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.graphics.Color+import android.view.Gravity+import android.view.View+import android.widget.FrameLayout+import android.widget.LinearLayout+import android.widget.Space+import android.widget.TextView+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.CarUiMetrics.COLUMNS+import com.vayunmathur.auto.platform.CarUiMetrics.MATCH+import com.vayunmathur.auto.platform.CarUiMetrics.MAX_DOCK_APPS+import com.vayunmathur.auto.platform.CarUiMetrics.WRAP+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_RAIL_DAY+import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_RAIL_NIGHT++/**+ * The bottom facet bar (`gh_coolwalk_facet_bar`) + rail status cluster+ * (`rail_statusbar`): dashboard button, assistant slot, ongoing-widget+ * slots, hotseat dock with guidelines, scrim slot, status cluster (icon row+ * over clock), edge spacer, resize + native-rail stubs, and the `app_bar`+ * equivalent.+ *+ * Touch targets match gearhead (`facet_bar_touch_target_size` 68dp,+ * `coolwalk_launcher_dashboard_margin` 10dp, `rail_coolwalk_rail_margin`+ * 6dp, 145dp hotseat guidelines, 2dp edge). Owns its views; the+ * presentation reads state through [tickClock]/[updatePhoneStatus] and+ * recolors through [setNight]. Views, not Compose (private display, no+ * lifecycle owner).+ */+internal class CarRailView(+    private val context: Context,+    private val apps: List<CarApp>,+    private val onOpenDrawer: () -> Unit,+    private val onCloseDrawer: () -> Unit,+) {+    private fun dp(value: Int): Int = context.carDp(value)++    private var railBar: LinearLayout? = null+    private var dockContainer: LinearLayout? = null+    private var clockView: TextView? = null+    private var signalOverlay: SignalBarsView? = null+    private var signalView: SignalBarsView? = null+    private var batteryView: BatteryLevelView? = null+    private var dndView: TextView? = null+    private var badgeView: TextView? = null+    private var statusCardView: LinearLayout? = null+    private var assistantSlot: FrameLayout? = null+    private var assistantIcon: TextView? = null+    private val timeFormat: java.text.DateFormat =+        java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT)++    /** The assembled rail; add once t

Diff truncated.