Modern Apps git

← Modern-Apps.git

appstore: TV entry, leanback catalog filter, TV browse UI

Commit
cd3519fb42e489927a941bf35dac350563bc273d
Author
vayun-mathur <[email protected]>
When
2026-10-20 07:30 UTC (1 month ago)
Parents
f923512

Diff

appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex db542290d5..4e8fd0e9e3 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -1,5 +1,9 @@ plugins {     id("common-conventions-app")+    // androidx.tv, so the TV entry is built on a design system that knows what a D-pad is+    // (the cast:tv precedent: name it alongside, not instead — the launcherIcon/nativeAbis+    // accessors below are generated from directly-applied plugins).+    id("common-conventions-tv")     // Listing screenshots come from Compose previews (src/screenshotTest), not from an     // instrumented test on a device. Same `:appstore:metadata` task name either way.     id("common-conventions-preview-metadata")@@ -14,6 +18,11 @@ launcherIcon {     symbol = "store" } +// Google TV hardware runs a 32-bit userspace: an arm64-only APK is rejected at install.+nativeAbis {+    armv7 = true+}+ android {     defaultConfig {         applicationId = "com.vayunmathur.appstore"@@ -43,8 +52,8 @@ androidComponents { }  // ed25519 verification of Accrescent's signify-signed repodata (Rust).-// See appstore/src/main/rust/.-rustNativeLib("appstore_signify", "appstore-signify")+// See appstore/src/main/rust/. extraAbis: the .so must also load on 32-bit Google TV.+rustNativeLib("appstore_signify", "appstore-signify", extraAbis = listOf("armeabi-v7a"))  dependencies {     implementRoom(libs)
appstore/src/main/AndroidManifest.xml
diff --git a/appstore/src/main/AndroidManifest.xml b/appstore/src/main/AndroidManifest.xmlindex 20f9acd2c7..4c53ed2d38 100644--- a/appstore/src/main/AndroidManifest.xml+++ b/appstore/src/main/AndroidManifest.xml@@ -13,8 +13,18 @@     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /> +    <!-- Leanback is supported, not required: one APK serves phones and TVs. Without these,+      a TV launcher never lists the app; with required="true" phones would lose it. -->+    <uses-feature+        android:name="android.software.leanback"+        android:required="false" />+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />+     <application         android:allowBackup="true"+        android:banner="@drawable/tv_banner"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"@@ -64,6 +74,25 @@             </intent-filter>         </activity> +        <!--+          TV entry: a separate activity carrying only LEANBACK_LAUNCHER, so the TV row+          opens the D-pad UI instead of the phone pager. Separate activity (not a second+          filter on MainActivity): split filters on one activity build separate resolve+          entries that confuse launcher resolution (the tvlauncher HOME lesson).+        -->+        <activity+            android:name=".tv.TvMainActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:launchMode="singleTask"+            android:screenOrientation="landscape"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LEANBACK_LAUNCHER" />+            </intent-filter>+        </activity>+         <service             android:name="androidx.work.impl.foreground.SystemForegroundService"             android:foregroundServiceType="dataSync"
appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.ktindex d08584b566..f01de06ed3 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -64,6 +64,12 @@ data class CachedAppEntity(     val antiFeatures: String? = null,     val whatsNew: String? = null,     val addedTimestamp: Long = 0L,+    /** Newline-joined TV screenshot URLs, in publication order. Null when none published. */+    val tvScreenshots: String? = null,+    /** Comma-joined `<uses-feature>` names from an authenticated index. Null when none published. */+    val requiredFeatures: String? = null,+    /** TV-compat verdict from the catalogue; null when the source said nothing either way. */+    val tvCompatible: Boolean? = null, )  /** URLs never contain a newline, so this survives values a comma would split apart. */@@ -108,6 +114,9 @@ fun UnifiedApp.toEntity(): CachedAppEntity = CachedAppEntity(     antiFeatures = antiFeatures.packList(),     whatsNew = whatsNew,     addedTimestamp = addedTimestamp,+    tvScreenshots = tvScreenshots.packList(),+    requiredFeatures = requiredFeatures.joinToString(",").ifBlank { null },+    tvCompatible = tvCompatible, )  fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(@@ -143,6 +152,9 @@ fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(     antiFeatures = antiFeatures.unpackList(),     whatsNew = whatsNew,     addedTimestamp = addedTimestamp,+    tvScreenshots = tvScreenshots.unpackList(),+    requiredFeatures = requiredFeatures?.split(",")?.filter { it.isNotBlank() } ?: emptyList(),+    tvCompatible = tvCompatible, )  /**@@ -324,7 +336,7 @@ interface CachedAppDao {         PinnedStampEntity::class,         AccrescentTrustEntity::class,     ],-    version = 7,+    version = 8,     exportSchema = false ) abstract class AppDatabase : RoomDatabase() {@@ -406,6 +418,17 @@ abstract class AppDatabase : RoomDatabase() {                             "minVersionCode INTEGER NOT NULL)"                     )                 }+            },+            object : Migration(7, 8) {+                override suspend fun migrate(connection: SQLiteConnection) {+                    // TV-compat catalogue signals: the per-version `<uses-feature>` list, the+                    // TV screenshot set, and the derived verdict. All nullable, so existing+                    // rows stay usable and fill in on the next sync; a null verdict means+                    // "unknown", which the filter treats as compatible.+                    connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN tvScreenshots TEXT")+                    connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN requiredFeatures TEXT")+                    connection.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN tvCompatible INTEGER")+                }             }         )     }
appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.ktindex ff40832cb8..79aa791683 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -87,6 +87,12 @@ data class UnifiedApp(     val isFree: Boolean = true,     /** Listing screenshots, in the order the source published them. */     val screenshots: List<String> = emptyList(),+    /**+     * TV screenshots, where the source publishes a separate set (F-Droid's `tv` set).+     * Shown on TV in place of [screenshots], which are phone-aspect and jump between+     * ratios when mixed. Empty when the source publishes no TV set.+     */+    val tvScreenshots: List<String> = emptyList(),     /** Wide header image, where the source publishes one. */     val featureGraphic: String? = null,     /** Average star rating, 0..5. Null when the source doesn't publish one. */@@ -111,6 +117,27 @@ data class UnifiedApp(     val expectedSigners: List<String> = emptyList(),     /** Lowercase-hex SHA-256 of the APK itself, when the source publishes one. */     val apkSha256: String? = null,+    /**+     * Hardware/software features the APK declares via `<uses-feature>` (F-Droid's+     * per-version `features` list; Play's `requiresFeature` where the proto exposes it).+     * Empty when the source publishes none. Used for TV-compat filtering — see+     * [com.vayunmathur.appstore.data.AppProvider.filterTvCompatible] — never as a+     * trust signal.+     */+    val requiredFeatures: List<String> = emptyList(),+    /**+     * Whether this listing is usable on Android TV, as far as the catalogue can tell.+     *+     * True when a TV signal is present (leanback `<uses-feature>`, a TV category, a+     * TV screenshot set); false when the listing positively declares itself+     * phone-only; null when the source says nothing either way (notably Accrescent,+     * whose server already decides per-device, and Play, whose phone-profile spoof+     * means the server never saw a TV). A null is *not* a verdict — it means unknown,+     * and the filter treats it as compatible rather than hiding an app for lack of+     * metadata. The install gate ([com.vayunmathur.appstore.data.security.InstallVerifier])+     * re-checks the actual APK regardless.+     */+    val tvCompatible: Boolean? = null, ) {     /** The single best image to head the detail page with. */     val heroImage: String? get() = featureGraphic ?: screenshots.firstOrNull()
appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.ktindex 4b16c29ba8..2f31ecffc5 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt@@ -24,4 +24,50 @@ object AppProvider {      fun filterTargetSdk(apps: List<UnifiedApp>): List<UnifiedApp> =         apps.filter { app -> app.targetSdk == null || app.targetSdk >= MIN_TARGET_SDK }++    /**+     * The `<uses-feature>` name F-Droid publishes for a leanback entry, and the value+     * Android's PackageManager reports for it on a TV.+     */+    const val FEATURE_LEANBACK = "android.software.leanback"++    /**+     * Features that positively mark an APK as needing phone hardware a TV has not got.+     * Matched as substrings against each declared feature name, lowercased: F-Droid+     * publishes names like `android.hardware.telephony`, and Play's proto (where it+     * exposes one) uses the same vocabulary.+     */+    private val PHONE_ONLY_FEATURES = listOf(+        "android.hardware.telephony",+        "android.hardware.camera.flash",+        "android.hardware.sensor.barometer",+    )++    /**+     * Keep only the listings usable on this form factor.+     *+     * A filter, never a trust decision: it hides listings the catalogue already marks+     * as incompatible, and the install gate re-checks the actual APK regardless (see+     * [com.vayunmathur.appstore.data.security.InstallVerifier.checkLeanback]).+     *+     * On a phone ([isTv] false) everything passes untouched. On a TV, a listing with+     * an explicit negative verdict ([UnifiedApp.tvCompatible] false) is hidden, as is+     * one whose declared features name phone-only hardware. Unknown (null) stays+     * visible: most sources publish no TV signal at all, and hiding every app for+     * lack of metadata would empty the store.+     */+    fun filterTvCompatible(isTv: Boolean, apps: List<UnifiedApp>): List<UnifiedApp> {+        if (!isTv) return apps+        return apps.filter { app ->+            if (app.tvCompatible == false) return@filter false+            !requiresPhoneHardware(app.requiredFeatures)+        }+    }++    /** True when any declared feature names hardware a TV does not have. */+    fun requiresPhoneHardware(requiredFeatures: List<String>): Boolean =+        requiredFeatures.any { feature ->+            val name = feature.lowercase()+            PHONE_ONLY_FEATURES.any { phoneOnly -> phoneOnly in name }+        } }
appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.ktindex 8646295b21..ba034d1563 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt@@ -55,6 +55,18 @@ class CatalogRepository(     private val modernProvider = FDroidAppProvider(db, appContext, DefaultRepos.MODERN_APPS)     private val proprietaryProvider = FDroidAppProvider(db, appContext, DefaultRepos.PROPRIETARY) +    /**+     * Whether this device is a TV. Read once: the leanback feature set cannot change+     * without a reboot, and every catalogue read below consults it for TV-compat+     * filtering.+     */+    private val isTv: Boolean by lazy {+        com.vayunmathur.appstore.data.accrescent.DeviceAttributesProvider(appContext).isTv()+    }++    private fun List<UnifiedApp>.filterTv(): List<UnifiedApp> =+        AppProvider.filterTvCompatible(isTv, this)+     val repos: StateFlow<List<RepoEntity>> =         db.repoDao().allFlow().stateIn(scope, SharingStarted.Eagerly, emptyList()) @@ -84,13 +96,13 @@ class CatalogRepository(         withContext(Dispatchers.IO) {             runCatching {                 db.cachedAppDao().recentlyUpdatedBySource(source.name, limit).map { it.toUnifiedApp() }-            }.getOrDefault(emptyList())+            }.getOrDefault(emptyList()).filterTv()         }      suspend fun byCategory(category: String, limit: Int = 60): List<UnifiedApp> =         withContext(Dispatchers.IO) {             runCatching { db.cachedAppDao().byCategory(category, limit).map { it.toUnifiedApp() } }-                .getOrDefault(emptyList())+                .getOrDefault(emptyList()).filterTv()         }      /** Categories present in the catalogue, most-populated first. */@@ -121,11 +133,14 @@ class CatalogRepository(                 queries.flatMap { db.cachedAppDao().searchAll(it, limit) }                     .distinctBy { it.packageName }                     .map { it.toUnifiedApp() }-            }.getOrDefault(emptyList())+            }.getOrDefault(emptyList()).filterTv()         }      suspend fun byPackage(packageName: String): UnifiedApp? = withContext(Dispatchers.IO) {         runCatching { db.cachedAppDao().byPackage(packageName)?.toUnifiedApp() }.getOrNull()+            // Single-item form of the TV gate every other read applies via filterTv():+            // an incompatible listing resolves to null, as if it were never cached.+            ?.let { app -> AppProvider.filterTvCompatible(isTv, listOf(app)).firstOrNull() }     }      suspend fun byPackages(packages: List<String>): List<UnifiedApp> = withContext(Dispatchers.IO) {@@ -134,7 +149,7 @@ class CatalogRepository(             packages.chunked(SQLITE_VARIABLE_LIMIT)                 .flatMap { db.cachedAppDao().byPackages(it) }                 .map { it.toUnifiedApp() }-        }.getOrDefault(emptyList())+        }.getOrDefault(emptyList()).filterTv()     }      /** Rows for packages that are installed but older than what the catalogue offers. */@@ -144,7 +159,7 @@ class CatalogRepository(             val known = index[inst.packageName] ?: return@filter false             known.versionCode > inst.versionCode         }.map { it.packageName }-        return byPackages(stale)+        return byPackages(stale).filterTv()     }      /**
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.ktindex 01e8ef557d..f35e146913 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidJson.kt@@ -125,29 +125,36 @@ private fun findNameInArray(reader: JsonReader): String? { /**  * index-v2 `screenshots`: `{ phone: { "en-US": [ { name, sha256, size }, … ] }, … }`.  *- * Only the phone set is taken — the tablet, TV and wear sets are the same app shot on- * hardware the reader isn't holding, and mixing them makes the carousel jump between- * aspect ratios. Falls back to whichever set exists if there is no phone one.+ * Both the phone set and the TV set are read. The phone set keeps its old behaviour —+ * the phone screenshots, falling back to whichever set exists when there is none — so+ * the carousel never jumps between aspect ratios. The TV set is returned alongside for+ * the TV UI; empty when the source publishes none.  */-internal fun readScreenshotsV2(reader: JsonReader, repoBase: String): List<String> {+internal data class ScreenshotSets(val phone: List<String>, val tv: List<String>)++internal fun readScreenshotsV2(reader: JsonReader, repoBase: String): List<String> =+    readScreenshotSetsV2(reader, repoBase).phone++internal fun readScreenshotSetsV2(reader: JsonReader, repoBase: String): ScreenshotSets {     if (reader.peek() != JsonToken.BEGIN_OBJECT) {         reader.skipValue()-        return emptyList()+        return ScreenshotSets(emptyList(), emptyList())     }     var phone: List<String> = emptyList()+    var tv: List<String> = emptyList()     var fallback: List<String> = emptyList()     reader.beginObject()     while (reader.hasNext()) {         val kind = reader.nextName()         val shots = readLocalizedFileList(reader, repoBase)-        if (kind == SCREENSHOT_PHONE) {-            phone = shots-        } else if (fallback.isEmpty()) {-            fallback = shots+        when (kind) {+            SCREENSHOT_PHONE -> phone = shots+            SCREENSHOT_TV -> tv = shots+            else -> if (fallback.isEmpty()) fallback = shots         }     }     reader.endObject()-    return phone.ifEmpty { fallback }+    return ScreenshotSets(phone = phone.ifEmpty { fallback }, tv = tv) }  /** `{ "en-US": [ { "name": "/pkg/en-US/phoneScreenshots/1.png" }, … ], … }`. */@@ -174,7 +181,7 @@ private fun readLocalizedFileList(reader: JsonReader, repoBase: String): List<St }  /** `[ { "name": …, "sha256": …, "size": … }, … ]` reduced to the names. */-private fun readFileNameArray(reader: JsonReader): List<String> {+internal fun readFileNameArray(reader: JsonReader): List<String> {     if (reader.peek() != JsonToken.BEGIN_ARRAY) {         reader.skipValue()         return emptyList()@@ -306,3 +313,38 @@ internal fun nextIntOrNull(reader: JsonReader): Int? { private const val LOCALE_US = "en-US" private const val LOCALE_EN = "en" private const val SCREENSHOT_PHONE = "phone"+private const val SCREENSHOT_TV = "tv"++/**+ * index-v2 per-version `features`: `[ { "name": "android.hardware.camera" }, … ]`.+ *+ * fdroidserver emits only the names that are present in the APK's `<uses-feature>`+ * tags; entries without a name carry nothing to filter on and are dropped. A missing+ * or malformed array means "the index says nothing", which is an empty list — the+ * verdict then stays unknown rather than incompatible.+ */+internal fun readFeatureNamesV2(reader: JsonReader): List<String> {+    if (reader.peek() != JsonToken.BEGIN_ARRAY) {+        reader.skipValue()+        return emptyList()+    }+    val names = mutableListOf<String>()+    reader.beginArray()+    while (reader.hasNext()) {+        if (reader.peek() != JsonToken.BEGIN_OBJECT) {+            reader.skipValue()+            continue+        }+        reader.beginObject()+        while (reader.hasNext()) {+            if (reader.nextName() == "name") {+                nextStringOrNull(reader)?.takeIf { it.isNotBlank() }?.let { names.add(it) }+            } else {+                reader.skipValue()+            }+        }+        reader.endObject()+    }+    reader.endArray()+    return names+}
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.ktindex 1453660859..fd5001392a 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt@@ -198,6 +198,7 @@ object FDroidRepository {         var iconUrl: String? = null         var featureGraphic: String? = null         var screenshots: List<String> = emptyList()+        var tvScreenshots: List<String> = emptyList()         var antiFeatures: List<String> = emptyList()         val versions = mutableListOf<VersionCandidate>()     }@@ -213,6 +214,7 @@ object FDroidRepository {         var targetSdk: Int? = null         var nativeCode: List<String> = emptyList()         var whatsNew: String? = null+        var requiredFeatures: List<String> = emptyList()          fun build(): VersionCandidate? {             val name = fileName ?: return null@@ -227,6 +229,7 @@ object FDroidRepository {                 targetSdk = targetSdk,                 nativeCode = nativeCode,                 whatsNew = whatsNew,+                requiredFeatures = requiredFeatures,             )         }     }@@ -257,6 +260,7 @@ object FDroidRepository {          // index-v2 file names are repo-absolute ("/com.example_12.apk").         val apkUrl = repoBase + "/" + latest.fileName.trimStart('/')+        val tvCompatible = deriveTvCompatible(b.categories, b.tvScreenshots, latest.requiredFeatures)         return UnifiedApp(             packageName = packageName,             source = source,@@ -269,6 +273,7 @@ object FDroidRepository {             iconUrl = b.iconUrl,             featureGraphic = b.featureGraphic,             screenshots = b.screenshots,+            tvScreenshots = b.tvScreenshots,             antiFeatures = b.antiFeatures,             author = b.author,             categories = b.categories,@@ -283,7 +288,9 @@ object FDroidRepository {             whatsNew = latest.whatsNew,             addedTimestamp = b.added,             lastUpdated = if (b.lastUpdated != 0L) b.lastUpdated else b.added,-            repoUrl = repoBase+            repoUrl = repoBase,+            requiredFeatures = latest.requiredFeatures,+            tvCompatible = tvCompatible,         )     } @@ -328,7 +335,11 @@ object FDroidRepository {         when (key) {             "icon" -> b.iconUrl = repoAssetUrl(reader, repoBase)             "featureGraphic" -> b.featureGraphic = repoAssetUrl(reader, repoBase)-            "screenshots" -> b.screenshots = readScreenshotsV2(reader, repoBase)+            "screenshots" -> {+                val sets = readScreenshotSetsV2(reader, repoBase)+                b.screenshots = sets.phone+                b.tvScreenshots = sets.tv+            }             // v2 states anti-features as a map of id -> localised reason;             // the ids are what the UI shows, so only the keys are kept.             "antiFeatures" -> b.antiFeatures = readObjectKeys(reader)@@ -398,6 +409,10 @@ object FDroidRepository {                 // The ABIs this APK carries native libraries for.                 // Absent means it has none and runs anywhere.                 "nativecode" -> v.nativeCode = readStringArray(reader)+                // `<uses-feature>` entries, as `[{ "name": "android.hardware.camera" }, …]`.+                // Kept verbatim for TV-compat filtering — a leanback entry marks a TV build,+                // phone-hardware entries mark one a TV should not be offered.+                "features" -> v.requiredFeatures = readFeatureNamesV2(reader)                 // signer.sha256 is the list of signing-certificate                 // fingerprints this APK is expected to carry.                 "signer" -> v.signers = readSignerShaV2(reader)@@ -456,8 +471,29 @@ object FDroidRepository {         val targetSdk: Int? = null,         val nativeCode: List<String> = emptyList(),         val whatsNew: String? = null,+        val requiredFeatures: List<String> = emptyList(),     ) +    /**+     * Whether the catalogue can call this listing TV-compatible, from the signals+     * F-Droid publishes: leanback `<uses-feature>`, a TV category, or a TV screenshot+     * set. Null when nothing says either way — unknown, not incompatible.+     */+    internal fun deriveTvCompatible(+        categories: List<String>,+        tvScreenshots: List<String>,+        requiredFeatures: List<String>,+    ): Boolean? {+        val names = requiredFeatures.map { it.lowercase() }+        if (names.any { AppProvider.FEATURE_LEANBACK in it }) return true+        if (categories.any { it.equals(TV_CATEGORY, ignoreCase = true) }) return true+        if (tvScreenshots.isNotEmpty()) return true+        if (AppProvider.requiresPhoneHardware(requiredFeatures)) return false+        return null+    }++    private const val TV_CATEGORY = "TV"+     private val deviceAbis: List<String> by lazy { Build.SUPPORTED_ABIS?.toList().orEmpty() }      /**
appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.ktindex 372dc690b5..950370d080 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/InstalledAppsRepository.kt@@ -26,7 +26,9 @@ class InstalledAppsRepository(private val context: Context) {     private val _updatable = MutableStateFlow<List<InstalledInfo>>(emptyList())      /**-     * [apps] minus the packages this device won't let the store install ([RestrictedPackages]).+     * [apps] minus the packages this device won't let the store install+     * ([RestrictedPackages]) or has already refused as incompatible+     * ([TvIncompatiblePackages]).      *      * They stay in [apps] — they are installed, and the library should say so — but every      * update check reads this instead, so the store never offers an update it cannot apply.@@ -50,7 +52,8 @@ class InstalledAppsRepository(private val context: Context) {             .sortedBy { it.name.lowercase() }         _apps.value = apps -        val restricted = RestrictedPackages.forDevice(context)+        val restricted = RestrictedPackages.forDevice(context) ++            TvIncompatiblePackages.forDevice(context)         _updatable.value = apps.filterNot { it.packageName in restricted }          _icons.value = userApps.mapNotNull { ai ->
appstore/src/main/java/com/vayunmathur/appstore/data/TvIncompatiblePackages.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/TvIncompatiblePackages.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/TvIncompatiblePackages.ktnew file mode 100644index 0000000000..ca6984d235--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/TvIncompatiblePackages.kt@@ -0,0 +1,96 @@+package com.vayunmathur.appstore.data++import android.content.Context+import androidx.core.content.edit++/**+ * Packages the OS refused as incompatible with this device, so the store stops+ * offering them updates.+ *+ * The shape mirrors [RestrictedPackages] deliberately: the OS's+ * `STATUS_FAILURE_INCOMPATIBLE` is a final answer for this device, not a failure the+ * user can act on — and without learning it, the 12-hour update check would re-offer+ * the same update forever, each time with a terminal failure message. One failed+ * install teaches the store; the next check skips the package.+ *+ * Unlike [RestrictedPackages.KNOWN], there is no pre-seeded set: incompatibility is+ * only ever learned the hard way, per device. Entries are device-specific facts, so+ * they are never synced or shared — a package incompatible with this TV may install+ * fine on the user's phone.+ *+ * Two guards keep the learning from going stale (both missing in the first version,+ * which suppressed forever):+ * - TV-only: recording is gated on [isTvLearned]. A phone `FAILURE_INCOMPATIBLE`+ *   (e.g. an ABI mismatch) is not a TV verdict and must not suppress updates.+ * - Expiry + clear-on-update: entries are stored as `package:timestamp` and expire+ *   after 7 days, so a newly shipped TV build is re-offered; a successful install+ *   clears the package immediately via [clearOnUpdate].+ * - Legacy bare-package entries (pre-timestamp) are treated as expired and dropped+ *   on read, retiring the permanent suppressions the old format created.+ */+object TvIncompatiblePackages {++    private const val PREFS = "appstore-tv-incompatible-packages"+    private const val KEY_LEARNED = "incompatible_packages"++    /** 7 days in milliseconds: learned incompatibility expires after this. */+    private const val EXPIRY_MS = 7L * 24 * 60 * 60 * 1000++    /** Packages to leave out of update checks on this device. */+    fun forDevice(context: Context): Set<String> = unexpiredPackages(context)++    /**+     * Remember [packageName] when the OS refused it as incompatible.+     *+     * Records only when [isTv] is true: only a TV learns TV-incompatibility. A+     * phone ABI-mismatch refusal must not suppress future updates. Pass the flag+     * from the receiver, which knows the device.+     *+     * The status code is the signal — unlike the restriction case there is no message+     * text worth matching, since every incompatibility refusal carries the same finality.+     */+    fun recordIfIncompatible(context: Context, packageName: String?, isTv: Boolean) {+        if (!isTv) return+        if (packageName.isNullOrEmpty()) return+        val now = System.currentTimeMillis()+        prefs(context).edit {+            putStringSet(KEY_LEARNED, pruneExpired(learned(context), now) + "$packageName:$now")+        }+    }++    /** Forget [packageName] after it installs successfully — the lesson is stale. */+    fun clearOnUpdate(context: Context, packageName: String?) {+        if (packageName.isNullOrEmpty()) return+        prefs(context).edit {+            putStringSet(+                KEY_LEARNED,+                learned(context).filterNot { it == packageName || it.startsWith("$packageName:") }+                    .toSet(),+            )+        }+    }++    private fun unexpiredPackages(context: Context): Set<String> {+        val now = System.currentTimeMillis()+        val entries = learned(context)+        val live = pruneExpired(entries, now)+        if (live.size != entries.size) {+            prefs(context).edit { putStringSet(KEY_LEARNED, live) }+        }+        return live.mapNotNull { it.substringBefore(":").takeIf { pkg -> pkg.isNotEmpty() } }.toSet()+    }++    private fun pruneExpired(entries: Set<String>, now: Long): Set<String> =+        entries.filter { entry ->+            val timestamp = entry.substringAfterLast(":", "").toLongOrNull()+                // Legacy bare-package entries (no timestamp) are treated as expired.+                ?: return@filter false+            now - timestamp < EXPIRY_MS+        }.toSet()++    private fun learned(context: Context): Set<String> =+        prefs(context).getStringSet(KEY_LEARNED, emptySet()).orEmpty()++    private fun prefs(context: Context) =+        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+}
appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.ktindex 26843120ea..5946719720 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -120,9 +120,21 @@ class UpdateCheckWorker(          // The surviving row's source decides which download-and-verify path the update takes,         // so it has to be the same precedence the rest of the store uses.-        return (fromCatalog + fromPlay + fromAccrescent)-            .sortedBy { it.source.priority }-            .distinctBy { it.packageName }+        //+        // The TV-compat filter is the single choke for every update stream: the offline+        // catalogue and Play already filter at read time, but defence in depth keeps one+        // place where a missed hook cannot re-offer an incompatible update every 12h.+        // Accrescent needs no per-app filtering — its server already decides per-device —+        // and passes through untouched.+        val isTv = com.vayunmathur.appstore.data.accrescent.DeviceAttributesProvider(+            context.applicationContext+        ).isTv()+        return com.vayunmathur.appstore.data.AppProvider.filterTvCompatible(+            isTv,+            (fromCatalog + fromPlay + fromAccrescent)+                .sortedBy { it.source.priority }+                .distinctBy { it.packageName },+        )     }      private suspend fun playUpdates(
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.ktindex 20804eb8e2..ed20309c35 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.kt@@ -2,6 +2,7 @@ package com.vayunmathur.appstore.data.accrescent  import android.app.ActivityManager import android.content.Context+import android.content.pm.PackageManager import android.os.Build import android.util.DisplayMetrics import android.view.WindowManager@@ -23,6 +24,20 @@ class DeviceAttributesProvider(private val context: Context) {     fun deviceAttributes(): DeviceAttributes =         DeviceAttributes.newBuilder().setSpec(deviceSpec()).build() +    /**+     * True on Android TV / Google TV: the leanback system feature is present and no+     * touchscreen is. Reused by the Play and F-Droid paths for TV-compat filtering —+     * the catalog servers each have their own notion of compatibility, but "am I a TV"+     * is one client-side fact.+     */+    fun isTv(): Boolean = try {+        val pm = context.packageManager+        pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) &&+            !pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)+    } catch (_: Exception) {+        false+    }+     fun deviceSpec(): DeviceSpec {         val builder = DeviceSpec.newBuilder()             .addAllSupportedAbis(Build.SUPPORTED_ABIS?.toList().orEmpty())
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.ktindex 56aa241b6e..de888c72e7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -66,6 +66,36 @@ class InstallCoordinator(     private val sessionInstaller = SessionInstaller(context)     private val playDownloader = PlayDownloader(context) +    /**+     * Whether this device is a TV. Read once: the leanback feature set cannot change+     * without a reboot, and every install consults it for the TV-compat gate.+     */+    private val isTv: Boolean by lazy {+        com.vayunmathur.appstore.data.accrescent.DeviceAttributesProvider(+            context.applicationContext+        ).isTv()+    }++    /**+     * The reason [app] must not install on this TV, or null when it may proceed.+     *+     * Null on phones unconditionally, and null for Accrescent everywhere: its server+     * already decides per-device, so a client-side refusal would second-guess the+     * authority. Everything else defers to the same verdict the catalogue filter uses.+     */+    private fun tvRefusal(app: UnifiedApp): String? {+        if (!isTv) return null+        if (app.source == com.vayunmathur.appstore.data.AppSource.ACCRESCENT) return null+        if (app.tvCompatible == false) {+            return "this app is not marked TV-compatible, so it is hidden on TV"+        }+        if (com.vayunmathur.appstore.data.AppProvider.requiresPhoneHardware(app.requiredFeatures)) {+            return "this app needs phone hardware (${app.requiredFeatures.firstOrNull().orEmpty()}) " ++                "this TV does not have"+        }+        return null+    }+     private val _stages = MutableStateFlow<Map<String, InstallStage>>(emptyMap())     val stages: StateFlow<Map<String, InstallStage>> = _stages.asStateFlow() @@ -101,6 +131,16 @@ class InstallCoordinator(         if (isBusy(app.packageName)) {             return SessionInstaller.Outcome(false, VerificationResult.Rejected("already installing"))         }+        // Pre-download TV-compat refusal, mirroring the catalogue filter: on a TV, a+        // listing the catalogue already marked incompatible (or naming phone-only+        // hardware) is refused before any bytes download. This is a fast path only —+        // the downloaded APK is still re-checked by InstallVerifier.checkLeanback, so a+        // lying listing cannot bypass the gate by carrying no metadata.+        tvRefusal(app)?.let { reason ->+            val outcome = SessionInstaller.Outcome(false, VerificationResult.Rejected(reason))+            record(app.packageName, outcome.verification)+            return finishInstall(app.packageName, outcome)+        }         stage(app.packageName, InstallStage.Preparing)         return try {             val outcome = when (app.source) {@@ -174,6 +214,7 @@ class InstallCoordinator(                     expectedSha256 = app.apkSha256                         ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),                     signerOrigin = "this store",+                    requireTvCompatible = isTv,                 )                 // This store's own Play mirror: the same release key signs the index, but                 // the APKs carry the developers' keys, so the per-version signers from@@ -184,6 +225,7 @@ class InstallCoordinator(                     expectedSha256 = app.apkSha256                         ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),                     signerOrigin = "this store's Play mirror",+                    requireTvCompatible = isTv,                 )                 else -> InstallRequirement(                     expectedPackage = app.packageName,@@ -191,6 +233,7 @@ class InstallCoordinator(                     expectedSha256 = app.apkSha256                         ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),                     signerOrigin = "F-Droid's signed app list",+                    requireTvCompatible = isTv,                 )             } @@ -310,6 +353,11 @@ class InstallCoordinator(                 expectedSha256 = emptyMap(),                 minVersionCode = trust.minVersionCode,                 signerOrigin = "Accrescent's signed app list",+                // Server is the authority for Accrescent: it already picks splits+                // per-device, so a client-side leanback refusal would second-guess+                // it (mirrors the tvRefusal() exemption). Every other source keeps+                // requireTvCompatible = isTv.+                requireTvCompatible = false,             )              stage(app.packageName, InstallStage.Verifying)@@ -324,7 +372,19 @@ class InstallCoordinator(         withContext(Dispatchers.IO) {             // The listing that got the user here may be a cluster entry with no version             // code, and purchase() needs one that matches what Play will serve.-            val details = play.details(app.packageName) ?: app+            // details() already applies the TV filter, so a null on a TV for a+            // TV-incompatible listing is a refusal, not a missing read: propagate it+            // instead of falling back to the unfiltered cluster entry. A null for any+            // other reason (no auth, network) keeps the old fallback. Phones are+            // untouched — tvRefusal() is null there unconditionally.+            val details = play.details(app.packageName) ?: run {+                tvRefusal(app)?.let { reason ->+                    return@withContext SessionInstaller.Outcome(+                        false, VerificationResult.Rejected(reason)+                    )+                }+                app+            }             val versionCode = details.versionCode.takeIf { it > 0 } ?: app.versionCode             val offerType = details.offerType @@ -369,6 +429,7 @@ class InstallCoordinator(                 expectedSha256 = expectedHashes,                 signerOrigin = "Google",                 pinnedStamp = db.pinnedStampDao().byPackage(app.packageName)?.stampSha256,+                requireTvCompatible = isTv,             )              sessionInstaller.installSplits(
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.ktindex cb9200d8b3..313184858b 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallStatusReceiver.kt@@ -7,6 +7,8 @@ import android.content.pm.PackageInstaller import com.vayunmathur.library.log.Log import com.vayunmathur.appstore.R import com.vayunmathur.appstore.data.RestrictedPackages+import com.vayunmathur.appstore.data.TvIncompatiblePackages+import com.vayunmathur.appstore.data.accrescent.DeviceAttributesProvider import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow@@ -37,7 +39,7 @@ class InstallStatusReceiver : BroadcastReceiver() {          when (status) {             PackageInstaller.STATUS_PENDING_USER_ACTION -> forwardUserAction(context, intent)-            PackageInstaller.STATUS_SUCCESS -> reportSuccess(pkg)+            PackageInstaller.STATUS_SUCCESS -> reportSuccess(context, pkg)             // The user backing out of the system prompt is not a failure worth reporting back.             PackageInstaller.STATUS_FAILURE_ABORTED -> reportAborted(pkg)             else -> reportFailure(context, status, message, pkg)@@ -64,9 +66,12 @@ class InstallStatusReceiver : BroadcastReceiver() {         }     } -    private fun reportSuccess(pkg: String?) {+    private fun reportSuccess(context: Context, pkg: String?) {         Log.status(TAG, "Install success for $pkg")         pkg?.let { InstallEvents.publish(InstallResult(it, success = true)) }+        // The lesson is stale: a build that installs proves compatibility, so stop+        // suppressing its updates.+        TvIncompatiblePackages.clearOnUpdate(context, pkg)     }      private fun reportAborted(pkg: String?) {@@ -79,6 +84,16 @@ class InstallStatusReceiver : BroadcastReceiver() {         pkg?.let { InstallEvents.publish(InstallResult(it, success = false)) }         // A source-restricted refusal is the OS's final answer, so stop offering it.         RestrictedPackages.recordIfRestricted(context, pkg, message)+        // An incompatibility refusal is equally final on this device: without learning+        // it, the update check would re-offer the same update every 12 hours with a+        // terminal toast each time. Recorded like a restriction, consulted the same way.+        // TV-only: a phone ABI-mismatch refusal is not a TV verdict and must not+        // suppress updates, so the receiver passes the device form factor along.+        if (status == PackageInstaller.STATUS_FAILURE_INCOMPATIBLE) {+            TvIncompatiblePackages.recordIfIncompatible(+                context, pkg, DeviceAttributesProvider(context).isTv()+            )+        }         val reason = failureReason(context, status, message)         val text = context.getString(R.string.install_failed_reason, pkg.orEmpty(), reason)         if (!InstallFailureBatch.collect(text)) {
appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.ktindex dd453b6bf1..7752581e9c 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayRepository.kt@@ -10,7 +10,9 @@ import com.aurora.gplayapi.data.models.AuthData import com.aurora.gplayapi.data.models.PlayFile import com.aurora.gplayapi.exceptions.GooglePlayException import com.aurora.gplayapi.helpers.AuthHelper+import com.vayunmathur.appstore.data.AppProvider import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.accrescent.DeviceAttributesProvider import com.vayunmathur.appstore.data.searchCandidate import com.vayunmathur.appstore.domain.SearchRanking import kotlinx.coroutines.CancellationException@@ -60,6 +62,18 @@ class PlayRepository(private val context: Context) {     private val httpClient = PlayHttpClient()     private val json = Json { ignoreUnknownKeys = true; isLenient = true } +    /**+     * Whether this device is a TV. Read once: the leanback feature set cannot change+     * without a reboot, and every Play call below consults it for TV-compat filtering.+     */+    private val isTv: Boolean by lazy { DeviceAttributesProvider(context).isTv() }++    private fun List<UnifiedApp>.filterTv(): List<UnifiedApp> =+        AppProvider.filterTvCompatible(isTv, this)++    private fun UnifiedApp.filterTv(): UnifiedApp? =+        AppProvider.filterTvCompatible(isTv, listOf(this)).firstOrNull()+     private val _authState = MutableStateFlow<PlayAuthState>(PlayAuthState.Idle)     val authState: StateFlow<PlayAuthState> = _authState.asStateFlow() @@ -202,22 +216,26 @@ class PlayRepository(private val context: Context) {         }         val direct = withApi { it.search(query, SEARCH_MAX_PAGES, answered) }.orEmpty()         val tokens = SearchRanking.tokenize(query)-        if (tokens.size < 2 || answered(direct)) return direct+        if (tokens.size < 2 || answered(direct)) return direct.filterTv()         val broader = withApi { it.search(tokens.first(), SEARCH_MAX_PAGES, answered) }.orEmpty()-        return (direct + broader).distinctBy { it.packageName }+        return (direct + broader).distinctBy { it.packageName }.filterTv()     }      suspend fun details(packageName: String): UnifiedApp? =-        withApi { it.getDetails(packageName) }+        withApi { it.getDetails(packageName) }?.filterTv()      suspend fun details(packageNames: List<String>): List<UnifiedApp> =-        withFreshApi { it.getDetails(packageNames) }.orEmpty()+        withFreshApi { it.getDetails(packageNames) }.orEmpty().filterTv()      suspend fun topChart(): List<UnifiedApp> =-        withFreshApi { it.topChart() }.orEmpty()+        withFreshApi { it.topChart() }.orEmpty().filterTv()      suspend fun homeClusters(): List<PlayCluster> =         withFreshApi { it.homeClusters() }.orEmpty()+            .mapNotNull { cluster ->+                val apps = AppProvider.filterTvCompatible(isTv, cluster.apps)+                if (apps.isEmpty()) null else cluster.copy(apps = apps)+            }      /** Throws, unlike the readers above: an install has no silent fallback. */     suspend fun purchase(
appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.ktindex 076507ede2..2ea4b38049 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt@@ -40,6 +40,17 @@ data class InstallRequirement(      * unaffected — the gate is additive and defaults to a no-op.      */     val minVersionCode: Long? = null,+    /**+     * True when the install is happening on a TV. Refuses APKs that cannot run there:+     * ones declaring phone-only hardware features, and ones with no leanback entry+     * (no `android.software.leanback` feature and no leanback-launched activity).+     * False (the default) skips the check entirely, so every phone install is+     * unaffected — the gate is additive and defaults to a no-op.+     *+     * This is a second opinion on the downloaded bytes, not a replacement for the+     * catalogue filter: a listing that lies about compatibility is still refused here.+     */+    val requireTvCompatible: Boolean = false, )  sealed class VerificationResult {@@ -124,6 +135,7 @@ object InstallVerifier {         val checks: List<() -> VerificationResult.Rejected?> = listOf(             { checkPackageName(ctx) },             { checkTargetSdk(ctx) },+            { checkLeanback(ctx) },             { signerCheck.rejection },             { checkRollbackFloor(ctx) },             { checkInstalledContinuity(ctx, signerCheck.signers) },@@ -183,6 +195,114 @@ object InstallVerifier {         return null     } +    /**+     * TV-compat gate: refuse APKs that cannot run on a TV, from the manifest we hold.+     *+     * Mirrors [checkTargetSdk]: the catalogue filters on what each source *claims*,+     * which a source may not state at all, so re-check the downloaded bytes. A lying+     * listing is refused here rather than installed.+     *+     * Two refusals, in order:+     * - phone-only hardware: a `<uses-feature>` naming telephony or other hardware a+     *   TV has not got means the OS would refuse the install anyway — fail here with+     *   a stated reason instead of a cryptic `INSTALL_FAILED_MISSING_FEATURE`;+     * - no leanback entry: without the leanback feature *or* a leanback-launched+     *   activity, the app has no TV entry point and would install invisibly — never+     *   listed in the TV launcher, never launchable by the user.+     *+     * Skipped entirely unless [InstallRequirement.requireTvCompatible]: every phone+     * install passes untouched. An APK whose manifest cannot be read for these fields+     * stays allowed — absence of evidence is not evidence of incompatibility, and the+     * OS remains the final arbiter at commit time.+     */+    private fun checkLeanback(ctx: CheckContext): VerificationResult.Rejected? {+        if (!ctx.requirement.requireTvCompatible) return null+        val baseInfo = ctx.parsed.firstOrNull { (_, info) ->+            info?.packageName == ctx.requirement.expectedPackage && info.splitNames.isNullOrEmpty()+        }?.second ?: return null++        val declaredFeatures = baseInfo.reqFeatures?.mapNotNull { it.name }.orEmpty()+        if (AppProvider.requiresPhoneHardware(declaredFeatures)) {+            return VerificationResult.Rejected(+                "it needs phone hardware (${declaredFeatures.firstOrNull().orEmpty()}) " ++                    "this TV does not have"+            )+        }++        val declaresLeanback = declaredFeatures.any {+            it.equals(AppProvider.FEATURE_LEANBACK, ignoreCase = true)+        }+        if (!declaresLeanback && !hasLeanbackActivity(ctx, declaredFeatures)) {+            return VerificationResult.Rejected(+                "it has no TV entry point, so it would install with no way to open it"+            )+        }+        ctx.checks += "TV-compatible"+        return null+    }++    /**+     * Whether the downloaded base APK names a leanback-launched activity.+     *+     * Heuristic limits — read before tightening this:+     * - `GET_ACTIVITIES` does not return intent-filters, so the true+     *   `LEANBACK_LAUNCHER` category cannot be observed here; an activity *name*+     *   containing "leanback" or ".tv." is only a naming convention, not proof of+     *   a TV entry point. A correctly-declared TV activity with an unrelated name+     *   is missed (false negative), and a phone activity that merely mentions "tv"+     *   passes (false positive).+     * - To narrow the false negatives without breaking the fail-open contract, an+     *   APK that declares ANY `<uses-feature>` this TV also reports is treated as+     *   TV-targeted: a phone-only manifest names hardware the TV has not got+     *   (already refused above), so a surviving feature intersect means the author+     *   aimed at hardware present here.+     * - Fail-open throughout: null base file, unreadable archive, or an unreadable+     *   device-feature list stays allowed — absence of evidence is not evidence of+     *   incompatibility, and the OS remains the final arbiter at commit time.+     */+    private fun hasLeanbackActivity(+        ctx: CheckContext,+        declaredFeatures: List<String>,+    ): Boolean {+        if (declaredFeatures.isNotEmpty() && declaresDeviceFeature(ctx, declaredFeatures)) {+            return true+        }+        val baseFile = ctx.parsed.firstOrNull { (_, info) ->+            info?.packageName == ctx.requirement.expectedPackage && info.splitNames.isNullOrEmpty()+        }?.first ?: return true+        val withActivities = try {+            @Suppress("DEPRECATION")+            ctx.context.packageManager.getPackageArchiveInfo(+                baseFile.absolutePath,+                android.content.pm.PackageManager.GET_ACTIVITIES,+            )+        } catch (_: Exception) {+            null+        } ?: return true+        return withActivities.activities.orEmpty().any { activity ->+            val name = activity.name.orEmpty()+            name.contains("leanback", ignoreCase = true) || name.contains(".tv.", ignoreCase = true)+        }+    }++    /**+     * True when any of the APK's declared `<uses-feature>` names is also reported+     * by this device — a TV-targeted signal that complements the activity-name+     * heuristic above. Fail-open: an unreadable device-feature list returns false+     * rather than refusing, leaving the name heuristic (and the OS) to decide.+     */+    private fun declaresDeviceFeature(ctx: CheckContext, declaredFeatures: List<String>): Boolean {+        val deviceFeatures = try {+            ctx.context.packageManager.systemAvailableFeatures.mapNotNullTo(mutableSetOf()) {+                it.name?.lowercase()+            }+        } catch (_: Exception) {+            return false+        }+        if (deviceFeatures.isEmpty()) return false+        return declaredFeatures.any { it.lowercase() in deviceFeatures }+    }+     // Signers of the bytes we actually hold. Every readable file must agree, or the     // set is mixed and something has been substituted.     private fun checkSignerAgreement(ctx: CheckContext): SignerCheck {
appstore/src/main/java/com/vayunmathur/appstore/tv/TvBrowse.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvBrowse.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvBrowse.ktnew file mode 100644index 0000000000..c8d5a138a9--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvBrowse.kt@@ -0,0 +1,226 @@+package com.vayunmathur.appstore.tv++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.Card+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.installer.InstallStage+import com.vayunmathur.library.image.compose.AsyncImage++/**+ * The TV browse: one row per source, TV-compatible listings only.+ *+ * The rows come from the same repositories the phone UI reads, which already filter+ * to TV-compatible apps — nothing here filters again. Each tile is a tv-material+ * [Card] so the D-pad focus ring is handled by the design system, not by hand.+ */+@Composable+fun TvStoreHome(+    viewModel: TvStoreViewModel,+    onAppClick: (UnifiedApp) -> Unit,+    modifier: Modifier = Modifier,+) {+    val state by viewModel.home.collectAsState()+    TvBrowseScreen(state = state, onAppClick = onAppClick, modifier = modifier)+}++/**+ * Stateless browse grid, so it can be rendered in a preview.+ *+ * // RAW SCAFFOLD EXCEPTION: androidx.tv has no AppScaffold equivalent, and the TV+ * ten-foot rule (see cast/tv ReceiverContent) is that a title bar above a browse+ * grid is furniture — the rows are the screen.+ */+@Composable+internal fun TvBrowseScreen(+    state: TvHomeUiState,+    onAppClick: (UnifiedApp) -> Unit = {},+    modifier: Modifier = Modifier,+) {+    Column(+        modifier = modifier+            .fillMaxSize()+            .background(MaterialTheme.colorScheme.background)+            .padding(horizontal = 48.dp, vertical = 32.dp),+        verticalArrangement = Arrangement.spacedBy(24.dp),+    ) {+        Text(+            text = stringResource(R.string.tv_browse_title),+            style = MaterialTheme.typography.headlineLarge,+            color = MaterialTheme.colorScheme.onSurface,+        )+        if (state.isLoading && state.sections.isEmpty()) {+            Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+                Text(+                    text = stringResource(R.string.sync_in_progress),+                    style = MaterialTheme.typography.titleMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+            return@Column+        }+        if (state.sections.isEmpty()) {+            Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+                Text(+                    text = stringResource(R.string.home_empty_message),+                    style = MaterialTheme.typography.titleMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    textAlign = TextAlign.Center,+                )+            }+            return@Column+        }+        LazyColumn(+            modifier = Modifier.fillMaxSize(),+            verticalArrangement = Arrangement.spacedBy(24.dp),+            contentPadding = PaddingValues(bottom = 24.dp),+        ) {+            items(state.sections, key = { it.id }) { section ->+                TvSectionRow(+                    section = section,+                    installedPackages = state.installedPackages,+                    stages = state.stages,+                    onAppClick = onAppClick,+                )+            }+        }+    }+}++@Composable+private fun TvSectionRow(+    section: TvSection,+    installedPackages: Set<String>,+    stages: Map<String, InstallStage>,+    onAppClick: (UnifiedApp) -> Unit,+) {+    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+        Text(+            text = section.title,+            style = MaterialTheme.typography.titleLarge,+            color = MaterialTheme.colorScheme.onSurface,+        )+        LazyRow(+            modifier = Modifier.fillMaxWidth(),+            horizontalArrangement = Arrangement.spacedBy(16.dp),+            contentPadding = PaddingValues(horizontal = 4.dp),+        ) {+            items(section.apps, key = { it.packageName }) { app ->+                TvAppTile(+                    app = app,+                    isInstalled = app.packageName in installedPackages,+                    stage = stages[app.packageName],+                    onClick = { onAppClick(app) },+                )+            }+        }+    }+}++@Composable+private fun TvAppTile(+    app: UnifiedApp,+    isInstalled: Boolean,+    stage: InstallStage?,+    onClick: () -> Unit,+) {+    Card(onClick = onClick, modifier = Modifier.width(160.dp)) {+        Column(+            modifier = Modifier.padding(12.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(8.dp),+        ) {+            TvAppIcon(app = app)+            Text(+                text = app.name,+                style = MaterialTheme.typography.titleSmall,+                color = MaterialTheme.colorScheme.onSurface,+                textAlign = TextAlign.Center,+                maxLines = 2,+                overflow = TextOverflow.Ellipsis,+                modifier = Modifier.height(40.dp),+            )+            val status = when {+                stage != null -> stage.tvLabel()+                isInstalled -> stringResource(R.string.installed)+                else -> null+            }+            if (status != null) {+                Text(+                    text = status,+                    style = MaterialTheme.typography.labelSmall,+                    color = if (stage is InstallStage.Failed) {+                        MaterialTheme.colorScheme.error+                    } else {+                        MaterialTheme.colorScheme.onSurfaceVariant+                    },+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                )+            }+        }+    }+}++@Composable+private fun TvAppIcon(app: UnifiedApp) {+    val box = Modifier+        .size(72.dp)+        .clip(RoundedCornerShape(16.dp))+    if (app.iconUrl != null) {+        AsyncImage(+            model = app.iconUrl,+            contentDescription = null,+            modifier = box,+            contentScale = ContentScale.Crop,+        )+    } else {+        Box(+            box.background(MaterialTheme.colorScheme.surfaceVariant),+            contentAlignment = Alignment.Center,+        ) {+            Text(+                text = app.name.take(1).uppercase(),+                style = MaterialTheme.typography.headlineSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+    }+}++@Composable+private fun InstallStage.tvLabel(): String = when (this) {+    InstallStage.Preparing -> stringResource(R.string.stage_preparing)+    is InstallStage.Downloading -> stringResource(R.string.stage_downloading, (fraction * 100).toInt())+    InstallStage.Verifying -> stringResource(R.string.stage_verifying)+    InstallStage.Installing -> stringResource(R.string.stage_installing)+    is InstallStage.Failed -> stringResource(R.string.stage_failed, reason)+}
appstore/src/main/java/com/vayunmathur/appstore/tv/TvDetail.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvDetail.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvDetail.ktnew file mode 100644index 0000000000..26d3c9fbd3--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvDetail.kt@@ -0,0 +1,228 @@+package com.vayunmathur.appstore.tv++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.installer.InstallStage+import com.vayunmathur.appstore.data.security.VerificationResult+import com.vayunmathur.library.ui.IconTv++/**+ * One app's TV page: what it is, whether it runs on TV, and the install button.+ *+ * The install and update buttons call the same [TvStoreViewModel.install] the browse+ * rows use — which runs the ordinary [InstallCoordinator] pipeline verbatim, including+ * the TV-compat gate. There is no TV-specific install path.+ *+ * TV compatibility is stated explicitly rather than implied by presence: an app that+ * reached this screen passed the catalogue filter, and the line says why (a leanback+ * entry the source published) or that the source said nothing either way.+ */+@Composable+fun TvAppDetail(+    viewModel: TvStoreViewModel,+    onBack: () -> Unit,+    modifier: Modifier = Modifier,+) {+    val state by viewModel.detail.collectAsState()+    TvDetailScreen(+        state = state,+        onInstall = { app -> viewModel.install(app) },+        onOpen = { pkg -> viewModel.openApp(pkg) },+        onBack = onBack,+        modifier = modifier,+    )+}++/**+ * Stateless detail, so it can be rendered in a preview.+ *+ * // RAW SCAFFOLD EXCEPTION: androidx.tv has no AppScaffold equivalent; the detail is+ * a single scrollable column with a back button, not a scaffolded phone screen.+ */+@Composable+internal fun TvDetailScreen(+    state: TvDetailUiState,+    onInstall: (UnifiedApp) -> Unit = {},+    onOpen: (String) -> Unit = {},+    onBack: () -> Unit = {},+    modifier: Modifier = Modifier,+) {+    val app = state.app ?: return+    val stage = state.stage+    val busy = stage != null && stage !is InstallStage.Failed+    Column(+        modifier = modifier+            .fillMaxSize()+            .background(MaterialTheme.colorScheme.background)+            .verticalScroll(rememberScrollState())+            .padding(horizontal = 48.dp, vertical = 32.dp),+        verticalArrangement = Arrangement.spacedBy(16.dp),+    ) {+        Button(onClick = onBack) {+            Text(stringResource(R.string.tv_detail_back))+        }+        Text(+            text = app.name,+            style = MaterialTheme.typography.displaySmall,+            color = MaterialTheme.colorScheme.onSurface,+        )+        if (app.summary.isNotBlank()) {+            Text(+                text = app.summary,+                style = MaterialTheme.typography.titleMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        TvCompatLine(app = app)+        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+            when {+                busy -> Button(onClick = {}, enabled = false, modifier = Modifier.weight(1f)) {+                    Text(stage.tvStageLabel())+                }+                state.hasUpdate -> {+                    Button(onClick = { onInstall(app) }, modifier = Modifier.weight(1f)) {+                        Text(stringResource(R.string.action_update))+                    }+                    Button(onClick = { onOpen(app.packageName) }) {+                        Text(stringResource(com.vayunmathur.library.ui.R.string.open))+                    }+                }+                state.isInstalled -> {+                    Button(+                        onClick = { onOpen(app.packageName) },+                        modifier = Modifier.weight(1f),+                    ) {+                        Text(stringResource(com.vayunmathur.library.ui.R.string.open))+                    }+                }+                else -> Button(onClick = { onInstall(app) }, modifier = Modifier.weight(1f)) {+                    Text(stringResource(R.string.action_install))+                }+            }+        }+        if (stage is InstallStage.Failed) {+            Text(+                text = stringResource(R.string.stage_failed, stage.reason),+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.error,+            )+        }+        state.verification.toMessage()?.let { message ->+            Text(+                text = message,+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        if (app.description.isNotBlank()) {+            Text(+                text = stringResource(R.string.tv_detail_about),+                style = MaterialTheme.typography.titleLarge,+                color = MaterialTheme.colorScheme.onSurface,+                fontWeight = FontWeight.SemiBold,+            )+            Text(+                text = app.description,+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        TvDetailFacts(app = app)+    }+}++/**+ * The TV-compat statement: why this app is offered on TV.+ *+ * Three cases, all factual: the source published a leanback signal; the source+ * published phone-only hardware but the APK still installed (cannot happen through+ * the filter — this line then explains the discrepancy); or the source said nothing+ * and the install gate verified the bytes instead.+ */+@Composable+private fun TvCompatLine(app: UnifiedApp) {+    Row(verticalAlignment = Alignment.CenterVertically) {+        IconTv(tint = MaterialTheme.colorScheme.primary)+        Spacer(Modifier.width(8.dp))+        Text(+            text = stringResource(+                if (app.tvCompatible == true) R.string.tv_compat_declared+                else R.string.tv_compat_unverified+            ),+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+    }+}++@Composable+private fun TvDetailFacts(app: UnifiedApp) {+    Column(+        modifier = Modifier.fillMaxWidth(),+        verticalArrangement = Arrangement.spacedBy(6.dp),+    ) {+        app.versionName?.let { TvFact(stringResource(R.string.fact_version), it) }+        app.author?.let { TvFact(stringResource(R.string.tv_detail_author), it) }+        app.license?.let { TvFact(stringResource(R.string.detail_license), it) }+        TvFact(stringResource(R.string.detail_package), app.packageName)+    }+}++@Composable+private fun TvFact(label: String, value: String) {+    Column(Modifier.fillMaxWidth()) {+        Text(+            text = label,+            style = MaterialTheme.typography.labelSmall,+            color = MaterialTheme.colorScheme.onSurfaceVariant,+        )+        Text(+            text = value,+            style = MaterialTheme.typography.bodyMedium,+            color = MaterialTheme.colorScheme.onSurface,+        )+    }+}++@Composable+private fun VerificationResult?.toMessage(): String? = when (this) {+    is VerificationResult.Rejected ->+        stringResource(R.string.detail_install_blocked, reason)+    is VerificationResult.Verified ->+        stringResource(R.string.detail_checked_on_install, detail)+    is VerificationResult.Unverified ->+        stringResource(R.string.detail_installed_unverified, reason)+    null -> null+}++@Composable+private fun InstallStage.tvStageLabel(): String = when (this) {+    InstallStage.Preparing -> stringResource(R.string.stage_preparing)+    is InstallStage.Downloading -> stringResource(R.string.stage_downloading, (fraction * 100).toInt())+    InstallStage.Verifying -> stringResource(R.string.stage_verifying)+    InstallStage.Installing -> stringResource(R.string.stage_installing)+    is InstallStage.Failed -> stringResource(R.string.stage_failed, reason)+}
appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.ktnew file mode 100644index 0000000000..13a66e1ab2--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvMainActivity.kt@@ -0,0 +1,62 @@+package com.vayunmathur.appstore.tv++import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.darkColorScheme+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.appstore.data.AppStoreDatabaseRepository+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.library.ui.MaActivity++/**+ * The TV entry: opened from TV launcher rows (LEANBACK_LAUNCHER). The phone MainActivity+ * stays exactly as it is — this activity hosts the D-pad store UI.+ *+ * Browse and detail are two states, not a nav graph: one selected app or none. The+ * ViewModel is the phone repositories reused verbatim, so installs go through the+ * ordinary pipeline including the TV-compat gate.+ */+class TvMainActivity : MaActivity() {+    override val edgeToEdge: Boolean = false++    @Composable+    override fun AppTheme(content: @Composable () -> Unit) {+        // Always dark, not dynamic: a TV has no wallpaper to derive a scheme from.+        // Paints nothing itself; screens set their own background.+        MaterialTheme(colorScheme = darkColorScheme(), content = content)+    }++    @Composable+    override fun Content() {+        val repository = remember { AppStoreDatabaseRepository.get(this) }+        val factory = remember { TvStoreViewModelFactory(this, repository.database) }+        val viewModel: TvStoreViewModel = viewModel(factory = factory)+        TvRoot(viewModel = viewModel)+    }+}++@Composable+private fun TvRoot(viewModel: TvStoreViewModel) {+    var selected by remember { mutableStateOf<UnifiedApp?>(null) }+    if (selected == null) {+        TvStoreHome(+            viewModel = viewModel,+            onAppClick = { app ->+                viewModel.selectApp(app)+                selected = app+            },+        )+    } else {+        TvAppDetail(+            viewModel = viewModel,+            onBack = {+                viewModel.clearSelection()+                selected = null+            },+        )+    }+}
appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.ktnew file mode 100644index 0000000000..4ca8c0d59b--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt@@ -0,0 +1,228 @@+package com.vayunmathur.appstore.tv++import android.app.Application+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import com.vayunmathur.appstore.data.AppDatabase+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.CatalogRepository+import com.vayunmathur.appstore.data.InstalledAppsRepository+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.accrescent.AccrescentRepository+import com.vayunmathur.appstore.data.installer.InstallCoordinator+import com.vayunmathur.appstore.data.installer.InstallStage+import com.vayunmathur.appstore.data.play.PlayRepository+import com.vayunmathur.appstore.data.priority+import com.vayunmathur.appstore.data.security.ApkCertificates+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++/**+ * Everything the TV browse and detail screens draw.+ *+ * The repositories are the phone's own — [CatalogRepository], [PlayRepository],+ * [InstalledAppsRepository], [InstallCoordinator] — reused verbatim, so the TV UI+ * can never drift into its own install path. What is TV-specific is only the state+ * derivation: the catalogue reads already filter to TV-compatible listings (see+ * `filterTvCompatible`), and this ViewModel holds the selected app plus the install+ * stages the detail screen reports.+ */+class TvStoreViewModel(+    internal val context: Application,+    db: AppDatabase,+) : ViewModel() {++    internal val catalog = CatalogRepository(context, db, viewModelScope)+    internal val play = PlayRepository(context)+    internal val accrescent = AccrescentRepository(context, db)+    internal val installedRepo = InstalledAppsRepository(context)+    internal val installer = InstallCoordinator(context, db, play, accrescent, viewModelScope) {+        ApkCertificates.selfSigners(context)+    }++    val enabledSourcesFlow = MutableStateFlow(AppSource.TOGGLEABLE.toSet())+    internal val sectionsFlow = MutableStateFlow<List<TvSection>>(emptyList())+    internal val isLoadingFlow = MutableStateFlow(true)+    internal val statusMessageFlow = MutableStateFlow("")+    internal val selectedAppFlow = MutableStateFlow<UnifiedApp?>(null)++    val home: StateFlow<TvHomeUiState> = combine(+        sectionsFlow,+        isLoadingFlow,+        statusMessageFlow,+        installedRepo.apps,+        installer.stages,+    ) { sections, loading, message, installed, stages ->+        TvHomeUiState(+            sections = sections,+            isLoading = loading,+            statusMessage = message,+            installedPackages = installed.map { it.packageName }.toSet(),+            stages = stages,+        )+    }.stateIn(viewModelScope, SharingStarted.Eagerly, TvHomeUiState())++    val detail: StateFlow<TvDetailUiState> = combine(+        selectedAppFlow,+        installedRepo.apps,+        installer.stages,+        installer.verification,+    ) { app, installed, stages, verification ->+        val pkg = app?.packageName+        TvDetailUiState(+            app = app,+            installedInfo = installed.find { it.packageName == pkg },+            stage = stages[pkg],+            verification = verification[pkg],+        )+    }.stateIn(viewModelScope, SharingStarted.Eagerly, TvDetailUiState())++    init {+        viewModelScope.launch {+            installedRepo.refresh()+            if (AppSource.PLAYSTORE in enabledSourcesFlow.value) play.restore()+            loadHome()+        }+        viewModelScope.launch {+            combine(catalog.packageIndex, installedRepo.updatable) { _, _ -> Unit }+                .collect { loadHome() }+        }+    }++    /** Fill the browse rows from the TV-filtered catalogue. */+    fun loadHome() {+        viewModelScope.launch {+            isLoadingFlow.value = true+            val enabled = enabledSourcesFlow.value+            val sections = buildList {+                if (AppSource.MODERN_APPS in enabled) {+                    catalog.recentlyUpdatedBySource(AppSource.MODERN_APPS, ROW_LIMIT)+                        .takeIf { it.isNotEmpty() }?.let {+                            add(TvSection("modern", "From Modern Apps", it))+                        }+                }+                if (AppSource.PLAYSTORE in enabled) {+                    play.homeClusters()+                        .filter { it.apps.isNotEmpty() }+                        .take(CLUSTER_LIMIT)+                        .forEach { cluster ->+                            add(TvSection("play-${cluster.title}", cluster.title, cluster.apps))+                        }+                }+                if (AppSource.FDROID in enabled) {+                    catalog.recentlyUpdatedBySource(AppSource.FDROID, ROW_LIMIT)+                        .takeIf { it.isNotEmpty() }?.let {+                            add(TvSection("fdroid", "New on F-Droid", it))+                        }+                }+            }+            // Same precedence the phone uses: the surviving row's source decides the+            // download-and-verify path, so cross-source duplicates resolve identically.+            sectionsFlow.value = sections.map { section ->+                section.copy(+                    apps = section.apps.sortedBy { it.source.priority }+                        .distinctBy { it.packageName }+                )+            }+            isLoadingFlow.value = false+        }+    }++    fun selectApp(app: UnifiedApp) {+        selectedAppFlow.value = app+    }++    fun clearSelection() {+        selectedAppFlow.value = null+    }++    fun install(app: UnifiedApp) {+        viewModelScope.launch {+            val outcome = installer.install(app)+            val verdict = outcome.verification+            AppMessages.show(+                when (verdict) {+                    is com.vayunmathur.appstore.data.security.VerificationResult.Rejected ->+                        context.getString(+                            com.vayunmathur.appstore.R.string.install_blocked,+                            app.name,+                            verdict.reason,+                        )+                    else ->+                        if (outcome.started) context.getString(+                            com.vayunmathur.appstore.R.string.install_started,+                            app.name,+                        )+                        else context.getString(+                            com.vayunmathur.appstore.R.string.install_failed,+                            app.name,+                        )+                },+            )+            if (outcome.started) installedRepo.refresh()+        }+    }++    fun openApp(packageName: String) {+        val launchIntent = runCatching {+            context.packageManager.getLaunchIntentForPackage(packageName)+        }.getOrNull() ?: return+        runCatching {+            context.startActivity(launchIntent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))+        }+    }++    override fun onCleared() {+        accrescent.shutdown()+        super.onCleared()+    }++    private companion object {+        const val ROW_LIMIT = 20+        const val CLUSTER_LIMIT = 4+    }+}++/** One titled row on the TV browse screen. */+data class TvSection(+    val id: String,+    val title: String,+    val apps: List<UnifiedApp>,+)++/** Everything the TV browse screen draws. */+data class TvHomeUiState(+    val sections: List<TvSection> = emptyList(),+    val isLoading: Boolean = false,+    val statusMessage: String = "",+    val installedPackages: Set<String> = emptySet(),+    val stages: Map<String, InstallStage> = emptyMap(),+)++/** Everything the TV detail screen draws. */+data class TvDetailUiState(+    val app: UnifiedApp? = null,+    val installedInfo: com.vayunmathur.appstore.data.InstalledInfo? = null,+    val stage: InstallStage? = null,+    val verification: com.vayunmathur.appstore.data.security.VerificationResult? = null,+) {+    val isInstalled: Boolean get() = installedInfo != null++    val hasUpdate: Boolean+        get() = installedInfo != null && (app?.versionCode ?: 0L) > installedInfo.versionCode+}++class TvStoreViewModelFactory(+    private val context: android.content.Context,+    private val db: AppDatabase,+) : ViewModelProvider.Factory {+    @Suppress("UNCHECKED_CAST")+    override fun <T : ViewModel> create(modelClass: Class<T>): T =+        TvStoreViewModel(context.applicationContext as Application, db) as T+}
appstore/src/main/res/drawable/tv_banner.xml
diff --git a/appstore/src/main/res/drawable/tv_banner.xml b/appstore/src/main/res/drawable/tv_banner.xmlnew file mode 100644index 0000000000..350f1fb31b--- /dev/null+++ b/appstore/src/main/res/drawable/tv_banner.xml@@ -0,0 +1,22 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Leanback-row banner (320x180): a dark tile with a white storefront glyph. The launcher+  icon (launcherIcon symbol="store") stays the phone adaptive icon; this is what TV rows show. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="320dp"+    android:height="180dp"+    android:viewportWidth="320"+    android:viewportHeight="180">+    <path+        android:fillColor="#FF1B1B1F"+        android:pathData="M0,0h320v180H0z" />+    <!-- Storefront: awning + body, centered. -->+    <path+        android:fillColor="#FFFFFFFF"+        android:pathData="M120,78 L200,78 L192,96 L128,96 Z" />+    <path+        android:fillColor="#FFFFFFFF"+        android:pathData="M128,100h64v36h-64z" />+    <path+        android:fillColor="#FF1B1B1F"+        android:pathData="M150,100h20v36h-20z" />+</vector>
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex 74381224d4..5e67974a5f 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -251,4 +251,12 @@     <string name="source_play_pin">Nothing to pin: Google holds the signing key</string>     <string name="source_accrescent_pin">Pinned to Accrescent\'s repodata signing key (ed25519)</string>     <string name="source_proprietary_pin">Pinned to this store\'s Play mirror signing key</string>++    <!-- TV browse and detail. -->+    <string name="tv_browse_title">App Store</string>+    <string name="tv_detail_back">Back</string>+    <string name="tv_detail_about">About</string>+    <string name="tv_detail_author">Developer</string>+    <string name="tv_compat_declared">Works on TV — the source lists a TV version</string>+    <string name="tv_compat_unverified">TV compatibility unverified — checked at install</string> </resources>
appstore/src/test/java/com/vayunmathur/appstore/data/TvCompatibleFilterTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/data/TvCompatibleFilterTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/data/TvCompatibleFilterTest.ktnew file mode 100644index 0000000000..d5d6d472eb--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/data/TvCompatibleFilterTest.kt@@ -0,0 +1,127 @@+package com.vayunmathur.appstore.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * TV-compat filtering: a filter through the catalogue, never a trust decision.+ *+ * On phones everything passes untouched. On TVs, explicit incompatibility and+ * phone-only hardware are hidden, while unknown (null — most sources publish no TV+ * signal) stays visible rather than emptying the store for lack of metadata.+ */+class TvCompatibleFilterTest {++    private fun app(+        tvCompatible: Boolean? = null,+        requiredFeatures: List<String> = emptyList(),+    ) = UnifiedApp(+        packageName = "com.example.app",+        source = AppSource.FDROID,+        name = "Example",+        tvCompatible = tvCompatible,+        requiredFeatures = requiredFeatures,+    )++    @Test+    fun `phone passes everything`() {+        val apps = listOf(+            app(tvCompatible = true),+            app(tvCompatible = false),+            app(tvCompatible = null),+            app(requiredFeatures = listOf("android.hardware.telephony")),+        )++        assertEquals(apps, AppProvider.filterTvCompatible(false, apps))+    }++    @Test+    fun `tv hides explicit incompatibility`() {+        val apps = listOf(app(tvCompatible = false), app(tvCompatible = true))++        assertEquals(listOf(app(tvCompatible = true)), AppProvider.filterTvCompatible(true, apps))+    }++    @Test+    fun `tv hides phone-only hardware`() {+        val apps = listOf(+            app(requiredFeatures = listOf("android.hardware.telephony")),+            app(requiredFeatures = listOf("android.software.leanback")),+        )++        val filtered = AppProvider.filterTvCompatible(true, apps)+        assertEquals(1, filtered.size)+        assertEquals(listOf("android.software.leanback"), filtered.single().requiredFeatures)+    }++    @Test+    fun `tv keeps unknown`() {+        val apps = listOf(app(tvCompatible = null))++        assertEquals(apps, AppProvider.filterTvCompatible(true, apps))+    }++    @Test+    fun `requiresPhoneHardware matches telephony`() {+        assertTrue(AppProvider.requiresPhoneHardware(listOf("android.hardware.telephony")))+        assertTrue(AppProvider.requiresPhoneHardware(listOf("android.hardware.camera.flash")))+        assertFalse(AppProvider.requiresPhoneHardware(listOf("android.software.leanback")))+        assertFalse(AppProvider.requiresPhoneHardware(emptyList()))+    }++    @Test+    fun `deriveTvCompatible marks leanback`() {+        assertEquals(+            true,+            FDroidRepository.deriveTvCompatible(+                emptyList(),+                emptyList(),+                listOf("android.software.leanback"),+            ),+        )+    }++    @Test+    fun `deriveTvCompatible marks tv category and screenshots`() {+        assertEquals(true, FDroidRepository.deriveTvCompatible(listOf("TV"), emptyList(), emptyList()))+        assertEquals(+            true,+            FDroidRepository.deriveTvCompatible(listOf("tv"), emptyList(), emptyList()),+        )+        assertEquals(+            true,+            FDroidRepository.deriveTvCompatible(+                emptyList(),+                listOf("https://f-droid.org/tv/1.png"),+                emptyList(),+            ),+        )+    }++    @Test+    fun `deriveTvCompatible marks phone hardware incompatible`() {+        assertEquals(+            false,+            FDroidRepository.deriveTvCompatible(+                emptyList(),+                emptyList(),+                listOf("android.hardware.telephony"),+            ),+        )+    }++    @Test+    fun `deriveTvCompatible stays unknown without signals`() {+        assertNull(FDroidRepository.deriveTvCompatible(emptyList(), emptyList(), emptyList()))+        assertNull(+            FDroidRepository.deriveTvCompatible(+                listOf("Multimedia"),+                emptyList(),+                listOf("android.hardware.camera.any"),+            )+        )+    }+}