tvlauncher: calm Compose TV home screen with banner grid
- Commit
52b9c39f03ca764740caaecae492dba3438e1203- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-19 22:08 UTC (1 month ago)
- Parents
89d01cf
Diff
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 7344ad5f57..6e54f345ec 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -223,10 +223,13 @@ import androidx.compose.material.icons.filled.Save import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings+import androidx.compose.material.icons.filled.SettingsEthernet+import androidx.compose.material.icons.filled.SettingsInputHdmi import androidx.compose.material.icons.filled.Shield import androidx.compose.material.icons.filled.SettingsBackupRestore import androidx.compose.material.icons.filled.Share import androidx.compose.material.icons.filled.Shuffle+import androidx.compose.material.icons.filled.SignalWifi4Bar import androidx.compose.material.icons.filled.SkipNext import androidx.compose.material.icons.filled.SkipPrevious import androidx.compose.material.icons.filled.Sms@@ -251,6 +254,7 @@ import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material.icons.filled.Warning import androidx.compose.material.icons.filled.WaterDrop+import androidx.compose.material.icons.filled.WifiOff import androidx.compose.material.icons.filled.WbSunny import androidx.compose.material.icons.filled.Whatshot import androidx.compose.material.icons.filled.CheckCircle@@ -1739,3 +1743,24 @@ fun IconOnline(modifier: Modifier = Modifier, tint: Color = LocalContentColor.cu @Composable fun IconClock(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.AccessTime, "Clock", modifier, tint)++// --- TV launcher (HDMI inputs + network tile) ---+/** An HDMI port — an HDMI input tile on the TV home screen. */+@Composable+fun IconHdmi(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.SettingsInputHdmi, "HDMI", modifier, tint)++/** A wired network link — the TV is on Ethernet. */+@Composable+fun IconEthernet(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.SettingsEthernet, "Ethernet", modifier, tint)++/** Full Wi-Fi signal — the TV is online over Wi-Fi. */+@Composable+fun IconWifiFull(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.SignalWifi4Bar, "Wi-Fi", modifier, tint)++/** No Wi-Fi — the TV is offline. */+@Composable+fun IconWifiOff(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.WifiOff, "Offline", modifier, tint)
metadata_data/tvlauncher.md
diff --git a/metadata_data/tvlauncher.md b/metadata_data/tvlauncher.mdnew file mode 100644index 0000000000..4eedc71c68--- /dev/null+++ b/metadata_data/tvlauncher.md@@ -0,0 +1,10 @@+A calm, fast home screen for Android TV and Google TV++Features:+- Your apps as large 16:9 banners, six per row, with nothing else competing+- HDMI inputs, Play Store and Settings one D-pad press away on the bottom row+- Giant clock and date header with a live network status icon+- Reorder, replace or remove tiles with the remote; order survives restarts+- Can be set as the default home screen via the system Home role++100% offline
tvlauncher/AGENTS.md
diff --git a/tvlauncher/AGENTS.md b/tvlauncher/AGENTS.mdnew file mode 100644index 0000000000..0e92409122--- /dev/null+++ b/tvlauncher/AGENTS.md@@ -0,0 +1,56 @@+# AGENTS.md — tvlauncher/ (':tvlauncher')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `tvlauncher/` + allowed shared modules. Do not root-scan.++_Install: ./install tvlauncher (dev by default) for a USB-connected device. For a TV over+Wi-Fi: `sh tvlauncher/install-tv.sh <TV_IP>` builds, installs and offers to set it as the+default home; `sh tvlauncher/undo-tv.sh <TV_IP>` restores the stock home and uninstalls._+<!-- last-reviewed: 2026-10-19 -->+- Gradle: :tvlauncher / dir: tvlauncher/+- Package roots present: ui, data, domain, platform+- Entry files: MainActivity.kt, Route.kt, Navigation.kt+- Deps: androidx.tv.material (via common-conventions-tv), datastore.preferences+- Metadata: metadata_data/tvlauncher.md (present)+- Rust: no / screenshotTest: no (TV fullscreen grid, Layoutlib cannot render it — cast:tv precedent)++## Overview+**Purpose:** Calm TV home-screen replacement in the tv-detox shape — app banner grid, HDMI inputs, clock header — rebuilt in Compose/Kotlin. No account, nothing uploaded; row order in DataStore.+**Key features:**+- 6-per-row 16:9 banner grid topped up from installed leanback apps, persisted order+- Bottom glass row: Play Store, HDMI inputs, Settings, Add+- D-pad focus scale + caption, long-OK edit menu (move/replace/remove/uninstall)+- Clock header with live network tile; HOME role so it can be the default launcher+**Architecture / data-flow:** `ui/` home/grid/bottom-row/edit-menu → `platform/TvHomeViewModel` (+ `TvUiContract`) → `data/TvPrefs` (DataStore); `domain/` is pure row-order math (move/replace/remove, 6-per-row) with no Android imports; `platform/TvInputs` owns HDMI via TvInputManager.+**Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/TvHomeScreen.kt` → `platform/TvHomeViewModel.kt` → `domain/TvRowOrder.kt`.+**Gotchas:**+- New package, so the `:launcher` raw-animation exemption does NOT apply — focus motion goes through `library.ui` motion helpers+- TV banner art comes from `PackageManager.getActivityBanner()`, which has no repo precedent; loading is bounded-parallel with a non-reflowing placeholder+- Back on home is a no-op; HOME intent resets to the grid (no folder/page state to reset in v1)++## Key files+### Root — entry + navigation+- com/vayunmathur/tvlauncher/MainActivity.kt+- com/vayunmathur/tvlauncher/Navigation.kt+- com/vayunmathur/tvlauncher/Route.kt+### data/ — DataStore row order+- com/vayunmathur/tvlauncher/data/TvPrefs.kt+### domain/ — pure row math (no Android/Compose)+- com/vayunmathur/tvlauncher/domain/TvRowOrder.kt+### platform/ — ViewModel, apps, inputs, home role+- com/vayunmathur/tvlauncher/platform/TvHomeViewModel.kt+- com/vayunmathur/tvlauncher/platform/TvUiContract.kt+- com/vayunmathur/tvlauncher/platform/TvApps.kt+- com/vayunmathur/tvlauncher/platform/TvInputs.kt+### ui/ — clock header, grid, bottom row, edit menu+- com/vayunmathur/tvlauncher/ui/TvHomeScreen.kt+- com/vayunmathur/tvlauncher/ui/TvClockHeader.kt+- com/vayunmathur/tvlauncher/ui/TvAppGrid.kt+- com/vayunmathur/tvlauncher/ui/TvBottomRow.kt+- com/vayunmathur/tvlauncher/ui/TvEditMenu.kt++## Verify (this module only)+```+./gradlew :tvlauncher:compileDevKotlin+./gradlew :tvlauncher:lint+./gradlew :tvlauncher:checkMetadata+```
tvlauncher/build.gradle.kts
diff --git a/tvlauncher/build.gradle.kts b/tvlauncher/build.gradle.ktsnew file mode 100644index 0000000000..a28ff63e16--- /dev/null+++ b/tvlauncher/build.gradle.kts@@ -0,0 +1,33 @@+plugins {+ id("common-conventions-app")+ // androidx.tv, so the home screen is built on a design system that knows what a D-pad is.+ // Named here *alongside* the app convention rather than instead of it, even though it applies+ // that itself: the type-safe `launcherIcon` and `nativeAbis` accessors below are generated+ // from the plugins this file applies directly (the cast:tv precedent).+ id("common-conventions-tv")+ // No preview-metadata convention. The home screen is a TV-shaped fullscreen grid and+ // Layoutlib cannot render it into a *phone* listing image (the cast:tv precedent).+ // metadata_data/tvlauncher.md still exists, which is what generates a listing at all.+}++launcherIcon {+ symbol = "tv"+}++// Google TV hardware (the onn 4K Streaming Box and friends) runs a 32-bit userspace and+// reports only `armeabi-v7a,armeabi`, so an arm64-only APK is rejected at install time.+nativeAbis {+ armv7 = true+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.tvlauncher"+ }+}++dependencies {+ // Pinned-row order + quick settings (the BackupConfig preferencesDataStore pattern, not+ // Room: a launcher row order is a flat list, not relational data).+ implementation(libs.androidx.datastore.preferences)+}
tvlauncher/install-tv.sh
diff --git a/tvlauncher/install-tv.sh b/tvlauncher/install-tv.shnew file mode 100644index 0000000000..cbce1873bc--- /dev/null+++ b/tvlauncher/install-tv.sh@@ -0,0 +1,172 @@+#!/bin/sh+# Installs the TV Launcher on your TV and makes it the default home screen.+# Needs adb (and, for the build step, the repo's Gradle wrapper).+#+# sh install-tv.sh <TV_IP> build + install + set as default home+# APK=path/to.apk sh install-tv.sh <TV_IP>+# install a prebuilt APK instead of building+#+# The TV and this machine must be on the same network, with USB/network+# debugging turned on on the TV (Settings > System > Developer options).+# An IP gets :5555 added; an adb serial (like emulator-5554) is used as is.+set -e+cd "$(dirname "$0")/.."++TARGET="$1"+[ -n "$TARGET" ] || { echo "Usage: sh tvlauncher/install-tv.sh <TV_IP>" >&2; exit 1; }+command -v adb >/dev/null 2>&1 || {+ echo "adb is missing. Install it first:" >&2+ echo " Mac: brew install android-platform-tools" >&2+ echo " Windows: https://developer.android.com/tools/releases/platform-tools" >&2+ exit 1; }++case "$TARGET" in+ *.*.*.*:*) TV=$TARGET ;;+ *.*.*.*) TV=$TARGET:5555 ;;+ *) TV=$TARGET ;;+esac+case "$TV" in *:*) adb connect "$TV" >/dev/null || true ;; esac++state=$(adb -s "$TV" get-state 2>&1 || true)+case "$state" in+ device) ;;+ *unauthorized*) echo "Your TV is asking \"Allow debugging?\". Press Allow (tick \"Always allow\"), then run this again." >&2; exit 1 ;;+ *) echo "Can't reach $TV. Check the TV is on, on the same network, and has USB/network debugging turned on." >&2; exit 1 ;;+esac++ME=com.vayunmathur.tvlauncher/.MainActivity++if [ -n "$APK" ]; then+ [ -f "$APK" ] || { echo "No such APK: $APK" >&2; exit 1; }+else+ echo "Building…"+ ./gradlew :tvlauncher:assembleDev --console=plain -q+ APK_DIR=tvlauncher/build/outputs/apk/dev+ META=$APK_DIR/output-metadata.json+ APK_NAME=tvlauncher-dev.apk+ if [ -f "$META" ]; then+ FOUND=$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$META" | head -1 | sed -E 's/.*"([^"]+)"$/\1/')+ [ -n "$FOUND" ] && APK_NAME=$FOUND+ fi+ APK=$APK_DIR/$APK_NAME+ [ -f "$APK" ] || { echo "Build produced no APK where expected ($APK)." >&2; exit 1; }+fi++echo "Installing… If your TV shows a Google Play Protect message, follow it on the TV to allow the install."+adb -s "$TV" install -r "$APK"++# Keeps adb's exit status, so a failed command on the TV counts as failed here.+sh_tv() { _rc=0; _out=$(adb -s "$TV" shell "$@") || _rc=$?; [ -z "$_out" ] || printf '%s\n' "$_out" | tr -d '\r'; return $_rc; }+current_home() { sh_tv cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME | tail -1; }++# Make it the default home: the role (Android 10+) and the classic way.+if [ "$(sh_tv getprop ro.build.version.sdk)" -ge 29 ]; then+ sh_tv cmd role add-role-holder --user 0 android.app.role.HOME com.vayunmathur.tvlauncher >/dev/null 2>&1 || true+fi+sh_tv cmd package set-home-activity "$ME" >/dev/null 2>&1 || true++# Known TV home screens that are safe to turn off.+LAUNCHERS="com.google.android.tvlauncher com.google.android.apps.tv.launcherx com.google.android.leanbacklauncher+ com.mitv.tvhome com.amazon.tv.launcher"++# Only known launchers get turned off. Settings, setup and System UI also answer Home, and+# the TV needs them to start, so they, unknown apps and anything always running stay on.+is_launcher() {+ case "$1" in+ com.vayunmathur.tvlauncher|com.android.settings|com.android.tv.settings|com.android.systemui|com.android.provision) return 1 ;;+ *setup*|*wraith*|*provision*|*systemui*|*tvcenter*|*.tv.framework*|*.tvinput*) return 1 ;;+ esac+ case " $(echo $LAUNCHERS) " in *" $1 "*) ;; *) return 1 ;; esac+ # If we can't read its flags, or it always runs, leave it on.+ flags=$(sh_tv dumpsys package "$1" 2>/dev/null | sed -n '/pkgFlags=\[/{p;q;}')+ [ -n "$flags" ] || return 1+ case "$flags" in *PERSISTENT*) return 1 ;; esac+ return 0+}++is_off() { sh_tv pm list packages -d "$1" | grep -Fqx "package:$1"; }++# Turns apps off (not uninstall). Each one is saved on the TV first, so undo-tv.sh can+# always turn it back on. If it can't be saved, it's left on.+turn_off() {+ for p in "$@"; do+ if ! sh_tv "echo $p >> /data/local/tmp/tvlauncher-disabled.txt"; then+ echo "Leaving $p on: couldn't save it for undo-tv.sh." >&2; continue+ fi+ sh_tv pm disable-user --user 0 "$p" >/dev/null 2>&1 || true+ is_off "$p" || echo "Couldn't turn $p off." >&2+ done+ # Android saves this a few seconds later. Restarting before then can undo it.+ echo "Saving the change on the TV, this takes 15 seconds…"+ sleep 15+ sh_tv cmd package set-home-activity "$ME" >/dev/null 2>&1 || true+}++# Google TV's setup app. It's handled on its own below.+WRAITH=com.google.android.tungsten.setupwraith+home_apps() { sh_tv cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME 2>/dev/null \+ | grep / | sed 's|/.*||; s/^ *//' | sort -u; }++# Most TVs' own launchers still win when you press Home. The fix is to turn them off.+if [ "$(current_home)" != "$ME" ]; then+ others=""+ for p in $(home_apps); do+ if is_launcher "$p"; then others="$others $p"; continue; fi+ case "$p" in com.vayunmathur.tvlauncher|com.android.settings|com.android.tv.settings|$WRAITH) ;; *) echo "Leaving $p on: it may be needed for your TV to start." ;; esac+ done+ others=$(echo $others | tr ' ' '\n')+ if [ -n "$others" ]; then+ echo "Your TV's own home screen keeps taking over:"+ echo "$others" | sed 's/^/ /'+ answer=${YES:+y}+ if [ -z "$answer" ]; then+ printf "Turn it off so Home opens TV Launcher? You can undo this with undo-tv.sh. [y/N] "+ read answer </dev/tty || answer=n+ fi+ case "$answer" in+ y|Y|yes) turn_off $others ;;+ *) echo "Left it on. Your TV may keep opening its own home screen." ;;+ esac+ fi+fi++# On some Google TVs (like Sony BRAVIA) the setup app wins Home once Google TV's home+# screen is off. It's only offered if Home opens exactly that app, Google TV's home screen+# is already off, the TV has finished its first setup, and the system doesn't keep it+# always running. YES=1 doesn't cover it: it needs its own answer, or YES_SETUP=1.+LAUNCHERX=com.google.android.apps.tv.launcherx+off_list=$(sh_tv pm list packages -d "$LAUNCHERX" 2>/dev/null) || off_list=+if [ "$(current_home | sed 's|/.*||')" = "$WRAITH" ] \+ && printf '%s\n' "$off_list" | grep -Fqx "package:$LAUNCHERX"; then+ flags=$(sh_tv dumpsys package "$WRAITH" 2>/dev/null | sed -n '/pkgFlags=\[/{p;q;}')+ [ -n "$flags" ] || flags=PERSISTENT+ if [ "$(sh_tv settings get global device_provisioned)" != 1 ] || [ "$(sh_tv settings get secure user_setup_complete)" != 1 ]; then+ echo "Leaving $WRAITH on: your TV hasn't finished its first setup."+ else case "$flags" in+ *PERSISTENT*) echo "Leaving $WRAITH on: it may be needed for your TV to start." ;;+ *)+ echo "Google TV's setup app ($WRAITH) is taking over Home."+ echo "Turning it off fixed this on a Sony BRAVIA, but it hasn't been tested on every TV."+ echo "If anything goes wrong, undo-tv.sh turns it back on."+ if [ "$YES_SETUP" = 1 ]; then answer=y+ elif [ -n "$YES" ]; then answer=n+ else+ printf "Turn off the setup app too? [y/N] "+ read answer </dev/tty || answer=n+ fi+ case "$answer" in+ y|Y|yes) turn_off "$WRAITH" ;;+ *) echo "Left it on. Your TV may keep opening its setup app when you press Home. To turn it off later, run this again with YES_SETUP=1." ;;+ esac ;;+ esac; fi+fi++# The row order lives in the app itself (DataStore): defaults lead, installed leanback apps+# top the row up, and the remote's edit menu (hold OK on a tile) persists changes. Nothing+# to push from here.+adb -s "$TV" shell input keyevent KEYCODE_HOME+if [ "$(current_home)" = "$ME" ]; then+ echo "Done. Press Home on your remote to see it."+else+ echo "Installed, but your TV still opens its own home screen. If it asks which home screen to use, pick \"TV Launcher\" and choose Always."+fi
tvlauncher/src/main/AndroidManifest.xml
diff --git a/tvlauncher/src/main/AndroidManifest.xml b/tvlauncher/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..7942ef7474--- /dev/null+++ b/tvlauncher/src/main/AndroidManifest.xml@@ -0,0 +1,78 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <!-- Only for the network tile: Wi-Fi, Ethernet or offline, and the Wi-Fi signal. -->+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+ <!-- Lets "Uninstall" in the edit menu open Android's uninstall prompt. -->+ <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />++ <!-- Android 11+ only shows apps a home screen asks to see: TV apps and normal apps. -->+ <queries>+ <intent>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />+ </intent>+ <intent>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent>+ <!-- Settings screens the network tile opens. -->+ <intent>+ <action android:name="android.settings.WIFI_SETTINGS" />+ </intent>+ <intent>+ <action android:name="android.settings.WIRELESS_SETTINGS" />+ </intent>+ <intent>+ <action android:name="android.settings.SETTINGS" />+ </intent>+ <!-- Google TV's HDMI input player, so HDMI tiles open the right surface. -->+ <package android:name="com.google.android.tv.inputplayer" />+ </queries>++ <!-- Leanback is the point; touch is incidental (some TVs report a touchscreen). -->+ <uses-feature+ android:name="android.software.leanback"+ android:required="true" />+ <uses-feature+ android:name="android.hardware.touchscreen"+ android:required="false" />++ <application+ android:allowBackup="true"+ android:banner="@drawable/banner"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">+ <!--+ singleTask + stateNotNeeded are what make this behave like a home app: HOME delivers+ a new intent to the existing instance rather than stacking another copy, and the system+ may kill it without saving state because the row order lives in DataStore, not in a+ Bundle. LEANBACK_LAUNCHER keeps it visible in other launchers' TV rows; HOME + DEFAULT+ is what lets the system offer it as the default home screen.+ -->+ <activity+ android:name=".MainActivity"+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:excludeFromRecents="true"+ android:exported="true"+ android:launchMode="singleTask"+ android:screenOrientation="landscape"+ android:stateNotNeeded="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />+ </intent-filter>+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.HOME" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ </activity>+ </application>+</manifest>
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/MainActivity.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/MainActivity.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/MainActivity.ktnew file mode 100644index 0000000000..fd8663b064--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/MainActivity.kt@@ -0,0 +1,50 @@+package com.vayunmathur.tvlauncher++import android.content.Intent+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import androidx.compose.runtime.SideEffect+import com.vayunmathur.library.ui.MaActivity+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.tvlauncher.platform.TvHomeViewModel++/**+ * The TV home screen activity.+ *+ * `singleTask` plus `stateNotNeeded` in the manifest are what make it behave like a home+ * app: HOME delivers a new intent to the existing instance rather than stacking another+ * copy, and the system may kill it without saving state because the row order is in+ * DataStore, not in a `Bundle`. `edgeToEdge` is false: a TV has no phone chrome to draw+ * behind (the cast:tv precedent).+ */+class MainActivity : MaActivity() {+ override val edgeToEdge: Boolean = false++ private val viewModel: TvHomeViewModel by viewModels()+ private var backStack: NavBackStack<Route>? = null++ @Composable+ override fun Content() {+ val stack = rememberNavBackStack<Route>(Route.Home)+ SideEffect { backStack = stack }+ Navigation(viewModel, stack)+ }++ override fun onResume() {+ super.onResume()+ // Cheap enough to redo every time we come back: an app may have been installed or+ // uninstalled while we were away without us being alive to hear the callback.+ viewModel.refreshApps()+ }++ /**+ * Pressing HOME from inside another app comes back here. Resetting to the grid is what+ * makes HOME feel like HOME rather than a no-op (the :launcher MainActivity precedent).+ */+ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ setIntent(intent)+ backStack?.reset(Route.Home)+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Navigation.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Navigation.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Navigation.ktnew file mode 100644index 0000000000..5b9d32215d--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Navigation.kt@@ -0,0 +1,18 @@+package com.vayunmathur.tvlauncher++import androidx.compose.runtime.Composable+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.tvlauncher.platform.TvHomeViewModel+import com.vayunmathur.tvlauncher.ui.TvHomePage++@Composable+fun Navigation(+ viewModel: TvHomeViewModel,+ backStack: NavBackStack<Route>,+) {+ // Opaque: a TV home screen paints its own warm gradient, never the wallpaper behind it.+ MainNavigation(backStack) {+ entry<Route.Home> { TvHomePage(viewModel) }+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Route.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Route.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Route.ktnew file mode 100644index 0000000000..ade3b40121--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/Route.kt@@ -0,0 +1,18 @@+package com.vayunmathur.tvlauncher++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++/**+ * The nav graph is a single destination in v1.+ *+ * The edit menu (move/replace/remove) and the add-app picker are **not** routes: they are+ * overlays inside the home screen, because D-pad focus must stay inside one focus tree while+ * editing (the :launcher drawer-as-overlay precedent, minus the drag system).+ */+@Serializable+sealed interface Route : NavKey {+ /** The banner grid with the clock header and bottom row. */+ @Serializable+ data object Home : Route+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/data/TvPrefs.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/data/TvPrefs.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/data/TvPrefs.ktnew file mode 100644index 0000000000..2d05d3e1b9--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/data/TvPrefs.kt@@ -0,0 +1,49 @@+package com.vayunmathur.tvlauncher.data++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++/** The persisted home-screen configuration: just the row order, like tv-detox's `apps`. */+data class TvSettings(+ /** Saved top-row packages in order, or null when the row still follows the defaults. */+ val appOrder: List<String>? = null,+ /** Optional settings shortcuts by the clock (`bluetooth`, `sound`, `picture`). */+ val quickSettings: List<String> = emptyList(),+)++private val Context.tvDataStore by preferencesDataStore(name = "tvlauncher_config")++/** DataStore-backed persistence for [TvSettings] (the BackupConfig pattern, not Room). */+class TvPrefs(private val context: Context) {+ val settings: Flow<TvSettings> = context.tvDataStore.data.map { p ->+ TvSettings(+ appOrder = p[KEY_APPS]+ ?.split(',')+ ?.map { it.trim() }+ ?.filter { it.isNotEmpty() },+ quickSettings = p[KEY_QUICK]+ ?.split(',')+ ?.map { it.trim().lowercase() }+ ?.filter { it.isNotEmpty() }+ ?: emptyList(),+ )+ }++ /** Saves the top row as the app list, so it no longer follows the defaults. */+ suspend fun saveOrder(order: List<String>) {+ context.tvDataStore.edit { it[KEY_APPS] = order.joinToString(",") }+ }++ suspend fun saveQuick(quick: List<String>) {+ context.tvDataStore.edit { it[KEY_QUICK] = quick.joinToString(",") }+ }++ companion object {+ private val KEY_APPS = stringPreferencesKey("apps")+ private val KEY_QUICK = stringPreferencesKey("quick")+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/domain/TvRowOrder.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/domain/TvRowOrder.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/domain/TvRowOrder.ktnew file mode 100644index 0000000000..f5f4fae17e--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/domain/TvRowOrder.kt@@ -0,0 +1,88 @@+package com.vayunmathur.tvlauncher.domain++/**+ * Pure row-order math for the TV home screen: no Android, no Compose.+ *+ * Mirrors the tv-detox ordering rules: a saved list wins verbatim (minus packages that+ * disappeared); otherwise the built-in defaults lead and installed leanback apps top the row+ * up to one full row of [PER_ROW].+ */+object TvRowOrder {+ const val PER_ROW = 6+ const val MAX_INPUTS = 4++ /** The default top row, in order (tv-detox's `apps.txt`). Missing apps are skipped. */+ val DEFAULT_ROW: List<String> = listOf(+ "com.google.android.youtube.tv",+ "com.netflix.ninja",+ "com.amazon.amazonvideo.livingroom",+ "com.disney.disneyplus",+ "com.hulu.livingroomplus",+ "com.wbd.stream",+ )++ /** Packages that are never tiles, even when launchable (tv-detox's `NOT_APPS`). */+ val NEVER_TILES: Set<String> = setOf(+ "com.android.vending",+ "com.android.tv.settings",+ "com.android.tv",+ "com.google.android.tvlauncher",+ "com.google.android.apps.tv.launcherx",+ "com.google.android.leanbacklauncher",+ )++ const val PLAY_STORE = "com.android.vending"++ /**+ * The top row as shown, in order.+ *+ * @param saved the persisted order, or null when the row still follows the defaults.+ * @param installed every installed launchable package (leanback first, then phone+ * launcher), already minus this app itself and minus [NEVER_TILES].+ */+ fun mergeOrder(+ saved: List<String>?,+ installed: List<String>,+ defaults: List<String> = DEFAULT_ROW,+ ): List<String> {+ val present = installed.toSet()+ val wanted = saved ?: defaults+ val row = wanted.filter { it in present }.toMutableList()+ if (saved == null) {+ // Top up with other TV apps on this TV, stopping at one full row.+ for (pkg in installed) {+ if (row.size >= PER_ROW) break+ if (pkg !in row) row.add(pkg)+ }+ }+ return row+ }++ /** Slides the entry at [from] to [to], clamping into range. */+ fun move(order: List<String>, from: Int, to: Int): List<String> {+ if (from !in order.indices) return order+ val clamped = to.coerceIn(0, order.size - 1)+ if (clamped == from) return order+ return order.toMutableList().apply { add(clamped, removeAt(from)) }+ }++ fun removeAt(order: List<String>, index: Int): List<String> =+ if (index in order.indices) order.toMutableList().apply { removeAt(index) } else order++ fun replaceAt(order: List<String>, index: Int, pkg: String): List<String> {+ if (pkg.isBlank()) return order+ val without = order.filter { it != pkg }+ return if (index in without.indices) {+ without.toMutableList().apply { set(index, pkg) }+ } else {+ without + pkg+ }+ }++ /**+ * How many HDMI tiles fit on the bottom row: the row holds [PER_ROW] with room always+ * kept for Settings and Add, plus the Play Store when it is shown (tv-detox's `room`).+ */+ fun maxHdmiSlots(hasStore: Boolean): Int = (PER_ROW - 2 - if (hasStore) 1 else 0)+ .coerceIn(0, MAX_INPUTS)+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvApps.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvApps.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvApps.ktnew file mode 100644index 0000000000..f0b93c71bb--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvApps.kt@@ -0,0 +1,84 @@+package com.vayunmathur.tvlauncher.platform++import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.graphics.drawable.Drawable++/** One launchable tile on the home screen. */+data class TvAppEntry(+ val packageName: String,+ val label: String,+ val leanback: Boolean,+)++/**+ * Discovers launchable apps, leanback-first (the tv-detox `appList`/`showAddMenu` logic).+ *+ * Leanback intent first, phone launcher intent as fallback — a sideloaded phone app on a TV+ * box still gets a tile rather than vanishing. System launchers and settings surfaces from+ * [TvRowOrder.NEVER_TILES] never become tiles, except the Play Store, which owns a bottom-row+ * slot of its own.+ */+object TvApps {+ fun installed(context: Context, selfPackage: String): List<TvAppEntry> {+ val pm = context.packageManager+ val leanbackPkgs = queryCategory(pm, Intent.CATEGORY_LEANBACK_LAUNCHER)+ val phonePkgs = queryCategory(pm, Intent.CATEGORY_LAUNCHER)+ // Keyed by package: two apps can share a label (locale duplicates, work-profile+ // clones), and keying by label would silently drop the second one.+ val seen = mutableSetOf<String>()+ val out = mutableListOf<TvAppEntry>()+ for (pkg in leanbackPkgs + phonePkgs) {+ if (pkg == selfPackage || pkg in seen) continue+ seen.add(pkg)+ val isLeanback = pkg in leanbackPkgs+ if (pkg in com.vayunmathur.tvlauncher.domain.TvRowOrder.NEVER_TILES &&+ pkg != com.vayunmathur.tvlauncher.domain.TvRowOrder.PLAY_STORE+ ) {+ continue+ }+ out.add(TvAppEntry(pkg, labelOf(pm, pkg), isLeanback))+ }+ return out+ }++ fun launchIntent(pm: PackageManager, pkg: String): Intent? =+ pm.getLeanbackLaunchIntentForPackage(pkg) ?: pm.getLaunchIntentForPackage(pkg)++ fun banner(pm: PackageManager, pkg: String): Drawable? {+ val launch = launchIntent(pm, pkg) ?: return appIcon(pm, pkg)+ return runCatching { pm.getActivityBanner(launch) }.getOrNull()+ ?: runCatching { pm.getApplicationBanner(pkg) }.getOrNull()+ ?: appIcon(pm, pkg)+ }++ fun appIcon(pm: PackageManager, pkg: String): Drawable? =+ runCatching { pm.getApplicationIcon(pkg) }.getOrNull()++ fun labelOf(pm: PackageManager, pkg: String): String =+ runCatching { pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString() }+ .getOrNull() ?: pkg++ fun isUserInstalled(pm: PackageManager, pkg: String): Boolean = runCatching {+ val info = pm.getApplicationInfo(pkg, 0)+ (info.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0+ }.getOrDefault(false)++ private fun queryCategory(pm: PackageManager, category: String): List<String> {+ val q = Intent(Intent.ACTION_MAIN).addCategory(category)+ return runCatching { pm.queryIntentActivities(q, 0) }+ .getOrDefault(emptyList())+ .map { it.activityInfo.packageName }+ .distinct()+ }+}++/** Extra launch details the ViewModel hands to the open path. */+data class TvLaunchTarget(+ val intent: Intent? = null,+ val openSettings: Boolean = false,+ val openNetworkSettings: Boolean = false,+ val addApp: Boolean = false,+ val hdmiInputId: String? = null,+)
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvArtCache.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvArtCache.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvArtCache.ktnew file mode 100644index 0000000000..e33c98c2bf--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvArtCache.kt@@ -0,0 +1,41 @@+package com.vayunmathur.tvlauncher.platform++import android.app.Application+import android.graphics.drawable.Drawable+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Per-process banner/icon cache: package-change rebuilds re-query the package list but must+ * not re-rasterise art the grid already holds. Drawables are immutable snapshots, so sharing+ * them across rebuilds is safe.+ */+class TvArtCache(private val app: Application) {+ private val banners = mutableMapOf<String, Drawable?>()+ private val icons = mutableMapOf<String, Drawable?>()++ suspend fun banner(pkg: String): Drawable? = withContext(Dispatchers.IO) {+ synchronized(banners) { banners[pkg] } ?: loadBanner(pkg)+ }++ suspend fun icon(pkg: String): Drawable? = withContext(Dispatchers.IO) {+ synchronized(icons) { icons[pkg] } ?: loadIcon(pkg)+ }++ private fun loadBanner(pkg: String): Drawable? {+ val banner = TvApps.banner(app.packageManager, pkg)+ synchronized(banners) { banners[pkg] = banner }+ return banner+ }++ private fun loadIcon(pkg: String): Drawable? {+ val icon = TvApps.appIcon(app.packageManager, pkg)+ synchronized(icons) { icons[pkg] = icon }+ return icon+ }++ fun drop(pkg: String) {+ synchronized(banners) { banners.remove(pkg) }+ synchronized(icons) { icons.remove(pkg) }+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeRole.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeRole.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeRole.ktnew file mode 100644index 0000000000..130b88dfe4--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeRole.kt@@ -0,0 +1,35 @@+package com.vayunmathur.tvlauncher.platform++import android.app.Activity+import android.app.role.RoleManager+import android.content.Intent+import android.content.pm.PackageManager+import android.provider.Settings++/**+ * The HOME-role plumbing that lets this app become the default launcher.+ *+ * Follows the :launcher `requestHomeRole` / `isDefaultHome` precedent: prefer the role+ * request when the platform offers it, otherwise fall back to the settings page where the+ * choice actually lives.+ */+object TvHomeRole {+ fun isDefaultHome(activity: Activity): Boolean {+ val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)+ val resolved = activity.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)+ return resolved?.activityInfo?.packageName == activity.packageName+ }++ fun requestHomeRole(activity: Activity): Boolean {+ val roleManager = activity.getSystemService(RoleManager::class.java)+ val intent = if (roleManager?.isRoleAvailable(RoleManager.ROLE_HOME) == true) {+ roleManager.createRequestRoleIntent(RoleManager.ROLE_HOME)+ } else {+ Intent(Settings.ACTION_HOME_SETTINGS)+ }+ return runCatching {+ activity.startActivity(intent)+ true+ }.getOrDefault(false)+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeViewModel.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeViewModel.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeViewModel.ktnew file mode 100644index 0000000000..bc1ba2faa2--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvHomeViewModel.kt@@ -0,0 +1,282 @@+package com.vayunmathur.tvlauncher.platform++import android.app.Application+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.net.Uri+import android.provider.Settings+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.tvlauncher.data.TvPrefs+import com.vayunmathur.tvlauncher.domain.TvRowOrder+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext++/**+ * Owns the row order, the app list, the HDMI inputs and the edit-menu state.+ *+ * Banner/icon drawables are loaded off-main and cached per process in [TvArtCache], so a+ * package-change rebuild does not re-rasterise art the grid already holds.+ */+class TvHomeViewModel(app: Application) : AndroidViewModel(app) {+ private val prefs = TvPrefs(app)+ private val artCache = TvArtCache(app)+ /** Serializes rebuilds: package broadcasts burst, and last-writer must win. */+ private val refreshMutex = Mutex()++ private val _home = MutableStateFlow(TvHomeState())+ val home: StateFlow<TvHomeState> = _home++ private val packagesChanged = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ refreshApps()+ }+ }++ init {+ val filter = IntentFilter().apply {+ addAction(Intent.ACTION_PACKAGE_ADDED)+ addAction(Intent.ACTION_PACKAGE_REMOVED)+ addAction(Intent.ACTION_PACKAGE_CHANGED)+ addDataScheme("package")+ }+ app.registerReceiver(packagesChanged, filter)+ refreshApps()+ }++ override fun onCleared() {+ runCatching { getApplication<Application>().unregisterReceiver(packagesChanged) }+ }++ /** Rebuilds the grid: re-query apps + inputs, re-merge with the saved order. */+ fun refreshApps() {+ viewModelScope.launch {+ refreshMutex.withLock {+ val context = getApplication<Application>()+ // Don't clobber an in-progress move: the order on screen is newer than+ // DataStore until finishMove persists it.+ if (_home.value.movingKey != null) return@withLock+ _home.value = _home.value.copy(loading = true)+ val settings = withContext(Dispatchers.IO) { prefs.settings.first() }+ val entries = withContext(Dispatchers.IO) { TvApps.installed(context, context.packageName) }+ val row = TvRowOrder.mergeOrder(settings.appOrder, entries.map { it.packageName })+ val byPkg = entries.associateBy { it.packageName }+ val tiles = withContext(Dispatchers.IO) {+ row.mapNotNull { pkg ->+ val entry = byPkg[pkg] ?: return@mapNotNull null+ TvTile(+ packageName = pkg,+ label = entry.label,+ banner = artCache.banner(pkg),+ appIcon = artCache.icon(pkg),+ userInstalled = TvApps.isUserInstalled(context.packageManager, pkg),+ )+ }+ }+ val hasStore = byPkg.containsKey(TvRowOrder.PLAY_STORE) &&+ TvRowOrder.PLAY_STORE !in row+ val inputs = withContext(Dispatchers.IO) {+ TvInputs.list(context, TvRowOrder.maxHdmiSlots(hasStore))+ }+ val storeLabel = byPkg[TvRowOrder.PLAY_STORE]?.label ?: "Play Store"+ _home.value = _home.value.copy(+ rowApps = tiles,+ showPlayStore = hasStore,+ playStoreLabel = storeLabel,+ hdmiInputs = inputs,+ loading = false,+ )+ }+ }+ }++ // --- open ---++ fun openTile(pkg: String) {+ val context = getApplication<Application>()+ val intent = TvApps.launchIntent(context.packageManager, pkg) ?: run {+ AppMessages.show("Could not open that app")+ return+ }+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (runCatching { context.startActivity(intent) }.isFailure) {+ AppMessages.show("Could not open that app")+ }+ }++ fun openPlayStore() = openTile(TvRowOrder.PLAY_STORE)++ fun openInput(inputId: String) {+ TvInputs.open(getApplication(), inputId)+ }++ fun openSettings() {+ val context = getApplication<Application>()+ val intent = Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (runCatching { context.startActivity(intent) }.isFailure) {+ AppMessages.show("Could not open settings")+ }+ }++ fun openNetworkSettings() {+ val context = getApplication<Application>()+ for (action in listOf(+ Settings.ACTION_WIFI_SETTINGS,+ Settings.ACTION_WIRELESS_SETTINGS,+ Settings.ACTION_SETTINGS,+ )) {+ val intent = Intent(action).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (runCatching { context.startActivity(intent) }.isSuccess) return+ }+ AppMessages.show("Could not open network settings")+ }++ // --- edit mode ---++ fun openEditMenu(pkg: String) {+ _home.value = _home.value.copy(editingKey = pkg, movingKey = null)+ }++ fun closeEditMenu() {+ _home.value = _home.value.copy(+ editingKey = null,+ movingKey = null,+ addCandidates = emptyList(),+ addReplacesIndex = -1,+ showAddMenu = false,+ )+ }++ fun startMove(pkg: String) {+ _home.value = _home.value.copy(editingKey = null, movingKey = pkg)+ }++ fun finishMove() {+ viewModelScope.launch {+ refreshMutex.withLock {+ withContext(Dispatchers.IO) {+ prefs.saveOrder(_home.value.rowApps.map { it.packageName })+ }+ _home.value = _home.value.copy(movingKey = null)+ }+ }+ }++ /** Exits move mode without persisting (Back while moving). */+ fun cancelMove() {+ _home.value = _home.value.copy(movingKey = null)+ refreshApps()+ }++ fun moveKey(pkg: String, step: Int) {+ // Guard against stale closures: only the tile actually being moved may move.+ if (_home.value.movingKey != pkg) return+ val order = _home.value.rowApps.map { it.packageName }.toMutableList()+ val from = order.indexOf(pkg)+ if (from < 0) return+ val to = (from + step).coerceIn(0, order.size - 1)+ if (to == from) return+ val moved = TvRowOrder.move(order, from, to)+ _home.value = _home.value.copy(+ rowApps = reorderTiles(_home.value.rowApps, moved),+ )+ }++ fun removeTile(pkg: String) {+ val kept = _home.value.rowApps.map { it.packageName }.filter { it != pkg }+ _home.value = _home.value.copy(rowApps = _home.value.rowApps.filter { it.packageName != pkg })+ closeEditMenu()+ viewModelScope.launch {+ refreshMutex.withLock {+ withContext(Dispatchers.IO) { prefs.saveOrder(kept) }+ }+ }+ }++ fun openAddMenu(replaceIndex: Int = -1) {+ viewModelScope.launch {+ val context = getApplication<Application>()+ val onRow = _home.value.rowApps.map { it.packageName }.toSet()+ val candidates = withContext(Dispatchers.IO) {+ TvApps.installed(context, context.packageName)+ .filter { it.packageName !in onRow }+ .filter {+ it.packageName !in TvRowOrder.NEVER_TILES ||+ it.packageName == TvRowOrder.PLAY_STORE+ }+ .sortedBy { it.label.lowercase() }+ }+ _home.value = _home.value.copy(+ editingKey = null,+ addCandidates = candidates,+ addReplacesIndex = replaceIndex,+ showAddMenu = true,+ )+ }+ }++ fun pickAddCandidate(pkg: String) {+ val state = _home.value+ val order = state.rowApps.map { it.packageName }+ val updated = TvRowOrder.replaceAt(order, state.addReplacesIndex, pkg)+ viewModelScope.launch {+ refreshMutex.withLock {+ withContext(Dispatchers.IO) { prefs.saveOrder(updated) }+ _home.value = _home.value.copy(+ addCandidates = emptyList(),+ addReplacesIndex = -1,+ showAddMenu = false,+ )+ }+ // Outside the lock: refreshApps takes it in turn, so the save above is visible.+ refreshApps()+ }+ }++ fun uninstallOrInfo(pkg: String) {+ val context = getApplication<Application>()+ val user = TvApps.isUserInstalled(context.packageManager, pkg)+ val uri = Uri.parse("package:$pkg")+ val intent = if (user) {+ Intent(Intent.ACTION_DELETE, uri)+ } else {+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri)+ }.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (runCatching { context.startActivity(intent) }.isFailure) {+ AppMessages.show("Could not open that")+ }+ closeEditMenu()+ }++ // --- home role ---++ fun refreshDefaultHome(activity: android.app.Activity) {+ _home.value = _home.value.copy(isDefaultHome = TvHomeRole.isDefaultHome(activity))+ }++ fun requestHomeRole(activity: android.app.Activity) {+ if (!TvHomeRole.requestHomeRole(activity)) {+ AppMessages.show("Could not open home app settings")+ }+ }++ // --- internals ---++ private fun persistOrder(order: List<String>) {+ viewModelScope.launch(Dispatchers.IO) { prefs.saveOrder(order) }+ }++ private fun reorderTiles(tiles: List<TvTile>, order: List<String>): List<TvTile> {+ val byPkg = tiles.associateBy { it.packageName }+ return order.mapNotNull { byPkg[it] }+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvInputs.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvInputs.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvInputs.ktnew file mode 100644index 0000000000..8568d6de97--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvInputs.kt@@ -0,0 +1,69 @@+package com.vayunmathur.tvlauncher.platform++import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.media.tv.TvContract+import android.media.tv.TvInputInfo+import android.media.tv.TvInputManager++/** One HDMI input tile on the bottom row. */+data class TvHdmiInput(+ val id: String,+ val label: String,+)++/**+ * The TV's own HDMI inputs (not devices behind them), in order, skipping hidden ones+ * (the tv-detox `hdmiInputs`/`inputLabel` logic).+ */+object TvInputs {+ fun list(context: Context, max: Int): List<TvHdmiInput> {+ val manager = context.getSystemService(Context.TV_INPUT_SERVICE) as? TvInputManager+ ?: return emptyList()+ return runCatching { manager.tvInputList }.getOrDefault(emptyList())+ .filter { it.type == TvInputInfo.TYPE_HDMI && it.parentId == null && !it.isHidden(context) }+ .sortedBy { it.id }+ .take(max)+ .map { TvHdmiInput(it.id, labelOf(context, it)) }+ }++ private fun labelOf(context: Context, input: TvInputInfo): String {+ val custom = runCatching { input.loadCustomLabel(context) }.getOrNull()+ if (!custom.isNullOrEmpty()) return custom.toString()+ val label = runCatching { input.loadLabel(context) }.getOrNull()+ return if (!label.isNullOrEmpty()) label.toString() else "HDMI"+ }++ /**+ * Opens an HDMI input: Google TV's input player first when the TV itself routes HDMI+ * through it (some Google TVs ship the stock Live TV app as a stub that starts fine but+ * only says hello), then the stock and Droidlogic Live TV apps, then whatever the TV picks.+ */+ fun open(context: Context, inputId: String) {+ val pm = context.packageManager+ val view = Intent(Intent.ACTION_VIEW, TvContract.buildChannelUriForPassthroughInput(inputId))+ val tries = mutableListOf<Intent>()+ val def = runCatching { pm.resolveActivity(view, PackageManager.MATCH_DEFAULT_ONLY) }.getOrNull()+ if (def?.activityInfo != null && def.activityInfo.packageName == INPUT_PLAYER) {+ tries.add(Intent(view).setClassName(INPUT_PLAYER, def.activityInfo.name))+ }+ for ((pkg, cls) in LIVE_TV) {+ val t = Intent(view).setClassName(pkg, cls)+ if (t.resolveActivity(pm) != null) tries.add(t)+ }+ tries.add(view)+ for (t in tries) {+ t.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (runCatching { context.startActivity(t) }.isSuccess) return+ }+ }++ private const val INPUT_PLAYER = "com.google.android.tv.inputplayer"++ /** Live TV apps an HDMI tile can open, in order (the tv-detox `LIVE_TV` table). */+ private val LIVE_TV = listOf(+ "com.android.tv" to "com.android.tv.MainActivity",+ "com.droidlogic.android.tv" to "com.android.tv.TvActivity",+ )+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvUiContract.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvUiContract.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvUiContract.ktnew file mode 100644index 0000000000..d055b7d623--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/platform/TvUiContract.kt@@ -0,0 +1,32 @@+package com.vayunmathur.tvlauncher.platform++import android.graphics.drawable.Drawable++/** One row-app tile as the screen renders it. */+data class TvTile(+ val packageName: String,+ val label: String,+ val banner: Drawable?,+ val appIcon: Drawable?,+ val userInstalled: Boolean,+)++/** Stateless home-screen state, collected from [TvHomeViewModel]. */+data class TvHomeState(+ val rowApps: List<TvTile> = emptyList(),+ val showPlayStore: Boolean = false,+ val playStoreLabel: String = "Play Store",+ val hdmiInputs: List<TvHdmiInput> = emptyList(),+ /** The package being moved with the arrows, or null when not in move mode. */+ val movingKey: String? = null,+ /** Packages offered by the add menu (not on the row, by label). */+ val addCandidates: List<TvAppEntry> = emptyList(),+ /** Index the add menu replaces, or -1 to append. */+ val addReplacesIndex: Int = -1,+ /** The package the edit menu is open for, or null when closed. */+ val editingKey: String? = null,+ /** True while the add/replace picker is open (even when it has no candidates). */+ val showAddMenu: Boolean = false,+ val isDefaultHome: Boolean = false,+ val loading: Boolean = true,+)
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvAppGrid.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvAppGrid.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvAppGrid.ktnew file mode 100644index 0000000000..f4594c4ef9--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvAppGrid.kt@@ -0,0 +1,286 @@+package com.vayunmathur.tvlauncher.ui++import android.graphics.drawable.Drawable+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.scale+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.painter.BitmapPainter+import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.KeyEventType+import androidx.compose.ui.input.key.key+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.input.key.type+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.core.graphics.drawable.toBitmap+import com.vayunmathur.library.ui.IconApps+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.animatedFloat+import com.vayunmathur.tvlauncher.domain.TvRowOrder+import com.vayunmathur.tvlauncher.platform.TvHomeState+import com.vayunmathur.tvlauncher.platform.TvTile+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * The app banner grid: six 16:9 tiles per row like the tv-detox reference.+ *+ * Focused tiles scale to ~1.1 with their label underneath; unfocused banner tiles show art+ * only. Tiles without banner art fall back to a glass tile with the app icon + label, so the+ * grid never reflows while art loads (the LauncherAppIcon placeholder precedent).+ *+ * Art rasterises off-main via [rememberRaster]: `Drawable.toBitmap` on a low-end TV box in+ * composition is jank, and on a cold grid is an ANR.+ */+@Composable+fun TvAppGrid(+ state: TvHomeState,+ onOpenTile: (String) -> Unit,+ onOpenEditMenu: (String) -> Unit,+ onMoveKey: (String, Int) -> Unit,+ onFinishMove: () -> Unit,+) {+ val firstFocus = remember { FocusRequester() }+ LazyVerticalGrid(+ columns = GridCells.Fixed(TvRowOrder.PER_ROW),+ horizontalArrangement = Arrangement.spacedBy(36.dp),+ verticalArrangement = Arrangement.spacedBy(36.dp),+ modifier = Modifier.fillMaxWidth(),+ // A grid inside the screen's scroller: the whole page scrolls as one.+ userScrollEnabled = false,+ ) {+ items(state.rowApps, key = { it.packageName }) { tile ->+ TvBannerTile(+ tile = tile,+ moving = state.movingKey == tile.packageName,+ focusRequester = if (tile == state.rowApps.firstOrNull()) firstFocus else null,+ onOpen = { onOpenTile(tile.packageName) },+ onEdit = { onOpenEditMenu(tile.packageName) },+ onMove = { step -> onMoveKey(tile.packageName, step) },+ onFinishMove = onFinishMove,+ )+ }+ }+ // Cold start: D-pad does nothing until something holds focus, so hand it to the first+ // tile once the row arrives.+ LaunchedEffect(state.rowApps.isNotEmpty(), state.loading) {+ if (state.rowApps.isNotEmpty() && !state.loading) {+ runCatching { firstFocus.requestFocus() }+ }+ }+}++private val MoveFinishKeys = setOf(Key.Enter, Key.NumPadEnter, Key.DirectionCenter)++@Composable+private fun TvBannerTile(+ tile: TvTile,+ moving: Boolean,+ focusRequester: FocusRequester?,+ onOpen: () -> Unit,+ onEdit: () -> Unit,+ onMove: (Int) -> Unit,+ onFinishMove: () -> Unit,+) {+ var focused by remember { mutableStateOf(false) }+ val scale = animatedFloat(if (focused) 1.1f else 1f)++ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .aspectRatio(16f / 9f)+ .scale(scale)+ .clip(MaterialTheme.shapes.largeIncreased)+ .background(+ if (tile.banner != null) Color(0xFF1E1A1C) else Color(0x13FFFFFF),+ )+ .then(+ if (tile.banner == null) {+ Modifier.border(+ width = 2.dp,+ color = Color(0x17FFFFFF),+ shape = MaterialTheme.shapes.largeIncreased,+ )+ } else {+ Modifier+ },+ )+ .then(+ if (moving) {+ Modifier.border(+ width = 4.dp,+ color = Color.White,+ shape = MaterialTheme.shapes.largeIncreased,+ )+ } else {+ Modifier+ },+ )+ .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier)+ .onFocusChanged { focused = it.isFocused }+ .focusable()+ .clickable(onClick = onOpen)+ .onPreviewKeyEvent { event ->+ // One edge only: D-pad repeats arrive as KeyDown, Menu as KeyUp. Handling+ // both edges double-fires (finish-then-edit-menu); handling neither edge+ // consistently lets the KeyUp fall through to clickable and launch the app.+ if (moving) {+ if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false+ when (event.key) {+ Key.DirectionLeft -> {+ onMove(-1)+ true+ }+ Key.DirectionRight -> {+ onMove(1)+ true+ }+ Key.DirectionUp -> {+ onMove(-TvRowOrder.PER_ROW)+ true+ }+ Key.DirectionDown -> {+ onMove(TvRowOrder.PER_ROW)+ true+ }+ in MoveFinishKeys -> {+ onFinishMove()+ true+ }+ // Back cancels the move; the screen's BackHandler owns it, so let+ // it through rather than swallowing it here.+ Key.Back -> false+ // Swallow the rest while moving so stray keys cannot open menus.+ Key.Menu -> true+ else -> false+ }+ } else {+ if (event.type != KeyEventType.KeyUp) return@onPreviewKeyEvent false+ when (event.key) {+ Key.Menu -> {+ onEdit()+ true+ }+ else -> false+ }+ }+ },+ contentAlignment = Alignment.Center,+ ) {+ val banner = tile.banner+ if (banner != null) {+ val bitmap = rememberRaster(banner, 320, 180)+ if (bitmap != null) {+ Image(+ painter = BitmapPainter(bitmap),+ contentDescription = null,+ contentScale = ContentScale.Crop,+ modifier = Modifier.fillMaxWidth(),+ )+ } else {+ TvGlassIcon(tile = tile)+ }+ } else {+ TvGlassIcon(tile = tile)+ }+ }+ // Banner tiles show their name underneath when focused (the tv-detox caption).+ if (focused || tile.banner == null) {+ Text(+ text = tile.label,+ style = MaterialTheme.typography.labelLarge,+ color = Color.White,+ textAlign = TextAlign.Center,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 12.dp),+ )+ }+ }+}++/** Rasterises a drawable off-main; null while loading or on failure (caller shows fallback). */+@Composable+private fun rememberRaster(drawable: Drawable, width: Int, height: Int): ImageBitmap? {+ val density = LocalContext.current.resources.displayMetrics.density+ val w = (width * density).toInt().coerceAtLeast(1)+ val h = (height * density).toInt().coerceAtLeast(1)+ val bitmap by produceState<ImageBitmap?>(initialValue = null, drawable, w, h) {+ value = withContext(Dispatchers.Default) {+ runCatching { drawable.toBitmap(width = w, height = h).asImageBitmap() }.getOrNull()+ }+ }+ return bitmap+}++/** Quiet glass tile for apps without TV banner art: icon above label. */+@Composable+private fun TvGlassIcon(tile: TvTile) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ val icon: Drawable? = tile.appIcon+ if (icon != null) {+ val bitmap = rememberRaster(icon, 128, 128)+ if (bitmap != null) {+ Image(+ painter = BitmapPainter(bitmap),+ contentDescription = null,+ modifier = Modifier.size(64.dp),+ )+ } else {+ IconApps(modifier = Modifier.size(44.dp), tint = Color.White)+ }+ } else {+ IconApps(modifier = Modifier.size(44.dp), tint = Color.White)+ }+ Text(+ text = tile.label,+ style = MaterialTheme.typography.labelLarge,+ color = Color(0xE0FFFFFF),+ textAlign = TextAlign.Center,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = 12.dp, start = 16.dp, end = 16.dp),+ )+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvBottomRow.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvBottomRow.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvBottomRow.ktnew file mode 100644index 0000000000..a3d25bae06--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvBottomRow.kt@@ -0,0 +1,152 @@+package com.vayunmathur.tvlauncher.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.scale+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconHdmi+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.animatedFloat+import com.vayunmathur.tvlauncher.domain.TvRowOrder+import com.vayunmathur.tvlauncher.platform.TvHdmiInput+import com.vayunmathur.tvlauncher.platform.TvHomeState++/**+ * The bottom glass row: Play Store, HDMI inputs, Settings, Add (the tv-detox bottom row).+ *+ * Glass tiles with icon above label; focused tiles lift to ~1.1 like the banner grid.+ */+@Composable+fun TvBottomRow(+ state: TvHomeState,+ onOpenPlayStore: () -> Unit,+ onOpenInput: (String) -> Unit,+ onOpenSettings: () -> Unit,+ onOpenAddMenu: () -> Unit,+) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(36.dp),+ modifier = Modifier.fillMaxWidth(),+ ) {+ if (state.showPlayStore) {+ TvGlassTile(+ label = state.playStoreLabel.ifBlank { "Play Store" },+ onClick = onOpenPlayStore,+ modifier = Modifier.weight(1f),+ ) {+ IconPlay(modifier = Modifier.size(44.dp), tint = Color.White)+ }+ }+ for (input in state.hdmiInputs) {+ key(input.id) {+ TvHdmiTile(+ input = input,+ onClick = { onOpenInput(input.id) },+ modifier = Modifier.weight(1f),+ )+ }+ }+ TvGlassTile(+ label = "Settings",+ onClick = onOpenSettings,+ modifier = Modifier.weight(1f),+ ) {+ IconSettings(modifier = Modifier.size(44.dp), tint = Color.White)+ }+ TvGlassTile(+ label = "Add app",+ onClick = onOpenAddMenu,+ modifier = Modifier.weight(1f),+ ) {+ IconAdd(modifier = Modifier.size(44.dp), tint = Color.White)+ }+ // Keep the row's rhythm when fewer than PER_ROW tiles show: spacers hold the width so+ // the grid above and this row stay aligned (tv-detox always lays out a full row).+ val shown = (if (state.showPlayStore) 1 else 0) + state.hdmiInputs.size + 2+ repeat((TvRowOrder.PER_ROW - shown).coerceAtLeast(0)) {+ Box(modifier = Modifier.weight(1f))+ }+ }+}++@Composable+private fun TvHdmiTile(+ input: TvHdmiInput,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+) {+ TvGlassTile(+ label = input.label,+ onClick = onClick,+ modifier = modifier,+ ) {+ IconHdmi(modifier = Modifier.size(44.dp), tint = Color.White)+ }+}++@Composable+private fun TvGlassTile(+ label: String,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ icon: @Composable () -> Unit,+) {+ var focused by remember { mutableStateOf(false) }+ val scale = animatedFloat(if (focused) 1.1f else 1f)+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = modifier+ .aspectRatio(16f / 9f)+ .scale(scale)+ .clip(MaterialTheme.shapes.largeIncreased)+ .background(Color(0x13FFFFFF))+ .border(+ width = 2.dp,+ color = if (focused) Color(0x38FFFFFF) else Color(0x17FFFFFF),+ shape = MaterialTheme.shapes.largeIncreased,+ )+ .onFocusChanged { focused = it.isFocused }+ .focusable()+ .clickable(onClick = onClick)+ .padding(16.dp),+ verticalArrangement = Arrangement.Center,+ ) {+ Box(contentAlignment = Alignment.Center) { icon() }+ Text(+ text = label,+ style = MaterialTheme.typography.labelLarge,+ color = Color(0xE0FFFFFF),+ textAlign = TextAlign.Center,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = 12.dp),+ )+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvClockHeader.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvClockHeader.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvClockHeader.ktnew file mode 100644index 0000000000..1ced87e63c--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvClockHeader.kt@@ -0,0 +1,113 @@+package com.vayunmathur.tvlauncher.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.DateString+import com.vayunmathur.library.ui.IconWifiFull+import com.vayunmathur.library.ui.IconWifiOff+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberClock+import com.vayunmathur.library.ui.rememberIs24Hour+import com.vayunmathur.library.util.rememberIsOnline+import kotlin.time.Duration.Companion.seconds+import kotlin.time.Instant+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime++/**+ * Top-left date + giant time, top-right network tile (the tv-detox header).+ *+ * The clock getter is invoked only inside the [Text] scopes that display it, so ticks+ * recompose just those labels (the `rememberClock` contract).+ */+@Composable+fun TvClockHeader(+ onOpenNetworkSettings: () -> Unit,+) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.Top,+ ) {+ Column {+ val clock = rememberClock(1.seconds)+ val is24Hour = rememberIs24Hour()+ Text(+ text = dateLabel(clock()),+ style = MaterialTheme.typography.titleLarge,+ color = Color(0xA8FFFFFF),+ )+ Text(+ text = timeLabel(clock(), is24Hour),+ fontSize = 176.sp,+ fontWeight = FontWeight.SemiBold,+ color = Color.White,+ lineHeight = 180.sp,+ )+ }+ Box(+ modifier = Modifier.padding(top = 12.dp),+ ) {+ TvNetworkTile(onOpenNetworkSettings = onOpenNetworkSettings)+ }+ }+}++/** "Saturday, 17 October" shape: weekday + locale-ordered month/day. */+private fun dateLabel(nowMillis: Long): String {+ val date = Instant.fromEpochMilliseconds(nowMillis)+ .toLocalDateTime(TimeZone.currentSystemDefault()).date+ val weekday = DateString.dateWeekdayNoYear(date).substringBefore(',')+ val monthDay = DateString.dateMonthDay(date)+ return "$weekday, $monthDay"+}++/** Giant digits only, like the reference — a 12h AM/PM marker would double the width. */+private fun timeLabel(nowMillis: Long, is24Hour: Boolean): String {+ val time = Instant.fromEpochMilliseconds(nowMillis)+ .toLocalDateTime(TimeZone.currentSystemDefault()).time+ return DateString.timeNumeric(time, is24Hour)+}++/** Live network tile: Wi-Fi or offline, opening network settings on click. */+@Composable+private fun TvNetworkTile(+ onOpenNetworkSettings: () -> Unit,+) {+ val online by rememberIsOnline()+ Box(+ modifier = Modifier+ .size(72.dp)+ .focusable()+ .clickable(onClick = onOpenNetworkSettings),+ contentAlignment = Alignment.Center,+ ) {+ if (online) {+ IconWifiFull(+ modifier = Modifier.size(40.dp),+ tint = Color.White,+ )+ } else {+ IconWifiOff(+ modifier = Modifier.size(40.dp),+ tint = Color(0xA8FFFFFF),+ )+ }+ }+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvEditMenu.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvEditMenu.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvEditMenu.ktnew file mode 100644index 0000000000..85624d535a--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvEditMenu.kt@@ -0,0 +1,123 @@+package com.vayunmathur.tvlauncher.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.tvlauncher.platform.TvHomeState++/**+ * Edit overlays: the per-tile menu (Move/Replace/Remove/Uninstall-or-App-info) and the+ * add-app picker. Both are dialogs over the grid, in the home screen's own glass look.+ *+ * Removing only takes the tile away: the app stays installed and can be added back (the+ * tv-detox contract).+ */+@Composable+fun TvEditMenu(+ state: TvHomeState,+ onDismiss: () -> Unit,+ onStartMove: (String) -> Unit,+ onReplace: () -> Unit,+ onRemove: () -> Unit,+ onUninstallOrInfo: () -> Unit,+ onPickAddCandidate: (String) -> Unit,+ onCloseAddMenu: () -> Unit,+) {+ val editing = state.editingKey+ if (editing != null) {+ val tile = state.rowApps.firstOrNull { it.packageName == editing }+ val uninstallLabel = if (tile?.userInstalled == true) "Uninstall" else "App info"+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(text = tile?.label ?: editing) },+ text = {+ Column {+ TvMenuRow(label = "Move", onClick = { onStartMove(editing) })+ TvMenuRow(label = "Replace", onClick = onReplace)+ TvMenuRow(label = "Remove from home", onClick = onRemove)+ TvMenuRow(label = uninstallLabel, onClick = onUninstallOrInfo)+ }+ },+ confirmButton = {+ TextButton(onClick = onDismiss) { Text(text = "Cancel") }+ },+ )+ }+ if (state.showAddMenu) {+ val title = if (state.addReplacesIndex >= 0) {+ val current = state.rowApps.getOrNull(state.addReplacesIndex)?.label ?: ""+ if (current.isNotBlank()) "Replace $current" else "Replace app"+ } else {+ "Add an app"+ }+ AlertDialog(+ onDismissRequest = onCloseAddMenu,+ title = { Text(text = title) },+ text = {+ if (state.addCandidates.isEmpty()) {+ Text(+ text = "Every app is already here",+ style = MaterialTheme.typography.bodyLarge,+ color = Color(0xE6FFFFFF),+ )+ } else {+ val firstFocus = remember { FocusRequester() }+ LazyColumn {+ items(state.addCandidates, key = { it.packageName }) { candidate ->+ TvMenuRow(+ label = candidate.label,+ onClick = { onPickAddCandidate(candidate.packageName) },+ modifier = if (candidate == state.addCandidates.first()) {+ Modifier.focusRequester(firstFocus)+ } else {+ Modifier+ },+ )+ }+ }+ LaunchedEffect(Unit) {+ runCatching { firstFocus.requestFocus() }+ }+ }+ },+ confirmButton = {+ TextButton(onClick = onCloseAddMenu) { Text(text = "Cancel") }+ },+ )+ }+}++@Composable+private fun TvMenuRow(+ label: String,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+) {+ Text(+ text = label,+ style = MaterialTheme.typography.bodyLarge,+ color = Color(0xE6FFFFFF),+ maxLines = 1,+ modifier = modifier+ .fillMaxWidth()+ .focusable()+ .clickable(onClick = onClick)+ .padding(vertical = 16.dp, horizontal = 8.dp),+ )+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomePage.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomePage.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomePage.ktnew file mode 100644index 0000000000..e9b43b4f58--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomePage.kt@@ -0,0 +1,46 @@+package com.vayunmathur.tvlauncher.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.tvlauncher.platform.TvHomeViewModel++/**+ * The stateful half of the TV home screen.+ *+ * Every `XxxPage` in this package does the same three things and nothing else: read the state+ * off the ViewModel, hand the stateless `XxxScreen` that state plus the actions, and wire+ * navigation (the :launcher HomePage split).+ */+@Composable+fun TvHomePage(viewModel: TvHomeViewModel) {+ val state by viewModel.home.collectAsState()+ val context = LocalContext.current++ TvHomeScreen(+ state = state,+ onOpenTile = viewModel::openTile,+ onOpenPlayStore = viewModel::openPlayStore,+ onOpenInput = viewModel::openInput,+ onOpenSettings = viewModel::openSettings,+ onOpenNetworkSettings = viewModel::openNetworkSettings,+ onOpenEditMenu = viewModel::openEditMenu,+ onCloseEditMenu = viewModel::closeEditMenu,+ onStartMove = viewModel::startMove,+ onFinishMove = viewModel::finishMove,+ onCancelMove = viewModel::cancelMove,+ onMoveKey = viewModel::moveKey,+ onRemoveTile = viewModel::removeTile,+ onOpenAddMenu = viewModel::openAddMenu,+ onPickAddCandidate = viewModel::pickAddCandidate,+ onUninstallOrInfo = viewModel::uninstallOrInfo,+ onRefreshHome = remember(viewModel, context) {+ { viewModel.refreshDefaultHome(context as android.app.Activity) }+ },+ onRequestHomeRole = remember(viewModel, context) {+ { viewModel.requestHomeRole(context as android.app.Activity) }+ },+ )+}
tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomeScreen.kt
diff --git a/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomeScreen.kt b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomeScreen.ktnew file mode 100644index 0000000000..8e0a2ef5cc--- /dev/null+++ b/tvlauncher/src/main/java/com/vayunmathur/tvlauncher/ui/TvHomeScreen.kt@@ -0,0 +1,126 @@+package com.vayunmathur.tvlauncher.ui++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.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import androidx.activity.compose.BackHandler+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++// RAW SCAFFOLD EXCEPTION: TV launcher fullscreen grid, no app bar.++/**+ * The TV home screen: clock header, app banner grid, bottom glass row, edit overlays.+ *+ * Paints its own warm gradient like the tv-detox reference — a TV home never shows the+ * wallpaper behind it, so this screen is opaque by design.+ */+@Composable+fun TvHomeScreen(+ state: com.vayunmathur.tvlauncher.platform.TvHomeState,+ onOpenTile: (String) -> Unit,+ onOpenPlayStore: () -> Unit,+ onOpenInput: (String) -> Unit,+ onOpenSettings: () -> Unit,+ onOpenNetworkSettings: () -> Unit,+ onOpenEditMenu: (String) -> Unit,+ onCloseEditMenu: () -> Unit,+ onStartMove: (String) -> Unit,+ onFinishMove: () -> Unit,+ onCancelMove: () -> Unit,+ onMoveKey: (String, Int) -> Unit,+ onRemoveTile: (String) -> Unit,+ onOpenAddMenu: (Int) -> Unit,+ onPickAddCandidate: (String) -> Unit,+ onUninstallOrInfo: (String) -> Unit,+ onRefreshHome: () -> Unit,+ onRequestHomeRole: () -> Unit,+) {+ Box(+ modifier = Modifier+ .fillMaxSize()+ .background(TvHomeBackground),+ ) {+ // A home screen has nothing to go back to: Back closes overlays, or exits move mode+ // without persisting, and is otherwise a no-op (the tv-detox precedent).+ BackHandler(enabled = state.editingKey != null) { onCloseEditMenu() }+ BackHandler(enabled = state.editingKey == null && state.movingKey != null) {+ onCancelMove()+ }+ Column(+ modifier = Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 96.dp, vertical = 64.dp),+ verticalArrangement = Arrangement.spacedBy(48.dp),+ ) {+ TvClockHeader(+ onOpenNetworkSettings = onOpenNetworkSettings,+ )+ TvAppGrid(+ state = state,+ onOpenTile = onOpenTile,+ onOpenEditMenu = onOpenEditMenu,+ onMoveKey = onMoveKey,+ onFinishMove = onFinishMove,+ )+ if (state.movingKey != null) {+ Text(+ text = "Use the arrows to move it, then press OK",+ style = MaterialTheme.typography.labelLarge,+ color = Color(0xA8FFFFFF),+ modifier = Modifier.fillMaxWidth(),+ )+ }+ if (!state.loading) {+ TvBottomRow(+ state = state,+ onOpenPlayStore = onOpenPlayStore,+ onOpenInput = onOpenInput,+ onOpenSettings = onOpenSettings,+ onOpenAddMenu = { onOpenAddMenu(-1) },+ )+ }+ if (!state.isDefaultHome && !state.loading) {+ TextButton(onClick = onRequestHomeRole) {+ Text(+ text = "Set as default home screen",+ style = MaterialTheme.typography.labelLarge,+ color = Color(0xA8FFFFFF),+ )+ }+ }+ }+ TvEditMenu(+ state = state,+ onDismiss = onCloseEditMenu,+ onStartMove = onStartMove,+ onReplace = { onOpenAddMenu(state.rowApps.indexOfFirst { it.packageName == state.editingKey }) },+ onRemove = { state.editingKey?.let(onRemoveTile) },+ onUninstallOrInfo = { state.editingKey?.let(onUninstallOrInfo) },+ onPickAddCandidate = onPickAddCandidate,+ onCloseAddMenu = onCloseEditMenu,+ )+ }+}++/** Static warm gradient drawn once by the background: no extra view, no animation. */+private val TvHomeBackground = Brush.verticalGradient(+ colors = listOf(+ Color(0xFF15100F),+ Color(0xFF0A0809),+ Color(0xFF050405),+ ),+)
tvlauncher/src/main/res/drawable/banner.xml
diff --git a/tvlauncher/src/main/res/drawable/banner.xml b/tvlauncher/src/main/res/drawable/banner.xmlnew file mode 100644index 0000000000..d7623aced0--- /dev/null+++ b/tvlauncher/src/main/res/drawable/banner.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Leanback-row banner (160x90), following the cast:tv banner pattern. The home grid itself+ draws banner art per app at runtime; this is the static icon other launchers show for us. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="160dp"+ android:height="90dp"+ android:viewportWidth="160"+ android:viewportHeight="90">+ <path+ android:fillColor="#FF15100F"+ android:pathData="M0,0h160v90H0z" />+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M62,30h36v10H62zM62,44h36v6H62zM62,54h24v6H62z" />+</vector>
tvlauncher/src/main/res/values/strings.xml
diff --git a/tvlauncher/src/main/res/values/strings.xml b/tvlauncher/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..a25c4ef615--- /dev/null+++ b/tvlauncher/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">TV Launcher</string>+</resources>
tvlauncher/src/main/res/xml/data_extraction_rules.xml
diff --git a/tvlauncher/src/main/res/xml/data_extraction_rules.xml b/tvlauncher/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..81a97e0f26--- /dev/null+++ b/tvlauncher/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="utf-8"?>+<data-extraction-rules>+ <cloud-backup>+ <include domain="root" path="." />+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" path="." />+ </cloud-backup>+ <device-transfer>+ <include domain="root" path="." />+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" path="." />+ </device-transfer>+</data-extraction-rules>
tvlauncher/src/test/java/com/vayunmathur/tvlauncher/domain/TvRowOrderTest.kt
diff --git a/tvlauncher/src/test/java/com/vayunmathur/tvlauncher/domain/TvRowOrderTest.kt b/tvlauncher/src/test/java/com/vayunmathur/tvlauncher/domain/TvRowOrderTest.ktnew file mode 100644index 0000000000..37b5449fd7--- /dev/null+++ b/tvlauncher/src/test/java/com/vayunmathur/tvlauncher/domain/TvRowOrderTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.tvlauncher.domain++import kotlin.test.Test+import kotlin.test.assertEquals++class TvRowOrderTest {+ private val installed = listOf(+ "com.google.android.youtube.tv",+ "com.netflix.ninja",+ "com.example.game",+ "com.example.other",+ )++ @Test+ fun savedOrderWinsVerbatimMinusMissing() {+ val saved = listOf("com.netflix.ninja", "com.gone.app", "com.example.game")+ assertEquals(+ listOf("com.netflix.ninja", "com.example.game"),+ TvRowOrder.mergeOrder(saved, installed),+ )+ }++ @Test+ fun noSavedOrderTopsUpDefaultsWithInstalled() {+ assertEquals(+ listOf(+ "com.google.android.youtube.tv",+ "com.netflix.ninja",+ "com.example.game",+ "com.example.other",+ ),+ TvRowOrder.mergeOrder(+ saved = null,+ installed = installed,+ defaults = listOf("com.google.android.youtube.tv", "com.netflix.ninja"),+ ),+ )+ }++ @Test+ fun topUpStopsAtOneFullRow() {+ val many = (1..10).map { "com.example.app$it" } + installed+ val row = TvRowOrder.mergeOrder(null, many, defaults = emptyList())+ assertEquals(TvRowOrder.PER_ROW, row.size)+ }++ @Test+ fun moveSlidesEntry() {+ val order = listOf("a", "b", "c", "d")+ assertEquals(listOf("b", "c", "a", "d"), TvRowOrder.move(order, 0, 2))+ assertEquals(listOf("d", "a", "b", "c"), TvRowOrder.move(order, 3, 0))+ assertEquals(order, TvRowOrder.move(order, 1, 1))+ assertEquals(order, TvRowOrder.move(order, 9, 0))+ }++ @Test+ fun replaceSwapsWithoutDuplicating() {+ val order = listOf("a", "b", "c")+ assertEquals(listOf("a", "x", "c"), TvRowOrder.replaceAt(order, 1, "x"))+ // Replacing with a package already on the row moves it rather than duplicating.+ assertEquals(listOf("b", "a"), TvRowOrder.replaceAt(order.take(2), 5, "a"))+ assertEquals(order, TvRowOrder.replaceAt(order, 1, ""))+ }++ @Test+ fun hdmiSlotsLeaveRoomForStoreSettingsAdd() {+ assertEquals(3, TvRowOrder.maxHdmiSlots(hasStore = true))+ assertEquals(4, TvRowOrder.maxHdmiSlots(hasStore = false))+ }+}
tvlauncher/undo-tv.sh
diff --git a/tvlauncher/undo-tv.sh b/tvlauncher/undo-tv.shnew file mode 100644index 0000000000..d54b9c456a--- /dev/null+++ b/tvlauncher/undo-tv.sh@@ -0,0 +1,63 @@+#!/bin/sh+# Removes TV Launcher and turns your TV's own home screen back on.+# Usage: sh undo-tv.sh <TV_IP>+set -e+[ -n "$1" ] || { echo "Usage: sh undo-tv.sh <TV_IP>" >&2; exit 1; }+case "$1" in+ *.*.*.*:*) TV=$1 ;;+ *.*.*.*) TV=$1:5555 ;;+ *) TV=$1 ;;+esac+case "$TV" in *:*) adb connect "$TV" >/dev/null || true ;; esac+[ "$(adb -s "$TV" get-state 2>/dev/null)" = device ] || { echo "Can't reach $TV." >&2; exit 1; }++failed=+# 0: the app is off. 1: it's on or not installed. 2: the TV couldn't be asked.+is_off() {+ out=$(adb -s "$TV" shell pm list packages -d "$1") || return 2+ out=$(printf '%s\n' "$out" | tr -d '\r' | grep -v '^$') || return 1+ # Anything but package lines is an error message, even if pm said it worked.+ printf '%s\n' "$out" | grep -qv '^package:' && return 2+ printf '%s\n' "$out" | grep -Fqx "package:$1" && return 0+ return 1+}+# Turns an app back on and checks it worked. An app that's no longer installed counts as done.+turn_on() {+ adb -s "$TV" shell pm enable "$1" >/dev/null 2>&1 || true+ rc=0; is_off "$1" || rc=$?+ case $rc in+ 1) echo "Turned $1 back on" ;;+ 0) echo "Couldn't turn $1 back on." >&2; failed=1 ;;+ *) echo "Couldn't check that $1 is back on." >&2; failed=1 ;;+ esac+}++# Turn back on whatever install-tv.sh turned off, before removing TV Launcher.+# END marks a full read; no list at all is fine.+LIST=/data/local/tmp/tvlauncher-disabled.txt+list=$(adb -s "$TV" shell "if [ -e $LIST ]; then cat $LIST && echo END; else echo END; fi" 2>/dev/null) || list=+list=$(printf '%s\n' "$list" | tr -d '\r')+case "$list" in+ *END) for p in $(printf '%s\n' "$list" | grep -vx END | sort -u); do turn_on "$p"; done ;;+ *) echo "Couldn't read the list of apps install-tv.sh turned off." >&2; failed=1 ;;+esac+# Google TV's setup app may have been turned off by hand (see install-tv.sh), so turn it+# back on too.+W=com.google.android.tungsten.setupwraith+rc=0; is_off "$W" || rc=$?+case $rc in+ 0) turn_on "$W" ;;+ 1) ;;+ *) echo "Couldn't check $W." >&2; failed=1 ;;+esac++# If something stayed off, keep TV Launcher and the list, so Home still works and+# undo-tv.sh can try again.+if [ -n "$failed" ]; then+ echo "Kept TV Launcher so your TV still has a home screen. Run undo-tv.sh again, or turn the app on with: adb shell pm enable <package>" >&2+ exit 1+fi+adb -s "$TV" shell rm -f "$LIST"+adb -s "$TV" uninstall com.vayunmathur.tvlauncher >/dev/null 2>&1 || true+adb -s "$TV" shell input keyevent KEYCODE_HOME+echo "Removed. Your TV is back to its own home screen."