Skip to content

Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.

Add the first-run, connect and device screens

jesse-agent-23296818bd32887
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 1aae7d4..012c89c 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -3,6 +3,7 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.roborazzi)
}
android {
@@ -64,6 +65,11 @@ android {
buildFeatures {
compose = true
}
+
+ testOptions {
+ // Robolectric renders the screenshot tests (see ScreenshotTest).
+ unitTests.isIncludeAndroidResources = true
+ }
}
dependencies {
@@ -72,10 +78,22 @@ dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.lifecycle.runtime.ktx)
+ implementation(libs.androidx.lifecycle.runtime.compose)
+ implementation(libs.androidx.lifecycle.viewmodel.compose)
+ implementation(libs.kotlinx.coroutines.core)
implementation(platform(libs.compose.bom))
implementation(libs.compose.ui)
implementation(libs.compose.ui.tooling.preview)
implementation(libs.compose.material3)
+ implementation(libs.compose.icons)
debugImplementation(libs.compose.ui.tooling)
+ debugImplementation(libs.compose.ui.test.manifest)
+
+ testImplementation(platform(libs.compose.bom))
+ testImplementation(libs.compose.ui.test.junit4)
+ testImplementation(libs.junit)
+ testImplementation(libs.robolectric)
+ testImplementation(libs.roborazzi)
+ testImplementation(libs.roborazzi.compose)
}
diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.kt
index 450b29a..696bdf3 100644
--- a/app/src/main/java/app/tellyscope/MainActivity.kt
+++ b/app/src/main/java/app/tellyscope/MainActivity.kt
@@ -4,61 +4,101 @@ package app.tellyscope
import android.os.Bundle
import androidx.activity.ComponentActivity
+import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.foundation.layout.padding
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Scaffold
-import androidx.compose.material3.Text
+import androidx.compose.material3.SnackbarDuration
+import androidx.compose.material3.SnackbarHostState
+import androidx.compose.material3.SnackbarResult
import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.tooling.preview.Preview
-import androidx.compose.ui.unit.dp
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import app.tellyscope.data.FakeDeviceSource
+import app.tellyscope.ui.Copy
+import app.tellyscope.ui.DeviceActions
+import app.tellyscope.ui.DeviceScreen
+import app.tellyscope.ui.ScanScreen
+import app.tellyscope.ui.TellyscopeViewModel
import app.tellyscope.ui.theme.TellyscopeTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
+ // Until the :adb module lands, the app runs on the fake source. Launch with
+ // `--es scenario empty|noallow` to see the guide or the timeout.
+ val scenario = when (intent.getStringExtra("scenario")) {
+ "empty" -> FakeDeviceSource.Scenario.Empty
+ "noallow" -> FakeDeviceSource.Scenario.NoAllow
+ else -> FakeDeviceSource.Scenario.Normal
+ }
setContent {
TellyscopeTheme {
- HomeScreen()
+ val vm: TellyscopeViewModel = viewModel(
+ factory = viewModelFactory { initializer { TellyscopeViewModel(FakeDeviceSource(scenario)) } },
+ )
+ TellyscopeApp(vm)
}
}
}
}
@Composable
-fun HomeScreen() {
- Scaffold { padding ->
- Column(
- modifier = Modifier
- .fillMaxSize()
- .padding(padding)
- .padding(24.dp),
- verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically),
- horizontalAlignment = Alignment.CenterHorizontally,
- ) {
- Text(
- text = stringResource(R.string.app_name),
- style = MaterialTheme.typography.displaySmall,
- )
- Text(
- text = stringResource(R.string.home_status),
- style = MaterialTheme.typography.bodyLarge,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
- }
+fun TellyscopeApp(vm: TellyscopeViewModel) {
+ val state by vm.state.collectAsStateWithLifecycle()
+ val done by vm.done.collectAsStateWithLifecycle()
+ val snackbar = remember { SnackbarHostState() }
+ var adding by rememberSaveable { mutableStateOf(false) }
+
+ LaunchedEffect(done) {
+ val entry = done ?: return@LaunchedEffect
+ vm.doneShown()
+ val result = snackbar.showSnackbar(
+ message = Copy.done(entry.action, entry.label),
+ actionLabel = entry.undo?.let(Copy::undo),
+ duration = SnackbarDuration.Long,
+ )
+ if (result == SnackbarResult.ActionPerformed) vm.undo(entry)
}
-}
-@Preview(showBackground = true)
-@Composable
-private fun HomeScreenPreview() {
- TellyscopeTheme { HomeScreen() }
+ // A newly connected TV becomes the selection; leave the add flow then, not on tap.
+ LaunchedEffect(state.selectedId) { adding = false }
+
+ if (state.selected == null || adding) {
+ BackHandler(enabled = adding) { adding = false }
+ ScanScreen(
+ scan = state.scan,
+ now = state.now,
+ onRescan = vm::rescan,
+ onConnect = vm::connect,
+ onCode = vm::codeChanged,
+ onPair = vm::pair,
+ onAddByIp = vm::addByIp,
+ onBack = if (adding) ({ adding = false }) else null,
+ )
+ } else {
+ DeviceScreen(
+ state = state,
+ snackbar = snackbar,
+ actions = DeviceActions(
+ select = vm::select,
+ addDevice = { adding = true; vm.rescan() },
+ showOffline = vm::showOffline,
+ query = vm::query,
+ propose = vm::propose,
+ confirm = vm::confirm,
+ cancel = vm::cancel,
+ undo = vm::undo,
+ reconnect = { state.selectedId?.let(vm::select) },
+ ),
+ )
+ }
}
diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
new file mode 100644
index 0000000..409b70e
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.data
+
+import kotlinx.coroutines.flow.Flow
+
+/**
+ * Everything the screens need from a TV. The UI only talks to this; an
+ * adapter over the `:adb` module implements it for real devices, and
+ * [FakeDeviceSource] stands in for screenshots and until that lands. Refresh tiers follow the slice-1 data list:
+ * fast 2 s ([live]), medium 10 s ([network]), slow / on open ([apps]).
+ */
+interface DeviceSource {
+ /** LAN sweep for 5555 plus mDNS for wireless debugging. Emits hits as they answer, then [ScanEvent.Done]. */
+ fun scan(): Flow<ScanEvent>
+
+ /** Classic connect. Suspends while the TV shows the Allow prompt; the caller owns the timeout. */
+ suspend fun connect(hit: ScanHit): ConnectResult
+
+ /** Wireless-debugging pairing with the 6-digit code shown on the TV, then connect. */
+ suspend fun pair(hit: ScanHit, code: String): ConnectResult
+
+ /** Previously paired devices, including offline ones. */
+ suspend fun known(): List<Device>
+
+ /** Fast-tier stats. Completes when the device goes offline. */
+ fun live(deviceId: String): Flow<Snapshot>
+
+ suspend fun apps(deviceId: String): List<AppInfo>
+
+ suspend fun network(deviceId: String): NetworkInfo
+
+ /** Runs an action. Never uninstalls: there is no uninstall in [Action] on purpose. */
+ suspend fun act(deviceId: String, action: Action, packageName: String): HistoryEntry
+}
diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt
new file mode 100644
index 0000000..dd3a777
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt
@@ -0,0 +1,202 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.data
+
+import kotlin.random.Random
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.isActive
+
+/**
+ * Stand-in [DeviceSource] for building the screens before the ADB module exists.
+ * [Scenario] switches between the flows worth looking at.
+ */
+class FakeDeviceSource(
+ private val scenario: Scenario = Scenario.Normal,
+ private val clock: () -> Long = System::currentTimeMillis,
+ private val random: Random = Random.Default,
+) : DeviceSource {
+
+ enum class Scenario {
+ Normal,
+ /** Scan finds nothing: the brand guide. */
+ Empty,
+ /** The TV never answers the Allow prompt. */
+ NoAllow,
+ }
+
+ private val hits = listOf(
+ ScanHit("192.168.1.23", 5555, ScanKind.Classic, "xgimi-projector", "XGIMI"),
+ ScanHit("192.168.1.41", 5555, ScanKind.Classic, "android-7f3a", "Amlogic"),
+ ScanHit("192.168.1.57", 37211, ScanKind.Wireless, "chromecast", "Google"),
+ ScanHit("192.168.1.88", 5555, ScanKind.Classic, null, null),
+ )
+
+ private val models = mapOf(
+ "XGIMI" to Triple("XGIMI Horizon Pro", "XGIMI", "11"),
+ "Amlogic" to Triple("X96 Max", "Amlogic", "9"),
+ "Google" to Triple("Chromecast with Google TV", "Google", "12"),
+ )
+
+ private val apps = mutableMapOf<String, MutableList<AppInfo>>()
+ private var nextHistoryId = 1L
+
+ override fun scan(): Flow<ScanEvent> = flow {
+ val subnet = "192.168.1.0/24"
+ val pending = if (scenario == Scenario.Empty) ArrayDeque() else ArrayDeque(hits)
+ var probed = 0
+ while (probed < 254) {
+ delay(120)
+ probed = minOf(254, probed + 23)
+ emit(ScanEvent.Progress(ScanProgress(probed, 254, subnet)))
+ if (pending.isNotEmpty() && random.nextFloat() < 0.45f) emit(ScanEvent.Found(pending.removeFirst()))
+ }
+ pending.forEach { emit(ScanEvent.Found(it)) }
+ emit(ScanEvent.Done)
+ }
+
+ override suspend fun connect(hit: ScanHit): ConnectResult {
+ if (scenario == Scenario.NoAllow) {
+ delay(Long.MAX_VALUE)
+ }
+ if (hit.kind == ScanKind.Wireless) {
+ delay(300)
+ return ConnectResult.NeedsPairing
+ }
+ delay(3_200) // the user finding the remote and pressing Allow
+ return ConnectResult.Online(device(hit))
+ }
+
+ override suspend fun pair(hit: ScanHit, code: String): ConnectResult {
+ delay(800)
+ if (!code.matches(Regex("\\d{6}"))) {
+ return ConnectResult.WrongCode("that code didn't work. codes change each time the box opens; check the tv and try again.")
+ }
+ return ConnectResult.Online(device(hit))
+ }
+
+ override suspend fun known(): List<Device> = listOf(
+ Device(
+ id = "192.168.1.64",
+ hit = ScanHit("192.168.1.64", 5555, ScanKind.Classic, "bedroom-firetv", "Amazon"),
+ state = DeviceState.Offline,
+ model = "Fire TV Stick 4K",
+ manufacturer = "Amazon",
+ android = "9",
+ lastSeen = clock() - 14 * 60_000,
+ ),
+ )
+
+ private fun device(hit: ScanHit): Device {
+ val (model, maker, android) = models[hit.maker] ?: Triple("Android TV box", hit.maker, "10")
+ return Device(hit.ip, hit, DeviceState.Online, model, maker, android, clock())
+ }
+
+ override fun live(deviceId: String): Flow<Snapshot> = flow {
+ while (currentCoroutineContext().isActive) {
+ emit(snapshot(deviceId))
+ delay(2_000)
+ }
+ }
+
+ fun snapshot(deviceId: String): Snapshot {
+ val enabled = appsFor(deviceId).filter { it.enabled }.map { it.packageName }.toSet()
+ val procs = baseProcs
+ .filter { it.packageName == null || it.packageName in enabled }
+ .map {
+ it.copy(
+ cpuPercent = (it.cpuPercent + (random.nextDouble() - 0.5) * 3).coerceAtLeast(0.0),
+ ramMb = (it.ramMb * (0.97 + random.nextDouble() * 0.06)).toInt(),
+ )
+ }
+ return Snapshot(
+ at = clock(),
+ cpuPercent = procs.sumOf { it.cpuPercent }.toInt(),
+ ramUsedMb = procs.sumOf { it.ramMb } + 260,
+ ramTotalMb = 2048,
+ storageUsedGb = 9.8,
+ storageTotalGb = 16.0,
+ tempC = 52 + random.nextInt(-1, 2),
+ uptimeSeconds = 3 * 86_400L + 4 * 3_600L,
+ screenOn = true,
+ procs = procs,
+ )
+ }
+
+ override suspend fun apps(deviceId: String): List<AppInfo> = appsFor(deviceId).toList()
+
+ private fun appsFor(deviceId: String) = apps.getOrPut(deviceId) { baseApps.toMutableList() }
+
+ override suspend fun network(deviceId: String) = NetworkInfo(
+ iface = "wifi",
+ ip = deviceId,
+ mac = "58:d5:0a:3c:91:e2",
+ ssid = "home-5g",
+ rssi = -54 + random.nextInt(-3, 4),
+ linkMbps = 433,
+ sockets = listOf(
+ Socket("YouTube", "youtube.com:443", "established"),
+ Socket("Jellyfin", "192.168.1.10:8096", "established"),
+ Socket("Google Play services", "googleapis.com:443", "established"),
+ Socket("XGIMI Assistant", "xgimi.com:443", "closing"),
+ ),
+ traffic = listOf(
+ AppTraffic("YouTube", 1840, 22),
+ AppTraffic("Jellyfin", 960, 4),
+ AppTraffic("Netflix", 410, 6),
+ AppTraffic("Google Play services", 120, 31),
+ AppTraffic("XGIMI Updates", 64, 1),
+ ),
+ )
+
+ override suspend fun act(deviceId: String, action: Action, packageName: String): HistoryEntry {
+ delay(400)
+ val list = appsFor(deviceId)
+ val i = list.indexOfFirst { it.packageName == packageName }
+ val app = list[i]
+ when (action) {
+ Action.Disable -> list[i] = app.copy(enabled = false)
+ Action.Enable -> list[i] = app.copy(enabled = true)
+ Action.Stop, Action.Open -> Unit
+ }
+ val undo = when (action) {
+ Action.Stop -> Action.Open
+ Action.Disable -> Action.Enable
+ Action.Enable -> Action.Disable
+ Action.Open -> null
+ }
+ return HistoryEntry(nextHistoryId++, deviceId, clock(), action, packageName, app.label, undo, null)
+ }
+
+ private companion object {
+ val baseApps = listOf(
+ AppInfo("com.spocky.projengmenu", "Projectivy Launcher", 0xFF3D5AFE, false, true, "this is your home screen", "4.52"),
+ AppInfo("com.google.android.youtube.tv", "YouTube", 0xFFC4302B, false, true, null, "4.40.303"),
+ AppInfo("com.netflix.ninja", "Netflix", 0xFFB20710, false, true, null, "11.2.0"),
+ AppInfo("org.jellyfin.androidtv", "Jellyfin", 0xFF7B5EA7, false, true, null, "0.17.4"),
+ AppInfo("com.xgimi.assistant", "XGIMI Assistant", null, true, true, null, "2.1.8"),
+ AppInfo("com.xgimi.ota", "XGIMI Updates", null, true, true, null, "1.4.0"),
+ AppInfo("com.google.android.tvrecommendations", "TV Recommendations", null, true, false, null, "1.0"),
+ AppInfo("com.android.systemui", "System UI", null, true, true, "the tv needs this to draw the screen", "11"),
+ AppInfo("com.android.tv.settings", "Settings", null, true, true, "you need this to change tv settings", "11"),
+ AppInfo("com.google.android.gms", "Google Play services", null, true, true, "most apps stop working without it", "24.38"),
+ AppInfo("com.google.android.inputmethod.latin", "Gboard", null, true, true, "you'd lose the on-screen keyboard", "14.1"),
+ )
+
+ val baseProcs = listOf(
+ Proc(412, "surfaceflinger", null, 9.0, 38),
+ Proc(688, "system_server", null, 6.0, 214),
+ Proc(1502, "com.spocky.projengmenu", "com.spocky.projengmenu", 2.0, 312),
+ Proc(2210, "com.google.android.youtube.tv", "com.google.android.youtube.tv", 4.0, 220),
+ Proc(2241, "com.google.android.youtube.tv:service", "com.google.android.youtube.tv", 1.0, 41),
+ Proc(1980, "com.google.android.gms.persistent", "com.google.android.gms", 1.0, 118),
+ Proc(2077, "com.xgimi.assistant", "com.xgimi.assistant", 1.0, 96),
+ Proc(2301, "org.jellyfin.androidtv", "org.jellyfin.androidtv", 0.5, 88),
+ Proc(1440, "com.android.systemui", "com.android.systemui", 1.0, 102),
+ Proc(530, "media.codec", null, 2.0, 22),
+ Proc(2390, "com.xgimi.ota", "com.xgimi.ota", 0.0, 31),
+ )
+ }
+}
diff --git a/app/src/main/java/app/tellyscope/data/Model.kt b/app/src/main/java/app/tellyscope/data/Model.kt
new file mode 100644
index 0000000..b9c53f1
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/data/Model.kt
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.data
+
+/** How a TV was found: legacy network ADB on 5555, or Android 11+ wireless debugging (TLS + pairing code). */
+enum class ScanKind { Classic, Wireless }
+
+data class ScanHit(
+ val ip: String,
+ val port: Int,
+ val kind: ScanKind,
+ /** mDNS name, else reverse DNS, else null. */
+ val hostname: String?,
+ /** From the MAC's OUI; null when the MAC is randomised. */
+ val maker: String?,
+)
+
+data class ScanProgress(val probed: Int, val total: Int, val subnet: String)
+
+sealed interface ScanEvent {
+ data class Found(val hit: ScanHit) : ScanEvent
+ data class Progress(val progress: ScanProgress) : ScanEvent
+ data object Done : ScanEvent
+}
+
+/**
+ * ADB reports `unauthorized` both before the user answers and after they press
+ * Deny, so there is no "denied" state: [NotAllowed] means "unauthorized past the
+ * timeout", and only on a first connect. A TV that was online before and stalls
+ * stays [Offline] and keeps retrying. [NeedsPairing] is a wireless-debugging TV
+ * that doesn't know our key yet: show the 6-digit code field.
+ */
+enum class DeviceState { Found, Waiting, NeedsPairing, Online, Offline, NotAllowed }
+
+data class Device(
+ val id: String,
+ val hit: ScanHit,
+ val state: DeviceState,
+ val model: String?,
+ val manufacturer: String?,
+ val android: String?,
+ /** Epoch millis of the last successful poll. */
+ val lastSeen: Long?,
+)
+
+sealed interface ConnectResult {
+ data class Online(val device: Device) : ConnectResult
+ data object NotAllowed : ConnectResult
+ /** Wireless-debugging TV that doesn't know our key; ask for the pairing code. */
+ data object NeedsPairing : ConnectResult
+ data class WrongCode(val message: String) : ConnectResult
+ data class Unreachable(val message: String) : ConnectResult
+}
+
+data class Proc(
+ val pid: Int,
+ val name: String,
+ /** Owning package; null for native daemons (shown as "android system"). */
+ val packageName: String?,
+ val cpuPercent: Double,
+ val ramMb: Int,
+)
+
+/** One poll of the fast tier. Null fields are stats the device doesn't report; the UI shows "—", never 0. */
+data class Snapshot(
+ val at: Long,
+ val cpuPercent: Int,
+ val ramUsedMb: Int,
+ val ramTotalMb: Int,
+ val storageUsedGb: Double?,
+ val storageTotalGb: Double?,
+ val tempC: Int?,
+ val uptimeSeconds: Long,
+ val screenOn: Boolean?,
+ val procs: List<Proc>,
+)
+
+data class AppInfo(
+ val packageName: String,
+ /** Human label from the APK. Never the package id; the source falls back to a humanised id. */
+ val label: String,
+ /** ARGB of the icon tile until real icons are wired; null = neutral tile. */
+ val iconColor: Long?,
+ val system: Boolean,
+ val enabled: Boolean,
+ /** Why this app can't be touched, in user words; null when actions are allowed. */
+ val protectedReason: String?,
+ val version: String,
+)
+
+data class Socket(val app: String, val remote: String, val state: String)
+data class AppTraffic(val app: String, val rxMb: Int, val txMb: Int)
+
+data class NetworkInfo(
+ val iface: String,
+ val ip: String,
+ val mac: String?,
+ val ssid: String?,
+ val rssi: Int?,
+ val linkMbps: Int?,
+ val sockets: List<Socket>,
+ val traffic: List<AppTraffic>,
+)
+
+enum class Action { Stop, Disable, Enable, Open }
+
+data class HistoryEntry(
+ val id: Long,
+ val deviceId: String,
+ val at: Long,
+ val action: Action,
+ val packageName: String,
+ val label: String,
+ /** What the undo button runs; null when there is nothing to undo. */
+ val undo: Action?,
+ val undoneAt: Long?,
+)
diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.kt
new file mode 100644
index 0000000..de6a8c0
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import app.tellyscope.data.Action
+
+/**
+ * Every user-facing sentence about actions and time lives here so wording is
+ * reviewed in one place: every button says what it does before it runs.
+ */
+object Copy {
+ fun button(action: Action) = when (action) {
+ Action.Stop -> "Stop"
+ Action.Disable -> "Disable"
+ Action.Enable -> "Turn on"
+ Action.Open -> "Open"
+ }
+
+ fun confirm(action: Action) = when (action) {
+ Action.Stop -> "Yes, stop it"
+ Action.Disable -> "Yes, disable it"
+ Action.Enable -> "Yes, turn it on"
+ Action.Open -> "Yes, open it"
+ }
+
+ fun explain(action: Action, app: String) = when (action) {
+ Action.Stop -> "Stops $app until you open it again."
+ Action.Disable -> "Hides $app and stops it running. Nothing is deleted; you can turn it back on here."
+ Action.Enable -> "Turns $app back on."
+ Action.Open -> "Opens $app on the TV."
+ }
+
+ fun done(action: Action, app: String) = when (action) {
+ Action.Stop -> "Stopped $app"
+ Action.Disable -> "Disabled $app"
+ Action.Enable -> "Turned on $app"
+ Action.Open -> "Opened $app"
+ }
+
+ /** Force-stop has no true undo; the button says what it actually does. */
+ fun undo(undo: Action) = if (undo == Action.Open) "Open again" else "Undo"
+
+ fun ago(at: Long, now: Long): String {
+ val s = ((now - at) / 1000).coerceAtLeast(0)
+ return when {
+ s < 10 -> "just now"
+ s < 60 -> "$s s ago"
+ s < 3600 -> "${s / 60} min ago"
+ s < 86_400 -> "${s / 3600} h ago"
+ else -> "${s / 86_400} d ago"
+ }
+ }
+
+ fun uptime(s: Long): String {
+ val d = s / 86_400
+ val h = (s % 86_400) / 3600
+ val m = (s % 3600) / 60
+ return when {
+ d > 0 -> "${d}d ${h}h"
+ h > 0 -> "${h}h ${m}m"
+ else -> "${m}m"
+ }
+ }
+
+ fun mb(v: Int) = if (v >= 1024) "%.1f GB".format(v / 1024.0) else "$v MB"
+
+ const val ANDROID_SYSTEM = "Android system"
+}
diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
new file mode 100644
index 0000000..8689c78
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
@@ -0,0 +1,525 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.animateContentSize
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+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.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxHeight
+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.LazyListScope
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Add
+import androidx.compose.material.icons.filled.ArrowDropDown
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.KeyboardArrowDown
+import androidx.compose.material.icons.filled.Search
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.Checkbox
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
+import androidx.compose.material3.FilledTonalButton
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.SnackbarHostState
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TextField
+import androidx.compose.material3.TextFieldDefaults
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import app.tellyscope.data.Action
+import app.tellyscope.data.AppInfo
+import app.tellyscope.data.Device
+import app.tellyscope.data.DeviceState
+import app.tellyscope.data.HistoryEntry
+import app.tellyscope.data.NetworkInfo
+import app.tellyscope.data.Proc
+import app.tellyscope.data.Snapshot
+import app.tellyscope.ui.theme.SmallNumber
+import app.tellyscope.ui.theme.StatNumber
+
+data class DeviceActions(
+ val select: (String) -> Unit = {},
+ val addDevice: () -> Unit = {},
+ val showOffline: (Boolean) -> Unit = {},
+ val query: (String) -> Unit = {},
+ val propose: (String, Action) -> Unit = { _, _ -> },
+ val confirm: () -> Unit = {},
+ val cancel: () -> Unit = {},
+ val undo: (HistoryEntry) -> Unit = {},
+ val reconnect: () -> Unit = {},
+)
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun DeviceScreen(
+ state: UiState,
+ actions: DeviceActions,
+ snackbar: SnackbarHostState = remember { SnackbarHostState() },
+) {
+ val device = state.selected ?: return
+ val ui = state.device
+ var searching by rememberSaveable { mutableStateOf(false) }
+ val q = state.query.trim().lowercase()
+ val offline = device.state != DeviceState.Online
+
+ Scaffold(
+ snackbarHost = { SnackbarHost(snackbar) },
+ topBar = {
+ if (searching) {
+ TopAppBar(
+ title = {
+ TextField(
+ value = state.query,
+ onValueChange = actions.query,
+ placeholder = { Text("Search apps, processes, connections") },
+ singleLine = true,
+ colors = TextFieldDefaults.colors(
+ focusedContainerColor = Color.Transparent,
+ unfocusedContainerColor = Color.Transparent,
+ ),
+ modifier = Modifier.fillMaxWidth(),
+ )
+ },
+ actions = {
+ IconButton(onClick = { searching = false; actions.query("") }) {
+ Icon(Icons.Default.Close, contentDescription = "Close search")
+ }
+ },
+ )
+ } else {
+ TopAppBar(
+ title = { DevicePicker(state, actions) },
+ actions = {
+ IconButton(onClick = { searching = true }, enabled = !offline) {
+ Icon(Icons.Default.Search, contentDescription = "Search")
+ }
+ },
+ )
+ }
+ },
+ ) { pad ->
+ LazyColumn(
+ Modifier.fillMaxSize().padding(pad),
+ contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ item {
+ Text(
+ listOfNotNull(device.model, device.android?.let { "Android $it" }, device.hit.ip).joinToString(" · "),
+ style = SmallNumber,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ if (offline) item { OfflineCard(device, state.now, actions.reconnect) }
+ item { StatGrid(ui.snapshot, Modifier.alpha(if (offline) 0.4f else 1f)) }
+ ui.snapshot?.let { snap ->
+ if (q.isEmpty()) item { UsageCard(snap, ui.apps) }
+ }
+ section(
+ key = "apps",
+ title = "Apps",
+ count = ui.apps.size,
+ expandedByDefault = true,
+ forceOpen = q.isNotEmpty(),
+ ) {
+ val apps = ui.apps
+ .filter { q.isEmpty() || it.label.lowercase().contains(q) || it.packageName.contains(q) }
+ .sortedWith(compareBy({ it.protectedReason != null }, { !it.enabled }, { it.system }, { it.label }))
+ if (apps.isEmpty()) EmptyLine(q)
+ apps.forEach { app ->
+ AppRow(app, ui.snapshot?.procs.orEmpty(), ui.pending, ui.busy == app.packageName, actions)
+ }
+ }
+ section("procs", "Processes", ui.snapshot?.procs?.size ?: 0, forceOpen = q.isNotEmpty()) {
+ ProcessTable(ui.snapshot?.procs.orEmpty(), ui.apps, q)
+ }
+ section("net", "Network", ui.network?.sockets?.size ?: 0, forceOpen = q.isNotEmpty()) {
+ ui.network?.let { NetworkBlock(it, q) }
+ }
+ section("history", "History", ui.history.size) {
+ HistoryList(ui.history, state.now, actions.undo)
+ }
+ }
+ }
+}
+
+@Composable
+private fun DevicePicker(state: UiState, actions: DeviceActions) {
+ var open by remember { mutableStateOf(false) }
+ val device = state.selected ?: return
+ val offlineCount = state.devices.count { it.state != DeviceState.Online }
+ Box {
+ Row(
+ Modifier.clip(MaterialTheme.shapes.large).clickable { open = true }.padding(horizontal = 8.dp, vertical = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ StateDot(device.state)
+ Spacer(Modifier.width(8.dp))
+ Text(device.hit.hostname ?: device.model ?: device.hit.ip, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Icon(Icons.Default.ArrowDropDown, contentDescription = "Switch TV")
+ }
+ DropdownMenu(open, onDismissRequest = { open = false }) {
+ state.devices
+ .filter { state.showOffline || it.state == DeviceState.Online || it.id == state.selectedId }
+ .forEach { d ->
+ DropdownMenuItem(
+ text = { Text(d.hit.hostname ?: d.model ?: d.hit.ip) },
+ leadingIcon = { StateDot(d.state) },
+ trailingIcon = {
+ if (d.state != DeviceState.Online) Text(
+ d.lastSeen?.let { "seen ${Copy.ago(it, state.now)}" } ?: "offline",
+ style = MaterialTheme.typography.labelSmall,
+ )
+ },
+ onClick = { open = false; actions.select(d.id) },
+ )
+ }
+ HorizontalDivider()
+ DropdownMenuItem(
+ text = { Text("Show offline ($offlineCount)") },
+ leadingIcon = { Checkbox(state.showOffline, onCheckedChange = null) },
+ onClick = { actions.showOffline(!state.showOffline) },
+ )
+ DropdownMenuItem(
+ text = { Text("Add a TV") },
+ leadingIcon = { Icon(Icons.Default.Add, null) },
+ onClick = { open = false; actions.addDevice() },
+ )
+ }
+ }
+}
+
+@Composable
+private fun StateDot(state: DeviceState) {
+ val c = when (state) {
+ DeviceState.Online -> MaterialTheme.colorScheme.primary
+ DeviceState.Waiting, DeviceState.Found, DeviceState.NeedsPairing -> MaterialTheme.colorScheme.tertiary
+ DeviceState.Offline, DeviceState.NotAllowed -> MaterialTheme.colorScheme.outline
+ }
+ Box(Modifier.size(10.dp).clip(CircleShape).background(c))
+}
+
+@Composable
+private fun OfflineCard(device: Device, now: Long, onReconnect: () -> Unit) {
+ Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh)) {
+ Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
+ Column(Modifier.weight(1f)) {
+ Text("Offline", style = MaterialTheme.typography.titleSmall)
+ Text(
+ "Last seen ${device.lastSeen?.let { Copy.ago(it, now) } ?: "a while ago"}. It reconnects on its own when the TV is back on.",
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ }
+ Spacer(Modifier.width(12.dp))
+ FilledTonalButton(onClick = onReconnect) { Text("Reconnect") }
+ }
+ }
+}
+
+/** Stat strip, phone-shaped: a 3×2 grid. Missing stats show "—", never 0. */
+@Composable
+private fun StatGrid(s: Snapshot?, modifier: Modifier = Modifier) {
+ val cells = listOf(
+ "CPU" to s?.let { "${it.cpuPercent}%" },
+ // Units live in the label so the value fits a third of a phone width.
+ "RAM GB" to s?.let { "%.1f/%.0f".format(it.ramUsedMb / 1024.0, it.ramTotalMb / 1024.0) },
+ "Storage GB" to s?.storageUsedGb?.let { u -> s.storageTotalGb?.let { t -> "%.1f/%.0f".format(u, t) } },
+ "Temp" to s?.tempC?.let { "$it°C" },
+ "Up" to s?.let { Copy.uptime(it.uptimeSeconds) },
+ "Screen" to s?.screenOn?.let { if (it) "on" else "off" },
+ )
+ Card(modifier, colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer)) {
+ Column(Modifier.padding(vertical = 8.dp)) {
+ cells.chunked(3).forEach { row ->
+ Row(Modifier.fillMaxWidth()) {
+ row.forEach { (label, value) ->
+ Column(Modifier.weight(1f).padding(horizontal = 16.dp, vertical = 8.dp)) {
+ Text(label.uppercase(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text(value ?: "—", style = StatNumber, maxLines = 1)
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** Grey bars, no chart library: top 6 by value, the rest summed as "other". */
+@Composable
+private fun UsageCard(snap: Snapshot, apps: List<AppInfo>) {
+ val labels = apps.associate { it.packageName to it.label }
+ fun label(p: Proc) = p.packageName?.let { labels[it] ?: it } ?: Copy.ANDROID_SYSTEM
+ val byApp = snap.procs.groupBy(::label)
+ var cpu by rememberSaveable { mutableStateOf(false) }
+ val rows = byApp.map { (name, ps) ->
+ name to if (cpu) ps.sumOf { it.cpuPercent } else ps.sumOf { it.ramMb }.toDouble()
+ }
+ Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer)) {
+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(if (cpu) "CPU by app" else "RAM by app", style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1f))
+ TextButton(onClick = { cpu = !cpu }) { Text(if (cpu) "Show RAM" else "Show CPU") }
+ }
+ Bars(rows, fmt = { if (cpu) "%.0f%%".format(it) else Copy.mb(it.toInt()) })
+ }
+ }
+}
+
+@Composable
+private fun Bars(rows: List<Pair<String, Double>>, fmt: (Double) -> String, top: Int = 6) {
+ val sorted = rows.sortedByDescending { it.second }
+ val rest = sorted.drop(top).sumOf { it.second }
+ val shown = sorted.take(top) + if (rest > 0) listOf("Other" to rest) else emptyList()
+ val max = shown.maxOfOrNull { it.second }?.coerceAtLeast(1.0) ?: 1.0
+ shown.forEach { (name, v) ->
+ val frac by animateFloatAsState((v / max).toFloat(), MaterialTheme.motionScheme.defaultSpatialSpec(), label = "bar")
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(name, Modifier.width(120.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Box(Modifier.weight(1f).height(12.dp).clip(MaterialTheme.shapes.small).background(MaterialTheme.colorScheme.surfaceContainerHigh)) {
+ Box(Modifier.fillMaxHeight().fillMaxWidth(frac).clip(MaterialTheme.shapes.small).background(MaterialTheme.colorScheme.primary))
+ }
+ Text(fmt(v), Modifier.width(72.dp), style = SmallNumber, textAlign = androidx.compose.ui.text.style.TextAlign.End)
+ }
+ }
+}
+
+/** A collapsible card section. */
+private fun LazyListScope.section(
+ key: String,
+ title: String,
+ count: Int,
+ expandedByDefault: Boolean = false,
+ forceOpen: Boolean = false,
+ body: @Composable () -> Unit,
+) {
+ item(key = key) {
+ var open by rememberSaveable { mutableStateOf(expandedByDefault) }
+ val shown = open || forceOpen
+ val turn by animateFloatAsState(if (shown) 180f else 0f, MaterialTheme.motionScheme.fastSpatialSpec(), label = "chevron")
+ Card(
+ Modifier.fillMaxWidth().animateContentSize(MaterialTheme.motionScheme.defaultSpatialSpec()),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow),
+ ) {
+ Row(
+ Modifier.fillMaxWidth().clickable { open = !open }.padding(16.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
+ Text("$count", style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Spacer(Modifier.width(8.dp))
+ Icon(Icons.Default.KeyboardArrowDown, contentDescription = if (shown) "Collapse" else "Expand", Modifier.rotate(turn))
+ }
+ AnimatedVisibility(shown) {
+ Column(Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ body()
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun EmptyLine(q: String) {
+ Text(
+ if (q.isEmpty()) "Nothing here yet." else "Nothing matches \"$q\".",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+}
+
+@Composable
+fun AppIcon(app: AppInfo, modifier: Modifier = Modifier) {
+ val bg = app.iconColor?.let { Color(it) } ?: MaterialTheme.colorScheme.secondaryContainer
+ val fg = if (app.iconColor != null) Color.White else MaterialTheme.colorScheme.onSecondaryContainer
+ Box(modifier.size(40.dp).clip(MaterialTheme.shapes.medium).background(bg), contentAlignment = Alignment.Center) {
+ Text(app.label.take(1).uppercase(), color = fg, style = MaterialTheme.typography.titleMedium)
+ }
+}
+
+@OptIn(ExperimentalMaterial3ExpressiveApi::class)
+@Composable
+private fun AppRow(
+ app: AppInfo,
+ procs: List<Proc>,
+ pending: Pair<String, Action>?,
+ busy: Boolean,
+ actions: DeviceActions,
+) {
+ var open by rememberSaveable(app.packageName) { mutableStateOf(false) }
+ val ram = procs.filter { it.packageName == app.packageName }.sumOf { it.ramMb }
+ val status = when {
+ !app.enabled -> "Disabled"
+ ram > 0 -> "Running · ${Copy.mb(ram)}"
+ else -> "Not running"
+ }
+ Column(Modifier.fillMaxWidth().clip(MaterialTheme.shapes.large).clickable(enabled = app.protectedReason == null) { open = !open }.padding(vertical = 8.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ AppIcon(app, Modifier.alpha(if (app.enabled) 1f else 0.4f))
+ Spacer(Modifier.width(12.dp))
+ Column(Modifier.weight(1f)) {
+ Text(app.label, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(
+ app.protectedReason?.let { "Protected: $it" } ?: status,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ if (busy) androidx.compose.material3.LoadingIndicator(Modifier.size(32.dp))
+ }
+ val proposed = pending?.takeIf { it.first == app.packageName }?.second
+ AnimatedVisibility((open || proposed != null) && app.protectedReason == null) {
+ Column(Modifier.padding(start = 52.dp, top = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (proposed == null) {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (app.enabled && ram > 0) OutlinedButton(onClick = { actions.propose(app.packageName, Action.Stop) }) { Text(Copy.button(Action.Stop)) }
+ if (app.enabled) OutlinedButton(onClick = { actions.propose(app.packageName, Action.Disable) }) { Text(Copy.button(Action.Disable)) }
+ else FilledTonalButton(onClick = { actions.propose(app.packageName, Action.Enable) }) { Text(Copy.button(Action.Enable)) }
+ }
+ } else {
+ Text(Copy.explain(proposed, app.label), style = MaterialTheme.typography.bodyMedium)
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(onClick = actions.confirm) { Text(Copy.confirm(proposed)) }
+ TextButton(onClick = actions.cancel) { Text("Cancel") }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun ProcessTable(procs: List<Proc>, apps: List<AppInfo>, q: String) {
+ val labels = apps.associate { it.packageName to it.label }
+ val groups = procs
+ .groupBy { p -> p.packageName?.let { labels[it] ?: it } ?: Copy.ANDROID_SYSTEM }
+ .filter { (name, ps) -> q.isEmpty() || name.lowercase().contains(q) || ps.any { it.name.lowercase().contains(q) } }
+ .toList()
+ .sortedByDescending { (_, ps) -> ps.sumOf { it.cpuPercent } }
+ if (groups.isEmpty()) return EmptyLine(q)
+ Row {
+ Text("App", Modifier.weight(1f), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text("CPU", Modifier.width(56.dp), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = androidx.compose.ui.text.style.TextAlign.End)
+ Text("RAM", Modifier.width(72.dp), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = androidx.compose.ui.text.style.TextAlign.End)
+ }
+ groups.forEach { (name, ps) ->
+ var open by rememberSaveable(name) { mutableStateOf(false) }
+ Column(Modifier.fillMaxWidth().clickable { open = !open }.padding(vertical = 6.dp)) {
+ Row {
+ Text(
+ if (ps.size > 1) "$name ×${ps.size}" else name,
+ Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+ Text("%.0f%%".format(ps.sumOf { it.cpuPercent }), Modifier.width(56.dp), style = SmallNumber, textAlign = androidx.compose.ui.text.style.TextAlign.End)
+ Text(Copy.mb(ps.sumOf { it.ramMb }), Modifier.width(72.dp), style = SmallNumber, textAlign = androidx.compose.ui.text.style.TextAlign.End)
+ }
+ if (open) ps.forEach { p ->
+ Row(Modifier.padding(start = 12.dp, top = 2.dp)) {
+ Text("${p.pid} ${p.name}", Modifier.weight(1f), style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text("%.1f%%".format(p.cpuPercent), Modifier.width(56.dp), style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = androidx.compose.ui.text.style.TextAlign.End)
+ Text(Copy.mb(p.ramMb), Modifier.width(72.dp), style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = androidx.compose.ui.text.style.TextAlign.End)
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun NetworkBlock(n: NetworkInfo, q: String) {
+ if (q.isEmpty()) {
+ KeyValue("Connection", listOfNotNull(if (n.iface == "wifi") "Wi-Fi" else "Ethernet", n.ssid).joinToString(" · "))
+ KeyValue("IP", n.ip)
+ n.mac?.let { KeyValue("MAC", it) }
+ n.rssi?.let { r -> KeyValue("Signal", "$r dBm · ${signalWord(r)}" + (n.linkMbps?.let { " · $it Mbps" } ?: "")) }
+ Spacer(Modifier.height(8.dp))
+ Text("Data used", style = MaterialTheme.typography.titleSmall)
+ Bars(n.traffic.map { it.app to (it.rxMb + it.txMb).toDouble() }, fmt = { Copy.mb(it.toInt()) })
+ Spacer(Modifier.height(8.dp))
+ }
+ Text("Open connections", style = MaterialTheme.typography.titleSmall)
+ val socks = n.sockets.filter { q.isEmpty() || it.app.lowercase().contains(q) || it.remote.lowercase().contains(q) }
+ if (socks.isEmpty()) EmptyLine(q)
+ socks.forEach { s ->
+ Row(Modifier.padding(vertical = 2.dp)) {
+ Text(s.app, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(s.remote, style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ }
+}
+
+private fun signalWord(rssi: Int) = when {
+ rssi >= -55 -> "strong"
+ rssi >= -67 -> "good"
+ rssi >= -75 -> "weak"
+ else -> "very weak"
+}
+
+@Composable
+private fun KeyValue(k: String, v: String) {
+ Row(Modifier.padding(vertical = 2.dp)) {
+ Text(k, Modifier.width(96.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ Text(v, style = SmallNumber)
+ }
+}
+
+@Composable
+private fun HistoryList(history: List<HistoryEntry>, now: Long, onUndo: (HistoryEntry) -> Unit) {
+ if (history.isEmpty()) {
+ Text(
+ "Nothing changed yet. Anything you stop, disable or turn on shows up here, with a way to undo it.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ return
+ }
+ history.forEach { h ->
+ Row(Modifier.padding(vertical = 2.dp), verticalAlignment = Alignment.CenterVertically) {
+ Column(Modifier.weight(1f)) {
+ Text(Copy.done(h.action, h.label), style = MaterialTheme.typography.bodyMedium)
+ Text(Copy.ago(h.at, now), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ when {
+ h.undoneAt != null -> Text("Undone", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ h.undo != null -> TextButton(onClick = { onUndo(h) }) { Text(Copy.undo(h.undo)) }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/app/tellyscope/ui/GuideCard.kt b/app/src/main/java/app/tellyscope/ui/GuideCard.kt
new file mode 100644
index 0000000..8f0884d
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/GuideCard.kt
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.FilterChip
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import app.tellyscope.ui.theme.SmallNumber
+
+/**
+ * Shown when a scan finds nothing. Steps differ per brand because the menu
+ * names do. The scan keeps re-running behind this card, so the user never has
+ * to come back and press anything.
+ */
+private val guides = linkedMapOf(
+ "Google TV" to listOf(
+ "Settings → System → About",
+ "Highlight \"Android TV OS build\" and press OK 7 times, until it says you're a developer",
+ "Back to System → Developer options",
+ "Turn on \"USB debugging\"",
+ ),
+ "Android TV" to listOf(
+ "Settings → Device Preferences → About",
+ "Press OK on \"Build\" 7 times",
+ "Back to Device Preferences → Developer options",
+ "Turn on \"USB debugging\", and \"Network debugging\" if you see it",
+ ),
+ "Fire TV" to listOf(
+ "Settings → My Fire TV → About",
+ "Press OK on the first row (your Fire TV's name) 7 times",
+ "Back to My Fire TV → Developer options",
+ "Turn on \"ADB debugging\"",
+ ),
+ "Xiaomi" to listOf(
+ "Settings → Device Preferences → About",
+ "Press OK on \"Build\" 7 times",
+ "Back to Device Preferences → Developer options",
+ "Turn on \"USB debugging\"",
+ ),
+ "XGIMI" to listOf(
+ "Settings → Device Preferences → About",
+ "Press OK on \"Build\" 7 times",
+ "Back to Device Preferences → Developer options",
+ "Turn on \"USB debugging\", then \"Network debugging\" if it's listed",
+ ),
+)
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+fun GuideCard(modifier: Modifier = Modifier) {
+ var brand by rememberSaveable { mutableStateOf(guides.keys.first()) }
+ Card(
+ modifier.fillMaxWidth(),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh),
+ ) {
+ Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text("Turn on debugging on your TV", style = MaterialTheme.typography.titleLarge)
+ Text(
+ "Pick your TV and follow the steps on it. This screen finds it on its own when you're done.",
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ guides.keys.forEach { b ->
+ FilterChip(selected = b == brand, onClick = { brand = b }, label = { Text(b) })
+ }
+ }
+ guides.getValue(brand).forEachIndexed { i, step ->
+ Row {
+ Text("${i + 1}", style = SmallNumber, color = MaterialTheme.colorScheme.primary)
+ androidx.compose.foundation.layout.Spacer(Modifier.width(12.dp))
+ Text(step, style = MaterialTheme.typography.bodyLarge)
+ }
+ }
+ HorizontalDivider()
+ Text(
+ "Newer TVs (Android 11+) may show \"Wireless debugging\" instead. Turn that on too; you'll type a 6-digit code when you connect.",
+ style = MaterialTheme.typography.bodySmall,
+ )
+ if (brand == "Fire TV") {
+ Text(
+ "No Developer options after 7 presses? Newer Fire TVs run Vega OS, which isn't Android, and Tellyscope can't reach them.",
+ style = MaterialTheme.typography.bodySmall,
+ )
+ }
+ Text(
+ "Debugging switched itself off? Some TVs reset it after a restart. Turn it back on and this screen reconnects.",
+ style = MaterialTheme.typography.bodySmall,
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/app/tellyscope/ui/ScanScreen.kt b/app/src/main/java/app/tellyscope/ui/ScanScreen.kt
new file mode 100644
index 0000000..70ad8ab
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/ScanScreen.kt
@@ -0,0 +1,252 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import androidx.compose.animation.animateContentSize
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+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.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Add
+import androidx.compose.material.icons.filled.Refresh
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
+import androidx.compose.material3.FilledTonalButton
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.LinearWavyProgressIndicator
+import androidx.compose.material3.LoadingIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+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.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+import app.tellyscope.data.ScanHit
+import app.tellyscope.data.ScanKind
+import app.tellyscope.ui.theme.SmallNumber
+import app.tellyscope.ui.theme.StatNumber
+
+@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
+@Composable
+fun ScanScreen(
+ scan: ScanUi,
+ now: Long,
+ onRescan: () -> Unit,
+ onConnect: (ScanHit) -> Unit,
+ onCode: (ScanHit, String) -> Unit,
+ onPair: (ScanHit) -> Unit,
+ onAddByIp: (String) -> String?,
+ onBack: (() -> Unit)? = null,
+) {
+ var adding by remember { mutableStateOf(false) }
+ Scaffold(
+ topBar = {
+ TopAppBar(
+ title = { Text("Tellyscope") },
+ navigationIcon = { if (onBack != null) TextButton(onClick = onBack) { Text("Done") } },
+ actions = {
+ IconButton(onClick = onRescan, enabled = !scan.scanning) {
+ Icon(Icons.Default.Refresh, contentDescription = "Scan again")
+ }
+ },
+ )
+ },
+ ) { pad ->
+ LazyColumn(
+ Modifier.fillMaxSize().padding(pad),
+ contentPadding = PaddingValues(16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ item {
+ Text("What's running on your TV?", style = MaterialTheme.typography.headlineMedium)
+ Text(
+ "Live stats, apps and network for the Android TVs on your Wi-Fi.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ item { ScanStatus(scan) }
+ items(scan.hits, key = { it.ip }) { hit ->
+ HitCard(hit, scan.rows[hit.ip] ?: RowState.Found, now, onConnect, onCode, onPair)
+ }
+ if (!scan.scanning && scan.hits.isEmpty()) {
+ item { GuideCard() }
+ }
+ item {
+ OutlinedButton(onClick = { adding = true }) {
+ Icon(Icons.Default.Add, null, Modifier.size(18.dp))
+ Spacer(Modifier.width(8.dp))
+ Text("Add by IP address")
+ }
+ }
+ }
+ }
+ if (adding) AddByIpDialog(onDismiss = { adding = false }, onSubmit = { onAddByIp(it).also { e -> if (e == null) adding = false } })
+}
+
+@OptIn(ExperimentalMaterial3ExpressiveApi::class)
+@Composable
+private fun ScanStatus(scan: ScanUi) {
+ val p = scan.progress
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (scan.scanning) {
+ Text(
+ "Looking for TVs on ${p?.subnet ?: "your Wi-Fi"}… ${p?.probed ?: 0}/${p?.total ?: 254}",
+ style = MaterialTheme.typography.labelLarge,
+ )
+ LinearWavyProgressIndicator(
+ progress = { p?.let { it.probed / it.total.toFloat() } ?: 0f },
+ modifier = Modifier.fillMaxWidth(),
+ )
+ } else {
+ val n = scan.hits.size
+ Text(
+ if (n == 0) "No TVs found yet" else "Found $n ${if (n == 1) "TV" else "TVs"} on ${p?.subnet ?: "your Wi-Fi"}",
+ style = MaterialTheme.typography.labelLarge,
+ )
+ }
+ }
+}
+
+@OptIn(ExperimentalMaterial3ExpressiveApi::class)
+@Composable
+private fun HitCard(
+ hit: ScanHit,
+ row: RowState,
+ now: Long,
+ onConnect: (ScanHit) -> Unit,
+ onCode: (ScanHit, String) -> Unit,
+ onPair: (ScanHit) -> Unit,
+) {
+ Card(
+ Modifier.fillMaxWidth().animateContentSize(MaterialTheme.motionScheme.defaultSpatialSpec()),
+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
+ ) {
+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Column(Modifier.weight(1f)) {
+ Text(hit.hostname ?: hit.maker ?: "Android device", style = MaterialTheme.typography.titleMedium)
+ Text(
+ listOfNotNull(hit.maker ?: "Unknown maker", hit.ip).joinToString(" · "),
+ style = SmallNumber,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ when (row) {
+ RowState.Found -> FilledTonalButton(onClick = { onConnect(hit) }) { Text("Connect") }
+ RowState.NotAllowed -> FilledTonalButton(onClick = { onConnect(hit) }) { Text("Try again") }
+ else -> Unit
+ }
+ }
+ when (row) {
+ RowState.Found -> Text(
+ if (hit.kind == ScanKind.Wireless) "Needs the pairing code from the TV" else "Ready to connect",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ is RowState.Waiting -> if (hit.kind == ScanKind.Wireless) Row(verticalAlignment = Alignment.CenterVertically) {
+ LoadingIndicator(Modifier.size(32.dp))
+ Spacer(Modifier.width(12.dp))
+ Text("Connecting…", style = MaterialTheme.typography.bodyMedium)
+ } else Row(verticalAlignment = Alignment.CenterVertically) {
+ LoadingIndicator(Modifier.size(48.dp))
+ Spacer(Modifier.width(12.dp))
+ Column {
+ Text("Check your TV", style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
+ Text(
+ "A box saying \"Allow USB debugging?\" is on screen. Tick \"Always allow from this phone\", then press Allow.",
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Text(
+ "Waiting… ${((now - row.since) / 1000).coerceAtLeast(0)} s",
+ style = SmallNumber,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ RowState.NotAllowed -> Column {
+ Text("No answer from the TV", style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.error)
+ Text(
+ "Is the box still on screen? If you pressed Deny by mistake, tap Try again and it will ask once more.",
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ }
+ is RowState.Code -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(
+ "On the TV: Settings → Developer options → Wireless debugging → Pair device with pairing code. Type the 6 digits it shows:",
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ OutlinedTextField(
+ value = row.input,
+ onValueChange = { onCode(hit, it) },
+ modifier = Modifier.weight(1f),
+ singleLine = true,
+ enabled = !row.busy,
+ textStyle = StatNumber,
+ placeholder = { Text("000000", style = StatNumber) },
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
+ isError = row.error != null,
+ )
+ Spacer(Modifier.width(12.dp))
+ Button(onClick = { onPair(hit) }, enabled = !row.busy && row.input.length == 6) {
+ Text(if (row.busy) "Pairing…" else "Pair")
+ }
+ }
+ row.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun AddByIpDialog(onDismiss: () -> Unit, onSubmit: (String) -> String?) {
+ var text by remember { mutableStateOf("") }
+ var error by remember { mutableStateOf<String?>(null) }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Add by IP address") },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Find it on the TV under Settings → Network → your Wi-Fi.")
+ OutlinedTextField(
+ value = text,
+ onValueChange = { text = it; error = null },
+ singleLine = true,
+ textStyle = StatNumber,
+ isError = error != null,
+ supportingText = error?.let { { Text(it) } },
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
+ )
+ }
+ },
+ confirmButton = { Button(onClick = { error = onSubmit(text) }) { Text("Connect") } },
+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
+ )
+}
diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
new file mode 100644
index 0000000..c5ddf2a
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
@@ -0,0 +1,238 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import app.tellyscope.data.Action
+import app.tellyscope.data.AppInfo
+import app.tellyscope.data.ConnectResult
+import app.tellyscope.data.Device
+import app.tellyscope.data.DeviceSource
+import app.tellyscope.data.DeviceState
+import app.tellyscope.data.HistoryEntry
+import app.tellyscope.data.NetworkInfo
+import app.tellyscope.data.ScanEvent
+import app.tellyscope.data.ScanHit
+import app.tellyscope.data.ScanProgress
+import app.tellyscope.data.Snapshot
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeoutOrNull
+
+/** Per-row connect state on the scan screen. */
+sealed interface RowState {
+ data object Found : RowState
+ data class Waiting(val since: Long) : RowState
+ data class Code(val input: String = "", val busy: Boolean = false, val error: String? = null) : RowState
+ data object NotAllowed : RowState
+}
+
+data class ScanUi(
+ val scanning: Boolean = false,
+ val progress: ScanProgress? = null,
+ val hits: List<ScanHit> = emptyList(),
+ val rows: Map<String, RowState> = emptyMap(),
+)
+
+data class DeviceUi(
+ val snapshot: Snapshot? = null,
+ val apps: List<AppInfo> = emptyList(),
+ val network: NetworkInfo? = null,
+ val history: List<HistoryEntry> = emptyList(),
+ /** Package whose action row is open, and the action awaiting confirmation. */
+ val pending: Pair<String, Action>? = null,
+ val busy: String? = null,
+)
+
+data class UiState(
+ val scan: ScanUi = ScanUi(),
+ val devices: List<Device> = emptyList(),
+ val selectedId: String? = null,
+ val showOffline: Boolean = false,
+ val device: DeviceUi = DeviceUi(),
+ val query: String = "",
+ val now: Long = System.currentTimeMillis(),
+) {
+ val selected: Device? get() = devices.firstOrNull { it.id == selectedId }
+}
+
+class TellyscopeViewModel(
+ private val source: DeviceSource,
+ private val allowTimeoutMs: Long = 60_000,
+ private val clock: () -> Long = System::currentTimeMillis,
+) : ViewModel() {
+
+ private val _state = MutableStateFlow(UiState(now = clock()))
+ val state: StateFlow<UiState> = _state.asStateFlow()
+
+ /** One-shot "done, undo?" messages for the snackbar. */
+ private val _done = MutableStateFlow<HistoryEntry?>(null)
+ val done: StateFlow<HistoryEntry?> = _done.asStateFlow()
+
+ private var scanJob: Job? = null
+ private var liveJob: Job? = null
+ private var mediumJob: Job? = null
+
+ init {
+ viewModelScope.launch { _state.update { it.copy(devices = source.known()) } }
+ viewModelScope.launch {
+ while (true) {
+ delay(1_000)
+ _state.update { it.copy(now = clock()) }
+ }
+ }
+ rescan()
+ }
+
+ fun rescan() {
+ if (scanJob?.isActive == true) return
+ scanJob = viewModelScope.launch {
+ _state.update { it.copy(scan = it.scan.copy(scanning = true)) }
+ source.scan().collect { e ->
+ when (e) {
+ is ScanEvent.Progress -> _state.update { it.copy(scan = it.scan.copy(progress = e.progress)) }
+ is ScanEvent.Found -> _state.update { s ->
+ val known = s.devices.any { it.hit.ip == e.hit.ip }
+ if (known || s.scan.hits.any { it.ip == e.hit.ip }) s
+ else s.copy(scan = s.scan.copy(
+ hits = (s.scan.hits + e.hit).sortedWith(compareBy({ it.maker == null }, { ipKey(it.ip) })),
+ rows = s.scan.rows + (e.hit.ip to RowState.Found),
+ ))
+ }
+ ScanEvent.Done -> Unit
+ }
+ }
+ _state.update { it.copy(scan = it.scan.copy(scanning = false)) }
+ // Empty scan: the guide is on screen; keep looking so the user never has to press anything.
+ if (_state.value.scan.hits.isEmpty()) {
+ delay(15_000)
+ rescan()
+ }
+ }
+ }
+
+ fun connect(hit: ScanHit) {
+ // Wireless-debugging TVs that already know our key connect straight away;
+ // the rest answer NeedsPairing and get the code field.
+ setRow(hit.ip, RowState.Waiting(clock()))
+ viewModelScope.launch {
+ when (val r = withTimeoutOrNull(allowTimeoutMs) { source.connect(hit) }) {
+ is ConnectResult.Online -> online(r.device)
+ ConnectResult.NeedsPairing -> setRow(hit.ip, RowState.Code())
+ null, ConnectResult.NotAllowed, is ConnectResult.Unreachable, is ConnectResult.WrongCode ->
+ setRow(hit.ip, RowState.NotAllowed)
+ }
+ }
+ }
+
+ fun codeChanged(hit: ScanHit, input: String) {
+ setRow(hit.ip, RowState.Code(input.filter(Char::isDigit).take(6)))
+ }
+
+ fun pair(hit: ScanHit) {
+ val row = _state.value.scan.rows[hit.ip] as? RowState.Code ?: return
+ setRow(hit.ip, row.copy(busy = true, error = null))
+ viewModelScope.launch {
+ when (val r = source.pair(hit, row.input)) {
+ is ConnectResult.Online -> online(r.device)
+ is ConnectResult.WrongCode -> setRow(hit.ip, row.copy(busy = false, error = r.message))
+ is ConnectResult.Unreachable -> setRow(hit.ip, row.copy(busy = false, error = r.message))
+ ConnectResult.NotAllowed -> setRow(hit.ip, RowState.NotAllowed)
+ ConnectResult.NeedsPairing -> setRow(hit.ip, row.copy(busy = false, error = "The TV still wants a code. Check the number on screen and try again."))
+ }
+ }
+ }
+
+ /** "Add by IP": `ip` or `ip:port`. Returns an error line, or null when the connect started. */
+ fun addByIp(text: String): String? {
+ val m = Regex("""^(\d{1,3}(?:\.\d{1,3}){3})(?::(\d{1,5}))?$""").find(text.trim())
+ ?: return "That doesn't look like an IP address. It should look like four numbers with dots, like the one in your TV's network settings."
+ val port = m.groupValues[2].toIntOrNull() ?: 5555
+ val kind = if (port == 5555) app.tellyscope.data.ScanKind.Classic else app.tellyscope.data.ScanKind.Wireless
+ val hit = ScanHit(m.groupValues[1], port, kind, null, null)
+ _state.update { s ->
+ if (s.scan.hits.any { it.ip == hit.ip }) s
+ else s.copy(scan = s.scan.copy(hits = listOf(hit) + s.scan.hits))
+ }
+ connect(hit)
+ return null
+ }
+
+ private fun online(device: Device) {
+ _state.update { s ->
+ s.copy(
+ devices = s.devices.filterNot { it.id == device.id } + device,
+ scan = s.scan.copy(hits = s.scan.hits.filterNot { it.ip == device.hit.ip }),
+ )
+ }
+ select(device.id)
+ }
+
+ fun select(id: String?) {
+ liveJob?.cancel()
+ mediumJob?.cancel()
+ _state.update { it.copy(selectedId = id, device = DeviceUi(), query = "") }
+ val device = _state.value.selected ?: return
+ if (device.state != DeviceState.Online) return
+ liveJob = viewModelScope.launch {
+ source.live(id!!).collect { snap -> _state.update { it.copy(device = it.device.copy(snapshot = snap)) } }
+ }
+ mediumJob = viewModelScope.launch {
+ _state.update { it.copy(device = it.device.copy(apps = source.apps(id!!))) }
+ while (true) {
+ val net = source.network(id!!)
+ _state.update { it.copy(device = it.device.copy(network = net)) }
+ delay(10_000)
+ }
+ }
+ }
+
+ fun showOffline(show: Boolean) = _state.update { it.copy(showOffline = show) }
+
+ fun query(q: String) = _state.update { it.copy(query = q) }
+
+ /** First tap on an action button: show what it will do. */
+ fun propose(pkg: String, action: Action) =
+ _state.update { it.copy(device = it.device.copy(pending = pkg to action)) }
+
+ fun cancel() = _state.update { it.copy(device = it.device.copy(pending = null)) }
+
+ fun confirm() {
+ val (pkg, action) = _state.value.device.pending ?: return
+ run(pkg, action)
+ }
+
+ fun undo(entry: HistoryEntry) {
+ val undo = entry.undo ?: return
+ run(entry.packageName, undo, undoing = entry.id)
+ }
+
+ private fun run(pkg: String, action: Action, undoing: Long? = null) {
+ val id = _state.value.selectedId ?: return
+ _state.update { it.copy(device = it.device.copy(pending = null, busy = pkg)) }
+ viewModelScope.launch {
+ val entry = source.act(id, action, pkg)
+ val apps = source.apps(id)
+ _state.update { s ->
+ val history = s.device.history.map { if (it.id == undoing) it.copy(undoneAt = entry.at) else it }
+ s.copy(device = s.device.copy(apps = apps, busy = null, history = listOf(entry) + history))
+ }
+ if (undoing == null) _done.value = entry
+ }
+ }
+
+ fun doneShown() {
+ _done.value = null
+ }
+
+ private fun setRow(ip: String, row: RowState) =
+ _state.update { it.copy(scan = it.scan.copy(rows = it.scan.rows + (ip to row))) }
+
+ private fun ipKey(ip: String) = ip.split('.').fold(0L) { acc, o -> acc * 256 + (o.toLongOrNull() ?: 0) }
+}
diff --git a/app/src/main/java/app/tellyscope/ui/theme/Theme.kt b/app/src/main/java/app/tellyscope/ui/theme/Theme.kt
index e9180ee..754b51c 100644
--- a/app/src/main/java/app/tellyscope/ui/theme/Theme.kt
+++ b/app/src/main/java/app/tellyscope/ui/theme/Theme.kt
@@ -7,30 +7,79 @@ import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.MaterialExpressiveTheme
import androidx.compose.material3.MotionScheme
+import androidx.compose.material3.Typography
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
-import androidx.compose.material3.expressiveLightColorScheme
+import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
+import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.sp
+
+// Branded fallback for phones without dynamic color (Android 11 and older).
+// Seed: a deep teal, picked to read as "screen glow" without clashing with app icon tiles.
+private val LightBrand = lightColorScheme(
+ primary = Color(0xFF00696B),
+ onPrimary = Color(0xFFFFFFFF),
+ primaryContainer = Color(0xFF9CF1F2),
+ onPrimaryContainer = Color(0xFF002020),
+ secondary = Color(0xFF4A6363),
+ secondaryContainer = Color(0xFFCCE8E8),
+ onSecondaryContainer = Color(0xFF051F1F),
+ tertiary = Color(0xFF4B607C),
+ tertiaryContainer = Color(0xFFD3E4FF),
+ error = Color(0xFFBA1A1A),
+ background = Color(0xFFF4FBFA),
+ surface = Color(0xFFF4FBFA),
+ surfaceContainerLow = Color(0xFFEEF5F4),
+ surfaceContainer = Color(0xFFE9EFEE),
+ surfaceContainerHigh = Color(0xFFE3E9E9),
+)
+
+private val DarkBrand = darkColorScheme(
+ primary = Color(0xFF80D4D5),
+ onPrimary = Color(0xFF003737),
+ primaryContainer = Color(0xFF004F50),
+ onPrimaryContainer = Color(0xFF9CF1F2),
+ secondary = Color(0xFFB0CCCB),
+ secondaryContainer = Color(0xFF324B4B),
+ onSecondaryContainer = Color(0xFFCCE8E8),
+ tertiary = Color(0xFFB3C8E8),
+ tertiaryContainer = Color(0xFF334863),
+ error = Color(0xFFFFB4AB),
+ background = Color(0xFF0E1415),
+ surface = Color(0xFF0E1415),
+ surfaceContainerLow = Color(0xFF161D1D),
+ surfaceContainer = Color(0xFF1A2121),
+ surfaceContainerHigh = Color(0xFF252B2B),
+)
+
+/** Numbers come first: stats use a tabular monospace so values don't jitter as they update. */
+val StatNumber = TextStyle(fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, fontSize = 20.sp, lineHeight = 26.sp)
+val SmallNumber = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp)
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun TellyscopeTheme(
- darkTheme: Boolean = isSystemInDarkTheme(),
+ dark: Boolean = isSystemInDarkTheme(),
+ dynamic: Boolean = true,
content: @Composable () -> Unit,
) {
- val colorScheme = when {
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
- val context = LocalContext.current
- if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
- }
- darkTheme -> darkColorScheme()
- else -> expressiveLightColorScheme()
+ val context = LocalContext.current
+ val colors = when {
+ dynamic && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
+ if (dark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
+ dark -> DarkBrand
+ else -> LightBrand
}
MaterialExpressiveTheme(
- colorScheme = colorScheme,
+ colorScheme = colors,
motionScheme = MotionScheme.expressive(),
+ typography = Typography(),
content = content,
)
}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 8f47ec6..3175ecb 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1,4 +1,3 @@
<resources>
<string name="app_name">Tellyscope</string>
- <string name="home_status">Pre-alpha. Nothing to connect to yet.</string>
</resources>
diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.kt
new file mode 100644
index 0000000..a20fdca
--- /dev/null
+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope
+
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.test.junit4.v2.createComposeRule
+import androidx.compose.ui.test.onRoot
+import app.tellyscope.data.Action
+import app.tellyscope.data.Device
+import app.tellyscope.data.DeviceState
+import app.tellyscope.data.FakeDeviceSource
+import app.tellyscope.data.HistoryEntry
+import app.tellyscope.data.ScanHit
+import app.tellyscope.data.ScanKind
+import app.tellyscope.data.ScanProgress
+import app.tellyscope.ui.DeviceActions
+import app.tellyscope.ui.DeviceScreen
+import app.tellyscope.ui.DeviceUi
+import app.tellyscope.ui.RowState
+import app.tellyscope.ui.ScanScreen
+import app.tellyscope.ui.ScanUi
+import app.tellyscope.ui.UiState
+import app.tellyscope.ui.theme.TellyscopeTheme
+import com.github.takahirom.roborazzi.captureRoboImage
+import kotlin.random.Random
+import kotlinx.coroutines.runBlocking
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.annotation.GraphicsMode
+
+/**
+ * Renders each screen on fixed fake data. `./gradlew :app:recordRoborazziDebug`
+ * writes PNGs to app/build/outputs/roborazzi; `verifyRoborazziDebug` diffs them.
+ * Dynamic color is off so the branded fallback scheme is what gets reviewed.
+ */
+@RunWith(RobolectricTestRunner::class)
+@GraphicsMode(GraphicsMode.Mode.NATIVE)
+@Config(sdk = [35], qualifiers = "w411dp-h891dp-xxhdpi")
+class ScreenshotTest {
+
+ @get:Rule val compose = createComposeRule()
+
+ private val now = 1_760_000_000_000L
+ private val fake = FakeDeviceSource(clock = { now }, random = Random(7))
+
+ private val xgimi = ScanHit("192.168.1.23", 5555, ScanKind.Classic, "xgimi-projector", "XGIMI")
+ private val box = ScanHit("192.168.1.41", 5555, ScanKind.Classic, "android-7f3a", "Amlogic")
+ private val chromecast = ScanHit("192.168.1.57", 37211, ScanKind.Wireless, "chromecast", "Google")
+ private val unknown = ScanHit("192.168.1.88", 5555, ScanKind.Classic, null, null)
+
+ private fun shot(name: String, dark: Boolean = false, content: @Composable () -> Unit) {
+ // Expressive indicators animate forever, so the clock never idles on its own:
+ // drive it by hand and capture a fixed frame.
+ compose.mainClock.autoAdvance = false
+ compose.setContent { TellyscopeTheme(dark = dark, dynamic = false) { content() } }
+ compose.mainClock.advanceTimeBy(1_000)
+ compose.onRoot().captureRoboImage("build/outputs/roborazzi/${name}${if (dark) "_dark" else ""}.png")
+ }
+
+ private fun scan(ui: ScanUi, dark: Boolean = false, name: String) = shot(name, dark) {
+ ScanScreen(ui, now, {}, {}, { _, _ -> }, {}, { null })
+ }
+
+ @Test fun scan_inProgress() = scan(
+ ScanUi(
+ scanning = true,
+ progress = ScanProgress(115, 254, "192.168.1.0/24"),
+ hits = listOf(xgimi, box),
+ rows = mapOf(xgimi.ip to RowState.Found, box.ip to RowState.Found),
+ ),
+ name = "01_scan_in_progress",
+ )
+
+ private val connectStates get() = ScanUi(
+ scanning = false,
+ progress = ScanProgress(254, 254, "192.168.1.0/24"),
+ hits = listOf(xgimi, chromecast, unknown),
+ rows = mapOf(
+ xgimi.ip to RowState.Waiting(now - 12_000),
+ chromecast.ip to RowState.Code("4821"),
+ unknown.ip to RowState.NotAllowed,
+ ),
+ )
+
+ @Test fun scan_connectStates() = scan(connectStates, name = "02_scan_connect_states")
+
+ @Test fun scan_connectStates_dark() = scan(connectStates, dark = true, name = "02_scan_connect_states")
+
+ @Test fun scan_empty() = scan(
+ ScanUi(scanning = false, progress = ScanProgress(254, 254, "192.168.1.0/24")),
+ name = "03_scan_empty_guide",
+ )
+
+ private fun deviceState(device: DeviceUi.() -> DeviceUi = { this }): UiState = runBlocking {
+ val d = Device(xgimi.ip, xgimi, DeviceState.Online, "XGIMI Horizon Pro", "XGIMI", "11", now)
+ UiState(
+ devices = listOf(d) + fake.known(),
+ selectedId = d.id,
+ device = DeviceUi(
+ snapshot = fake.snapshot(d.id),
+ apps = fake.apps(d.id),
+ network = fake.network(d.id),
+ ).device(),
+ now = now,
+ )
+ }
+
+ @Test fun device_overview() = shot("04_device") { DeviceScreen(deviceState(), DeviceActions()) }
+
+ @Test fun device_overview_dark() = shot("04_device", dark = true) { DeviceScreen(deviceState(), DeviceActions()) }
+
+ @Config(qualifiers = "w411dp-h1500dp-xxhdpi")
+ @Test fun device_confirmDisable() {
+ val state = deviceState { copy(pending = "com.xgimi.assistant" to Action.Disable) }
+ shot("05_device_confirm_disable") { DeviceScreen(state, DeviceActions()) }
+ }
+
+ @Test fun device_offline() {
+ val base = deviceState()
+ val off = base.devices.last()
+ shot("06_device_offline") {
+ DeviceScreen(base.copy(selectedId = off.id, device = DeviceUi(), showOffline = true), DeviceActions())
+ }
+ }
+
+ @Config(qualifiers = "w411dp-h1500dp-xxhdpi")
+ @Test fun device_history() {
+ val history = listOf(
+ HistoryEntry(2, xgimi.ip, now - 40_000, Action.Disable, "com.xgimi.ota", "XGIMI Updates", Action.Enable, null),
+ HistoryEntry(1, xgimi.ip, now - 5 * 60_000, Action.Stop, "com.netflix.ninja", "Netflix", Action.Open, now - 4 * 60_000),
+ )
+ shot("07_device_history") { DeviceScreen(deviceState { copy(history = history) }, DeviceActions()) }
+ }
+}
diff --git a/build.gradle.kts b/build.gradle.kts
index e886066..68f905d 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -4,4 +4,5 @@ plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.jvm) apply false
alias(libs.plugins.kotlin.compose) apply false
+ alias(libs.plugins.roborazzi) apply false
}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 49c5ebc..6ae63f2 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -12,6 +12,8 @@ kadb = "2.1.5"
kadb-mdns = "2.1.4"
coroutines = "1.11.0"
conscrypt = "2.5.2"
+roborazzi = "1.77.0"
+robolectric = "4.17"
junit = "4.13.2"
[libraries]
@@ -23,6 +25,14 @@ compose-ui = { module = "androidx.compose.ui:ui" }
compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }
compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
compose-material3 = { module = "androidx.compose.material3:material3", version.ref = "material3" }
+compose-icons = { module = "androidx.compose.material:material-icons-core" }
+compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4" }
+compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" }
+androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }
+androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
+roborazzi = { module = "io.github.takahirom.roborazzi:roborazzi", version.ref = "roborazzi" }
+roborazzi-compose = { module = "io.github.takahirom.roborazzi:roborazzi-compose", version.ref = "roborazzi" }
+robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }
kadb = { module = "com.flyfishxu:kadb", version.ref = "kadb" }
kadb-mdns = { module = "com.flyfishxu:kadb-mdns", version.ref = "kadb-mdns" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
@@ -35,3 +45,4 @@ junit = { module = "junit:junit", version.ref = "junit" }
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
+roborazzi = { id = "io.github.takahirom.roborazzi", version.ref = "roborazzi" }