Modern Apps git

← Modern-Apps.git

cast: system-display resolution modes and MAOS launcher hiding

Commit
468d2204e79056c37141009dbe14c2d62a6639b3
Author
vayun-mathur <[email protected]>
When
2026-09-10 01:05 UTC (2 months ago)
Parents
6a99a8f

Diff

cast/src/main/AndroidManifest.xml
diff --git a/cast/src/main/AndroidManifest.xml b/cast/src/main/AndroidManifest.xmlindex 8451169a2d..11bab37614 100644--- a/cast/src/main/AndroidManifest.xml+++ b/cast/src/main/AndroidManifest.xml@@ -65,6 +65,7 @@         android:protectionLevel="signature" />      <application+        android:name=".CastApplication"         android:allowBackup="true"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"@@ -85,14 +86,24 @@             android:exported="true"             android:launchMode="singleTop"             android:theme="@style/Theme.General">-            <intent-filter>-                <action android:name="android.intent.action.MAIN" />-                <category android:name="android.intent.category.LAUNCHER" />-            </intent-filter>             <intent-filter>                 <action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />             </intent-filter>         </activity>+        <!-- Launcher entry as an alias so MAOS can hide it (there the app's own screen-sharing UI+             is redundant - the OS drives casting) without disabling MainActivity, which is still+             reached as the QS tile's preferences/settings activity. CastApplication disables this+             alias when the app is the privileged system remote-display provider (only on MAOS); on+             an ordinary install it stays enabled and the icon shows. -->+        <activity-alias+            android:name=".LauncherAlias"+            android:exported="true"+            android:targetActivity=".MainActivity">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity-alias>          <activity             android:name=".platform.mirror.MirrorConsentActivity"
cast/src/main/java/com/vayunmathur/cast/CastApplication.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/CastApplication.kt b/cast/src/main/java/com/vayunmathur/cast/CastApplication.ktnew file mode 100644index 0000000000..dbfbf81e4d--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/CastApplication.kt@@ -0,0 +1,51 @@+package com.vayunmathur.cast++import android.app.Application+import android.content.ComponentName+import android.content.pm.PackageManager+import android.util.Log++private const val TAG = "CastApplication"++/** The launcher entry, an `<activity-alias>` so it can be hidden without touching MainActivity. */+private const val LAUNCHER_ALIAS = "com.vayunmathur.cast.LauncherAlias"++/**+ * Hides the launcher icon when this app is the privileged system cast provider — i.e. only on+ * MAOS, where the OS itself drives casting (the system Cast page, desktop mode) and the app's own+ * screen-sharing UI is redundant. An ordinary install (e.g. from F-Droid) is never granted+ * `REMOTE_DISPLAY_PROVIDER`, so the icon stays and the app works exactly as before.+ *+ * This mirrors the Files app's approach: a component whose enabled state follows a MAOS-only+ * signal, flipped from a small [Application] at runtime rather than baked into the manifest, so the+ * APK is byte-for-byte identical everywhere it ships.+ */+class CastApplication : Application() {+    override fun onCreate() {+        super.onCreate()+        if (!isSystemCastProvider()) return+        val alias = ComponentName(this, LAUNCHER_ALIAS)+        // Idempotent: only the first launch on MAOS actually flips it; the setting then persists.+        if (packageManager.getComponentEnabledSetting(alias) ==+            PackageManager.COMPONENT_ENABLED_STATE_DISABLED+        ) {+            return+        }+        runCatching {+            packageManager.setComponentEnabledSetting(+                alias,+                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,+                PackageManager.DONT_KILL_APP,+            )+        }.onFailure { Log.w(TAG, "could not hide the launcher icon", it) }+    }++    /**+     * True when the OS granted this app `REMOTE_DISPLAY_PROVIDER` — the signal that it is the+     * preinstalled, privileged system cast provider (only ever the case on MAOS). It is+     * `signature|privileged`, so an ordinary install requests it but is denied.+     */+    private fun isSystemCastProvider(): Boolean =+        checkSelfPermission("android.permission.REMOTE_DISPLAY_PROVIDER") ==+            PackageManager.PERMISSION_GRANTED+}
cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktindex 42da902c2e..a168768d1b 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -482,7 +482,10 @@ object CastController {             // lays it out for whatever size the display was created at rather than reproducing the             // phone.             val geometry = if (source is MirrorSource.SystemDisplay) {-                MirrorGeometry.forDesktop(appContext, codec.selection, activeClient.displayModes)+                val desktopModes =+                    MirrorGeometry.desktopModes(appContext, codec.selection, activeClient.displayModes)+                source.supportedModes = desktopModes+                desktopModes.first()             } else {                 MirrorGeometry.forDisplay(appContext, codec.selection)             }
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.ktindex 70258bf8d7..09849e289f 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorEngine.kt@@ -270,7 +270,7 @@ class MirrorEngine(                 // mirror of the phone. The id is written back onto the source so the caller can                 // publish it to the route - the framework will not go looking for it.                 val desktop = CastSystemDisplay(appContext)-                if (!desktop.start(surface, geometry, source.receiverId)) {+                if (!desktop.start(surface, geometry, source.receiverId, source.supportedModes)) {                     encoder.release()                     desktop.release()                     return false
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.ktindex 0728d497e3..882c8592f7 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorGeometry.kt@@ -179,32 +179,55 @@ object MirrorGeometry {         context: Context,         chosen: CodecSelection.Chosen,         modes: List<DisplayMode>,-    ): CaptureGeometry {-        val largest = modes.maxByOrNull { it.area }-        if (largest == null) {-            Log.w(TAG, "the TV advertised no panel modes; composing the desktop for the phone")-            return forDisplay(context, chosen)-        }+    ): CaptureGeometry = desktopModes(context, chosen, modes).first() -        val (fittedWidth, fittedHeight) = chosen.receiverLimits.fit(largest.width, largest.height)+    /**+     * Every desktop resolution this phone can actually send, largest first.+     *+     * The first entry is what a desktop is composed at by default - the panel's biggest mode,+     * fitted to the TV's decoder and then clamped to what this phone's *encoder* will emit (a 4K+     * panel behind a 1080p-class encoder lands here). The rest are the smaller panel modes, each+     * likewise encodable, and they are what fills Android's external-display resolution picker+     * once they are declared on the virtual display via `VirtualDisplayConfig.setSupportedModes`.+     *+     * Falls back to the single [forDisplay] geometry when the receiver advertised no modes (a+     * pre-version-8 television) or when nothing it offered is encodable - the old,+     * wrong-but-working behaviour, and the one mode the picker then shows.+     */+    fun desktopModes(+        context: Context,+        chosen: CodecSelection.Chosen,+        modes: List<DisplayMode>,+    ): List<CaptureGeometry> {         val frameRate = frameRateFor(chosen.receiverLimits)-        val (width, height) =-            EncoderSupport.clampToEncoder(chosen.codec, fittedWidth, fittedHeight, frameRate)-        val bitRate = bitRateFor(width, height, frameRate, chosen)-        val density = desktopDensityFor(width, height)-+        val sizes = LinkedHashSet<Pair<Int, Int>>()+        for (mode in modes) {+            val (fittedWidth, fittedHeight) = chosen.receiverLimits.fit(mode.width, mode.height)+            val (width, height) =+                EncoderSupport.clampToEncoder(chosen.codec, fittedWidth, fittedHeight, frameRate)+            if (width > 0 && height > 0) sizes.add(width to height)+        }+        val geometries = sizes+            .map { (width, height) ->+                CaptureGeometry(+                    width = width,+                    height = height,+                    densityDpi = desktopDensityFor(width, height),+                    bitRate = bitRateFor(width, height, frameRate, chosen),+                )+            }+            // Largest first: the sender composes at the head and the picker lists from the top.+            .sortedByDescending { it.width.toLong() * it.height }+        if (geometries.isEmpty()) {+            Log.w(TAG, "the TV advertised no encodable panel modes; composing for the phone")+            return listOf(forDisplay(context, chosen))+        }         Log.i(             TAG,-            "desktop: panel is ${largest.width}x${largest.height}, sending ${width}x$height " +-                "@ ${frameRate}fps at ${bitRate / 1_000_000.0} Mbit/s, ${density}dpi" +-                chosen.rateReasoning(),-        )-        return CaptureGeometry(-            width = width,-            height = height,-            densityDpi = density,-            bitRate = bitRate,+            "desktop: offering ${geometries.joinToString { "${it.width}x${it.height}" }} " ++                "@ ${frameRate}fps${chosen.rateReasoning()}",         )+        return geometries     }      /**
cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.kt b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.ktindex ee9c634d5c..5ba8e89685 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/mirror/MirrorSource.kt@@ -62,6 +62,16 @@ sealed interface MirrorSource {          */         var receiverId: String? = null             internal set++        /**+         * The desktop resolutions to declare on the display, largest (the default) first.+         *+         * These become the display's `supportedModes`, which is what populates Android's+         * external-display resolution picker. Empty until [com.vayunmathur.cast.platform.CastController]+         * computes them from the TV's advertised modes and this phone's encoder limits.+         */+        var supportedModes: List<CaptureGeometry> = emptyList()+            internal set     }      /**
cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/CastSystemDisplay.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/CastSystemDisplay.kt b/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/CastSystemDisplay.ktindex 234fed3a8a..7131d14953 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/CastSystemDisplay.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/CastSystemDisplay.kt@@ -6,6 +6,7 @@ import android.hardware.display.DisplayManager import android.hardware.display.VirtualDisplay import android.hardware.display.VirtualDisplayConfig import android.util.Log+import android.view.Display import android.view.Surface import com.vayunmathur.cast.platform.mirror.CaptureGeometry @@ -68,6 +69,11 @@ private const val CAST_DISPLAY_FLAGS =  /** What the display is called, in Settings and in `dumpsys display`. */ private const val DISPLAY_NAME = "cast"+/**+ * Nominal refresh rate for a declared mode. `VirtualDisplayAdapter` rebuilds each declared mode at+ * the display's own refresh rate and reads only its width and height, so this value is not shown.+ */+private const val DESKTOP_MODE_REFRESH_RATE = 60f  /**  * Namespaces the unique id so it cannot collide with another adapter's.@@ -119,7 +125,12 @@ class CastSystemDisplay(context: Context) {      * verified against `DisplayManager.java` and restated on each constant above.      */     @SuppressLint("WrongConstant")-    fun start(surface: Surface, geometry: CaptureGeometry, receiverId: String?): Boolean {+    fun start(+        surface: Surface,+        geometry: CaptureGeometry,+        receiverId: String?,+        supportedModes: List<CaptureGeometry> = emptyList(),+    ): Boolean {         if (displays == null) {             Log.w(TAG, "no DisplayManager")             return false@@ -133,6 +144,7 @@ class CastSystemDisplay(context: Context) {             )                 .setFlags(CAST_DISPLAY_FLAGS)                 .setSurface(surface)+            builder.applySupportedModes(supportedModes)             receiverId?.let { builder.applyUniqueId("$UNIQUE_ID_PREFIX$it") }             display = displays.createVirtualDisplay(builder.build())             if (display == null) Log.w(TAG, "the platform returned no display")@@ -171,6 +183,49 @@ class CastSystemDisplay(context: Context) {         }     } +    /**+     * `VirtualDisplayConfig.Builder.setSupportedModes`, which is `@SystemApi` and+     * `@FlaggedApi(FLAG_VIRTUAL_DISPLAYS_SUPPORT_DESKTOP_MODE)` - not on the public SDK this module+     * compiles against - hence reflection. Each [CaptureGeometry] becomes a `Display.Mode`; the+     * framework re-creates each at the display's own refresh rate, reading only width and height,+     * so Settings' resolution picker ends up offering exactly these sizes.+     *+     * Best effort, and never fatal to the display: on a build without the framework change the+     * method is absent and the picker simply shows the single mode the display was created at,+     * which is the pre-desktop behaviour.+     */+    private fun VirtualDisplayConfig.Builder.applySupportedModes(modes: List<CaptureGeometry>) {+        if (modes.isEmpty()) return+        try {+            val displayModes = modes.mapNotNull { buildDisplayMode(it.width, it.height) }+            if (displayModes.isEmpty()) return+            VirtualDisplayConfig.Builder::class.java+                .getMethod("setSupportedModes", List::class.java)+                .invoke(this, displayModes)+        } catch (e: Throwable) {+            Log.w(TAG, "setSupportedModes unavailable; the resolution picker will show one mode", e)+        }+    }++    /**+     * A `Display.Mode` for [width] x [height]. Its constructor is not on the public SDK, so it is+     * reached reflectively; the refresh rate is nominal (see [DESKTOP_MODE_REFRESH_RATE]).+     */+    private fun buildDisplayMode(width: Int, height: Int): Display.Mode? =+        try {+            Display.Mode::class.java+                .getDeclaredConstructor(+                    Int::class.javaPrimitiveType,+                    Int::class.javaPrimitiveType,+                    Float::class.javaPrimitiveType,+                )+                .apply { isAccessible = true }+                .newInstance(width, height, DESKTOP_MODE_REFRESH_RATE)+        } catch (e: Throwable) {+            Log.w(TAG, "Display.Mode(int, int, float) unavailable; cannot declare ${width}x$height", e)+            null+        }+     fun release() {         runCatching { display?.release() }         display = null
cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.kt b/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.ktindex 33d3708e93..5fc0aa0dee 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/remotedisplay/MaRemoteDisplayProvider.kt@@ -81,11 +81,13 @@ class MaRemoteDisplayProvider(context: Context) : RemoteDisplayProvider(context)     private var pairTimeoutJob: Job? = null      init {+        Log.i(TAG, "MaRemoteDisplayProvider constructed")         scope.launch { CastController.mirrorPhase.collect { onMirrorPhase(it) } }         scope.launch { CastController.sessionState.collect { onSessionState(it) } }     }      override fun onDiscoveryModeChanged(mode: Int) {+        Log.i(TAG, "onDiscoveryModeChanged mode=$mode")         if (mode == RemoteDisplayProvider.DISCOVERY_MODE_NONE) {             discoveryJob?.cancel()             discoveryJob = null@@ -245,6 +247,7 @@ class MaRemoteDisplayProvider(context: Context) : RemoteDisplayProvider(context)     }      private fun syncRoutes(found: List<CastDevice>) {+        Log.i(TAG, "syncRoutes: ${found.size} device(s): ${found.map { it.friendlyName }}")         val seen = found.associateBy { it.id }         devices.clear()         devices.putAll(seen)
cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.kt b/cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.ktindex a8e9a07bc4..2039b21669 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/CastRemoteDisplayService.kt@@ -28,13 +28,18 @@ class CastRemoteDisplayService : Service() {     private var provider: MaRemoteDisplayProvider? = null      override fun onBind(intent: Intent?): IBinder? {-        if (intent?.action != RemoteDisplayProvider.SERVICE_INTERFACE) return null+        Log.i(TAG, "onBind called action=${intent?.action}")+        if (intent?.action != RemoteDisplayProvider.SERVICE_INTERFACE) {+            Log.w(TAG, "onBind: action mismatch (want ${RemoteDisplayProvider.SERVICE_INTERFACE}), returning null")+            return null+        }         val existing = provider ?: try {             MaRemoteDisplayProvider(this).also { provider = it }-        } catch (e: LinkageError) {-            Log.w(TAG, "com.android.media.remotedisplay is not on this device", e)+        } catch (e: Throwable) {+            Log.e(TAG, "onBind: failed to construct MaRemoteDisplayProvider", e)             return null         }+        Log.i(TAG, "onBind: returning provider binder=${existing.binder}")         return existing.binder     }