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 a remote control for the connected TV
jesse-agent-23295ac6643fbe7
diff --git a/README.md b/README.mdindex 55a9d1b..805802f 100644--- a/README.md+++ b/README.md@@ -14,6 +14,7 @@ Tellyscope is a phone app that talks to your Android TV or Google TV over the ne- **Debloat**: turn off preinstalled apps, ads and trackers you don't want, and turn them back on with one tap.- **Install apps**: pick an APK, a set of split APKs or an `.apks`/`.xapk` bundle on your phone and install it on the TV. It tells you first whether it's new or an update, and won't put an older version over a newer one unless you tick the box.- **Files**: send a file from your phone into the TV's Download or Movies folder, or save one from there to your phone. Nothing on the TV is overwritten.+- **Remote**: D-pad, Back, Home, volume and play/pause from the phone, typing into the TV's search boxes, and Sleep or Restart.It connects either through classic network debugging (port 5555) or through Android 11+ wireless debugging with a pairing code.diff --git a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.ktindex 805495e..8c020bf 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt@@ -31,4 +31,7 @@ data class RemoteEntry(val name: String, val mode: Int, val size: Long, val mtiminterface AdbSession : AdbShell, AdbTransfer, AutoCloseable {/** Writes [bytes] to [remotePath] on the device, mode 0644. Throws [java.io.IOException] if the link is gone. */suspend fun push(bytes: ByteArray, remotePath: String)++ /** Asks adbd to restart the device (the `reboot:` service, what `adb reboot` uses). */+ suspend fun reboot()}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.ktindex 9829aee..4081a25 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt@@ -116,5 +116,9 @@ internal class KadbSession(private val kadb: Kadb) : AdbSession {sync.list(remoteDir).map { RemoteEntry(it.name, it.mode, it.size, it.mtimeSec) }}+ override suspend fun reboot() {+ runInterruptible(Dispatchers.IO) { kadb.open("reboot:").close() }+ }+override fun close() = kadb.close()}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt b/adb/src/main/kotlin/app/tellyscope/adb/Remote.ktnew file mode 100644index 0000000..9f50e11--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt@@ -0,0 +1,75 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.CancellationException++/**+ * The TV's remote. Keys are a fixed list of Android key codes, so nothing the user does reaches+ * the shell line except text, which [typeCommand] quotes. [repeats] keys repeat while held.+ */+enum class RemoteKey(val code: Int, val repeats: Boolean = false) {+ UP(19, repeats = true),+ DOWN(20, repeats = true),+ LEFT(21, repeats = true),+ RIGHT(22, repeats = true),+ OK(23),+ BACK(4),+ HOME(3),+ MENU(82),+ PLAY_PAUSE(85),+ VOLUME_UP(24, repeats = true),+ VOLUME_DOWN(25, repeats = true),+ MUTE(164),+ /** Sleep, not the power toggle: pressing it twice never wakes a TV the user meant to turn off. */+ SLEEP(223),+}++class Remote(private val session: AdbSession) {++ /** False when the TV answered with an error. Throws if the link is gone. */+ suspend fun press(key: RemoteKey): Boolean = session.shell("input keyevent ${key.code}").exitCode == 0++ /** Types [text] into whatever box has focus on the TV. Check [typeable] first. */+ suspend fun type(text: String): Boolean = session.shell(typeCommand(text)).exitCode == 0++ /**+ * Restarts the TV. adbd's `reboot:` service works for the shell user on stock builds; where a+ * build refuses it, `svc power reboot` goes through the power service instead. Returns false+ * only when the TV said no. A link that drops on the way counts as restarting.+ */+ suspend fun reboot(): Boolean {+ try {+ session.reboot()+ return true+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ // Refused, or the link went: the fallback tells which.+ }+ val r = try {+ session.shell("svc power reboot 2>&1")+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ return true+ }+ return r.exitCode == 0 && r.output.isBlank()+ }++ companion object {+ const val MAX_TEXT = 200++ /**+ * What `input text` can type: printable ASCII only (it has no key for anything else), and+ * never `%s`, which it reads as a space.+ */+ fun typeable(text: String): Boolean =+ text.isNotEmpty() && text.length <= MAX_TEXT && text.all { it in ' '..'~' } && "%s" !in text++ /** `input text` reads `%s` as a space, and the whole thing is single-quoted for the shell. */+ fun typeCommand(text: String): String {+ require(typeable(text)) { "input text can't type this" }+ return "input text " + shellQuote(text.replace(" ", "%s"))+ }+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.ktindex d1b251f..586435a 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt@@ -16,6 +16,9 @@ class FakeShell(val ran = mutableListOf<String>()var closed = falsevar failWith: Exception? = null+ var rebooted = false+ /** Thrown by [reboot], like Kadb does when adbd refuses the service. */+ var rebootFails: Exception? = nulloverride suspend fun shell(command: String): ShellResult {failWith?.let { throw it }@@ -31,6 +34,11 @@ class FakeShell(pushed[remotePath] = bytes}+ override suspend fun reboot() {+ rebootFails?.let { throw it }+ rebooted = true+ }+override fun close() { closed = true }}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/RemoteTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/RemoteTest.ktnew file mode 100644index 0000000..405dcce--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/RemoteTest.kt@@ -0,0 +1,82 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.test.runTest+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class RemoteTest {++ @Test fun keysSendTheirCode() = runTest {+ val sh = FakeShell()+ assertTrue(Remote(sh).press(RemoteKey.DOWN))+ assertTrue(Remote(sh).press(RemoteKey.SLEEP))+ assertEquals(listOf("input keyevent 20", "input keyevent 223"), sh.ran)+ }++ @Test fun keyRefusedByTheTvIsFalse() = runTest {+ val sh = FakeShell(mapOf("input keyevent" to ShellResult("Error: Unknown command", 1)))+ assertFalse(Remote(sh).press(RemoteKey.HOME))+ }++ @Test fun spacesBecomePercentS() {+ assertEquals("input text 'star%swars'", Remote.typeCommand("star wars"))+ }++ @Test fun percentBeforeASpaceStillTypesBoth() {+ // input text only rewrites "%s"; the leading % of "%%s" stays a plain %.+ assertEquals("input text '50%%soff'", Remote.typeCommand("50% off"))+ }++ @Test fun shellCharactersStayInsideTheQuotes() {+ assertEquals("input text '\$(reboot);`id`&&\"x\"|\\'", Remote.typeCommand("\$(reboot);`id`&&\"x\"|\\"))+ }++ @Test fun singleQuoteIsClosedEscapedAndReopened() {+ assertEquals("input text 'it'\\''s'", Remote.typeCommand("it's"))+ }++ @Test fun refusesWhatInputTextCannotType() {+ listOf("", "café", "line\nbreak", "tab\there", "emoji 🙂", "100%sure", "x".repeat(Remote.MAX_TEXT + 1))+ .forEach { assertFalse(Remote.typeable(it), it) }+ assertTrue(Remote.typeable("x".repeat(Remote.MAX_TEXT)))+ assertFailsWith<IllegalArgumentException> { Remote.typeCommand("café") }+ }++ @Test fun typeRunsTheQuotedCommand() = runTest {+ val sh = FakeShell()+ assertTrue(Remote(sh).type("hello there"))+ assertEquals(listOf("input text 'hello%sthere'"), sh.ran)+ }++ @Test fun rebootUsesTheAdbService() = runTest {+ val sh = FakeShell()+ assertTrue(Remote(sh).reboot())+ assertTrue(sh.rebooted)+ assertTrue(sh.ran.isEmpty())+ }++ @Test fun refusedServiceFallsBackToSvc() = runTest {+ val sh = FakeShell().apply { rebootFails = IllegalStateException("closed") }+ assertTrue(Remote(sh).reboot())+ assertEquals(listOf("svc power reboot 2>&1"), sh.ran)+ }++ @Test fun svcSayingNoIsFalse() = runTest {+ val sh = FakeShell(mapOf("svc power" to ShellResult("Failed to reboot: permission denied\n", 0)))+ .apply { rebootFails = IllegalStateException("closed") }+ assertFalse(Remote(sh).reboot())+ }++ @Test fun linkDroppingDuringFallbackCountsAsRestarting() = runTest {+ val sh = FakeShell().apply {+ rebootFails = IllegalStateException("closed")+ failWith = IOException("connection reset")+ }+ assertTrue(Remote(sh).reboot())+ }+}diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex e19411f..4f7436c 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -38,6 +38,8 @@ import app.tellyscope.ui.Copyimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceScreenimport app.tellyscope.ui.PermissionScreen+import app.tellyscope.ui.RemoteActions+import app.tellyscope.ui.RemoteScreenimport app.tellyscope.ui.ScanScreenimport app.tellyscope.ui.TellyscopeViewModelimport app.tellyscope.ui.theme.TellyscopeTheme@@ -119,6 +121,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {val notice by vm.notice.collectAsStateWithLifecycle()val snackbar = remember { SnackbarHostState() }var adding by rememberSaveable { mutableStateOf(false) }+ var remote by rememberSaveable { mutableStateOf(false) }// "*/*": file managers label .apks and .xapk bundles inconsistently, so a narrower type would grey them out.val pickApp = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { vm.pickedApp(it) }@@ -143,7 +146,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {}// A newly connected TV becomes the selection; leave the add flow then, not on tap.- LaunchedEffect(state.selectedId) { adding = false }+ LaunchedEffect(state.selectedId) { adding = false; remote = false }if (state.selected == null || adding) {BackHandler(enabled = adding) { adding = false }@@ -157,6 +160,18 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {onAddByIp = vm::addByIp,onBack = if (adding) ({ adding = false }) else null,)+ } else if (remote) {+ BackHandler { remote = false }+ RemoteScreen(+ state = state,+ snackbar = snackbar,+ actions = RemoteActions(+ press = vm::press,+ type = vm::type,+ reboot = vm::reboot,+ back = { remote = false },+ ),+ )} else {DeviceScreen(state = state,@@ -185,6 +200,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {cancelTransfer = vm::cancelTransfer,pickList = vm::pickList,disableSuggested = vm::disableSuggested,+ remote = { remote = true },),)}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 26c4b3e..57d1fe5 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -21,6 +21,8 @@ import app.tellyscope.adb.LanScannerimport app.tellyscope.adb.Parsersimport app.tellyscope.adb.Protectedimport app.tellyscope.adb.ProtectedReason+import app.tellyscope.adb.Remote+import app.tellyscope.adb.RemoteKeyimport com.flyfishxu.kadb.exception.AdbPairAuthExceptionimport com.flyfishxu.kadb.mdns.KadbMdnsAndroidimport kotlinx.coroutines.CancellationException@@ -366,6 +368,12 @@ class AdbDeviceSource(context: Context) : DeviceSource {return Resolved(index, entry, list, out.getOrNull(MATCH_KEYS.size)?.toIntOrNull())}+ override suspend fun press(deviceId: String, key: RemoteKey) = Remote(session(deviceId)).press(key)++ override suspend fun type(deviceId: String, text: String) = Remote(session(deviceId)).type(text)++ override suspend fun reboot(deviceId: String) = Remote(session(deviceId)).reboot()+/*** The history key for a TV, read from it once connected and saved with it. Until it has* answered (offline since install) the address stands in, and that history moves over whendiff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 8ac2915..6e67ba3 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -6,6 +6,7 @@ import app.tellyscope.adb.ApkInfoimport app.tellyscope.adb.InstallResultimport app.tellyscope.adb.InstalledVersionimport app.tellyscope.adb.Progress+import app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFileimport app.tellyscope.adb.TvFolderimport kotlinx.coroutines.flow.Flow@@ -88,4 +89,13 @@ interface DeviceSource {/** "Pick your TV": use list [listId] for this TV from now on. */suspend fun pickList(deviceId: String, listId: String)++ /** One remote key. False when the TV answered with an error; throws when it's gone. */+ suspend fun press(deviceId: String, key: RemoteKey): Boolean++ /** Types into the focused box on the TV. The caller checks [app.tellyscope.adb.Remote.typeable] first. */+ suspend fun type(deviceId: String, text: String): Boolean++ /** Restarts the TV. The link drops and reconnects on its own once the TV is back. False if the TV refused. */+ suspend fun reboot(deviceId: String): Boolean}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex e976772..2a0ebaf 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -6,6 +6,7 @@ import app.tellyscope.adb.ApkInfoimport app.tellyscope.adb.InstallResultimport app.tellyscope.adb.InstalledVersionimport app.tellyscope.adb.Progress+import app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFileimport app.tellyscope.adb.TvFolderimport java.io.File@@ -103,7 +104,15 @@ class FakeDeviceSource().takeIf { scenario == Scenario.Normal }.orEmpty().forEach { put(it.id, it) }}- override suspend fun known(): List<Device> = remembered.values.toList()+ /** TVs restarting, and when they answer again. */+ private val backAt = mutableMapOf<String, Long>()++ override suspend fun known(): List<Device> {+ backAt.entries.removeAll { (id, at) ->+ (at <= clock()).also { back -> if (back) remembered[id]?.let { remembered[id] = it.copy(state = DeviceState.Online, lastSeen = clock()) } }+ }+ return remembered.values.toList()+ }override suspend fun reconnect(deviceId: String) = Unit@@ -272,6 +281,23 @@ class FakeDeviceSource(override suspend fun pickList(deviceId: String, listId: String) = Unit+ override suspend fun press(deviceId: String, key: RemoteKey): Boolean {+ delay(60)+ return true+ }++ override suspend fun type(deviceId: String, text: String): Boolean {+ delay(150)+ return true+ }++ override suspend fun reboot(deviceId: String): Boolean {+ delay(300)+ remembered[deviceId]?.let { remembered[deviceId] = it.copy(state = DeviceState.Offline) }+ backAt[deviceId] = clock() + 20_000+ return true+ }+private companion object {val fakeList = DeviceList(id = "xgimi-horizon-pro",diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex 99f1363..923bd34 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -204,4 +204,32 @@ object Copy {const val CANCELLED_SAVE = "Cancelled. Nothing was saved."const val CANT_READ = "Couldn't read that file on your phone."const val FILES_LOST = "Couldn't read this folder. Check the TV is still connected."++ // Remote++ const val KEY_REFUSED = "The TV didn't take that key."+ const val TYPE_REFUSED = "The TV didn't take the text. Select a text box on the TV first, then send again."+ const val REMOTE_LOST = "Lost the TV. Check it's still on and connected."+ const val REBOOT_REFUSED = "The TV said no to restarting. Use its own remote or power button instead."+ const val REBOOT_IGNORED = "The TV didn't restart. Use its own remote or power button instead."+ const val REMOTE_OFFLINE = "The TV is offline. The remote works again once it reconnects."+ const val TYPE_HINT = "Select a text box on the TV, like a search box, then type here."++ fun cantType(text: String): String {+ val odd = text.firstOrNull { it !in ' '..'~' }+ return when {+ text.isEmpty() -> "Type something first."+ text.length > app.tellyscope.adb.Remote.MAX_TEXT -> "That's too long to send in one go. Send up to ${app.tellyscope.adb.Remote.MAX_TEXT} characters at a time."+ odd == '\n' || odd == '\t' -> "The TV can only take one line at a time."+ odd != null -> "The TV can only type plain letters, numbers and symbols, not \u201c$odd\u201d."+ else -> "The TV reads \u201c%s\u201d as a space, so it can't type that."+ }+ }++ const val REBOOT_TITLE = "Restart the TV?"+ const val REBOOT_TEXT = "Whatever is playing stops, and the TV takes a minute or two to come back. Tellyscope reconnects on its own when it's back."++ fun restarting(minutes: Long) =+ if (minutes < 3) "Tellyscope reconnects on its own when the TV is back, usually within a couple of minutes."+ else "Taking a while. Some TVs turn network debugging off when they restart. If it doesn't come back, turn it on again in the TV's Developer options."}diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex a2a26fb..d47e6a5 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -121,6 +121,7 @@ data class DeviceActions(val cancelTransfer: () -> Unit = {},val pickList: (String) -> Unit = {},val disableSuggested: (List<String>) -> Unit = {},+ val remote: () -> Unit = {},)@OptIn(ExperimentalMaterial3Api::class)@@ -164,6 +165,7 @@ fun DeviceScreen(TopAppBar(title = { DevicePicker(state, actions) },actions = {+ TextButton(onClick = actions.remote, enabled = !offline) { Text("Remote") }IconButton(onClick = { searching = true }, enabled = !offline) {Icon(Icons.Default.Search, contentDescription = "Search")}@@ -192,7 +194,10 @@ fun DeviceScreen(),)}- if (device.state == DeviceState.NotAllowed) {+ val restart = state.restarting[device.id]+ if (restart != null) {+ item { RestartingCard(restart, state.now) }+ } else if (device.state == DeviceState.NotAllowed) {item { NotAllowedCard(actions.reconnect) }} else if (offline) {item { OfflineCard(device, state.now, actions.reconnect) }diff --git a/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt b/app/src/main/java/app/tellyscope/ui/RemoteScreen.ktnew file mode 100644index 0000000..ef04cdd--- /dev/null+++ b/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt@@ -0,0 +1,327 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.ui++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.waitForUpOrCancellation+import androidx.compose.foundation.indication+import androidx.compose.foundation.interaction.MutableInteractionSource+import androidx.compose.foundation.interaction.PressInteraction+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.Spacer+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.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.material.icons.automirrored.filled.Send+import androidx.compose.material.icons.filled.Home+import androidx.compose.material.icons.filled.KeyboardArrowDown+import androidx.compose.material.icons.filled.KeyboardArrowLeft+import androidx.compose.material.icons.filled.KeyboardArrowRight+import androidx.compose.material.icons.filled.KeyboardArrowUp+import androidx.compose.material.icons.filled.Menu+import androidx.compose.material.icons.filled.PlayArrow+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.Icon+import androidx.compose.material3.IconButton+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.SnackbarHost+import androidx.compose.material3.SnackbarHostState+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TopAppBar+import androidx.compose.material3.ripple+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+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.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.onClick+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.unit.dp+import app.tellyscope.adb.RemoteKey+import app.tellyscope.data.DeviceState+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++data class RemoteActions(+ /** Suspends until the TV took the key, so a held key never queues up presses. */+ val press: suspend (RemoteKey) -> Unit = {},+ /** Returns why the text can't be typed, or null once it's sent. */+ val type: (String) -> String? = { null },+ val reboot: () -> Unit = {},+ val back: () -> Unit = {},+)++/** A held key repeats after this, then as fast as the TV takes them. */+private const val REPEAT_AFTER_MS = 400L++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun RemoteScreen(+ state: UiState,+ actions: RemoteActions,+ snackbar: SnackbarHostState = remember { SnackbarHostState() },+) {+ val device = state.selected ?: return+ val restart = state.restarting[device.id]+ val live = device.state == DeviceState.Online && restart == null+ var confirmReboot by rememberSaveable { mutableStateOf(false) }+ if (confirmReboot) RebootDialog(onRestart = { confirmReboot = false; actions.reboot() }, onDismiss = { confirmReboot = false })++ Scaffold(+ snackbarHost = { SnackbarHost(snackbar) },+ topBar = {+ TopAppBar(+ title = { Text("Remote") },+ navigationIcon = {+ IconButton(onClick = actions.back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to the TV's page") }+ },+ )+ },+ ) { pad ->+ Column(+ Modifier.fillMaxSize().padding(pad).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(20.dp),+ ) {+ when {+ restart != null -> RestartingCard(restart, state.now)+ device.state != DeviceState.Online -> Text(+ Copy.REMOTE_OFFLINE,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ Column(+ Modifier.alpha(if (live) 1f else 0.38f),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(20.dp),+ ) {+ DPad(live, actions.press)+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {+ RoundKey(RemoteKey.BACK, "Back", live, actions.press) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null) }+ RoundKey(RemoteKey.HOME, "Home", live, actions.press) { Icon(Icons.Default.Home, null) }+ RoundKey(RemoteKey.MENU, "Menu", live, actions.press) { Icon(Icons.Default.Menu, null) }+ }+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ PillKey(RemoteKey.VOLUME_DOWN, "Volume down", live, actions.press, Modifier.weight(1f)) { Text("Vol −") }+ PillKey(RemoteKey.MUTE, "Mute", live, actions.press, Modifier.weight(1f)) { Text("Mute") }+ PillKey(RemoteKey.VOLUME_UP, "Volume up", live, actions.press, Modifier.weight(1f)) { Text("Vol +") }+ }+ PillKey(RemoteKey.PLAY_PAUSE, "Play or pause", live, actions.press, Modifier.fillMaxWidth()) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Icon(Icons.Default.PlayArrow, null)+ Spacer(Modifier.width(8.dp))+ Text("Play / Pause")+ }+ }+ Keyboard(live, actions.type)+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ val scope = rememberCoroutineScope()+ OutlinedButton(onClick = { scope.launch { actions.press(RemoteKey.SLEEP) } }, enabled = live, modifier = Modifier.weight(1f)) {+ Text("Sleep")+ }+ OutlinedButton(onClick = { confirmReboot = true }, enabled = live, modifier = Modifier.weight(1f)) {+ Text("Restart TV")+ }+ }+ }+ }+ }+}++/** The four arrows around a big OK, shaped like the remote in the user's other hand. */+@Composable+private fun DPad(enabled: Boolean, press: suspend (RemoteKey) -> Unit) {+ Surface(Modifier.size(272.dp), shape = CircleShape, color = MaterialTheme.colorScheme.surfaceContainerHigh) {+ Box {+ val arrow = Modifier.size(80.dp)+ val tint = MaterialTheme.colorScheme.onSurface+ KeySurface(RemoteKey.UP, "Up", enabled, press, CircleShape, Color.Transparent, arrow.align(Alignment.TopCenter)) {+ Icon(Icons.Default.KeyboardArrowUp, null, Modifier.size(40.dp), tint = tint)+ }+ KeySurface(RemoteKey.DOWN, "Down", enabled, press, CircleShape, Color.Transparent, arrow.align(Alignment.BottomCenter)) {+ Icon(Icons.Default.KeyboardArrowDown, null, Modifier.size(40.dp), tint = tint)+ }+ KeySurface(RemoteKey.LEFT, "Left", enabled, press, CircleShape, Color.Transparent, arrow.align(Alignment.CenterStart)) {+ Icon(Icons.Default.KeyboardArrowLeft, null, Modifier.size(40.dp), tint = tint)+ }+ KeySurface(RemoteKey.RIGHT, "Right", enabled, press, CircleShape, Color.Transparent, arrow.align(Alignment.CenterEnd)) {+ Icon(Icons.Default.KeyboardArrowRight, null, Modifier.size(40.dp), tint = tint)+ }+ KeySurface(+ RemoteKey.OK, "OK", enabled, press, CircleShape, MaterialTheme.colorScheme.primary,+ Modifier.size(112.dp).align(Alignment.Center),+ ) {+ Text("OK", style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onPrimary)+ }+ }+ }+}++@Composable+private fun RoundKey(key: RemoteKey, label: String, enabled: Boolean, press: suspend (RemoteKey) -> Unit, icon: @Composable () -> Unit) {+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {+ KeySurface(key, label, enabled, press, CircleShape, MaterialTheme.colorScheme.secondaryContainer, Modifier.size(64.dp), icon)+ Text(label, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+}++@Composable+private fun PillKey(+ key: RemoteKey,+ label: String,+ enabled: Boolean,+ press: suspend (RemoteKey) -> Unit,+ modifier: Modifier = Modifier,+ content: @Composable () -> Unit,+) = KeySurface(key, label, enabled, press, MaterialTheme.shapes.extraLarge, MaterialTheme.colorScheme.secondaryContainer, modifier.height(56.dp), content)++/**+ * One remote key. Not a Button: a held [RemoteKey.repeats] key has to keep sending until the+ * finger lifts, and each repeat waits for the TV to take the last one so nothing piles up.+ */+@Composable+private fun KeySurface(+ key: RemoteKey,+ label: String,+ enabled: Boolean,+ press: suspend (RemoteKey) -> Unit,+ shape: Shape,+ color: Color,+ modifier: Modifier = Modifier,+ content: @Composable () -> Unit,+) {+ val scope = rememberCoroutineScope()+ val haptic = LocalHapticFeedback.current+ val interactions = remember { MutableInteractionSource() }+ Surface(+ shape = shape,+ color = color,+ modifier = modifier+ .clip(shape)+ .indication(interactions, ripple())+ .semantics {+ role = Role.Button+ contentDescription = label+ if (enabled) onClick { scope.launch { press(key) }; true }+ }+ .pointerInput(key, enabled) {+ if (!enabled) return@pointerInput+ awaitEachGesture {+ val down = awaitFirstDown()+ val p = PressInteraction.Press(down.position)+ interactions.tryEmit(p)+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)+ var held = true+ scope.launch {+ press(key)+ if (!key.repeats) return@launch+ delay(REPEAT_AFTER_MS)+ while (held) press(key)+ }+ waitForUpOrCancellation()+ held = false+ interactions.tryEmit(PressInteraction.Release(p))+ }+ },+ ) {+ Box(contentAlignment = Alignment.Center) { content() }+ }+}++@Composable+private fun Keyboard(enabled: Boolean, type: (String) -> String?) {+ var text by rememberSaveable { mutableStateOf("") }+ var error by rememberSaveable { mutableStateOf<String?>(null) }+ fun send() {+ error = type(text)+ if (error == null) text = ""+ }+ OutlinedTextField(+ value = text,+ onValueChange = { text = it; error = null },+ enabled = enabled,+ label = { Text("Type on the TV") },+ supportingText = { Text(error ?: Copy.TYPE_HINT) },+ isError = error != null,+ singleLine = true,+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),+ keyboardActions = KeyboardActions(onSend = { send() }),+ trailingIcon = {+ IconButton(onClick = ::send, enabled = enabled && text.isNotEmpty()) {+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send to the TV")+ }+ },+ modifier = Modifier.fillMaxWidth(),+ )+}++@Composable+fun RebootDialog(onRestart: () -> Unit, onDismiss: () -> Unit) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(Copy.REBOOT_TITLE) },+ text = { Text(Copy.REBOOT_TEXT) },+ confirmButton = { Button(onClick = onRestart) { Text("Restart") } },+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },+ )+}++/** Shown instead of the offline card while a TV restarts: it's expected, not an error. */+@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun RestartingCard(restart: Restart, now: Long) {+ Card(+ Modifier.fillMaxWidth(),+ colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh),+ ) {+ Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {+ LoadingIndicator(Modifier.size(48.dp))+ Spacer(Modifier.width(12.dp))+ Column(Modifier.weight(1f)) {+ Text("Restarting", style = MaterialTheme.typography.titleSmall)+ Text(Copy.restarting((now - restart.since) / 60_000), style = MaterialTheme.typography.bodyMedium)+ }+ }+ }+}diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex cbd9ad1..cb6a648 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -9,6 +9,8 @@ import app.tellyscope.adb.InstallKindimport app.tellyscope.adb.InstallResultimport app.tellyscope.adb.InstalledVersionimport app.tellyscope.adb.Progress+import app.tellyscope.adb.Remote+import app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFileimport app.tellyscope.adb.TvFolderimport app.tellyscope.adb.installKind@@ -36,6 +38,8 @@ import kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withTimeoutOrNull/** Per-row connect state on the scan screen. */@@ -107,10 +111,15 @@ data class UiState(val device: DeviceUi = DeviceUi(),val query: String = "",val now: Long = System.currentTimeMillis(),+ /** TVs asked to restart, by id. */+ val restarting: Map<String, Restart> = emptyMap(),) {val selected: Device? get() = devices.firstOrNull { it.id == selectedId }}+/** A restart in progress: [down] once the TV has dropped, so its coming back can be told apart from not having left. */+data class Restart(val since: Long, val down: Boolean = false)+/** [DeviceUi.busy] value while "Restore everything" runs. */const val RESTORING = "restore"@@ -138,6 +147,9 @@ class TellyscopeViewModel(/** Last stats per TV, so an offline page shows where it stood instead of blanks. Lives as long as the app. */private val lastSnapshot = mutableMapOf<String, Snapshot>()+ /** Keys go out one at a time, in the order pressed. */+ private val keys = Mutex()+private var scanJob: Job? = nullprivate var sideloadJob: Job? = nullprivate var transferJob: Job? = null@@ -290,7 +302,7 @@ class TellyscopeViewModel(private suspend fun refreshDevices() {val known = source.known()val before = _state.value.selected?.state- _state.update { it.copy(devices = known) }+ _state.update { s -> s.copy(devices = known, restarting = restarts(s.restarting, known)) }val now = _state.value.selected ?: returnif (now.state == DeviceState.Online && before != DeviceState.Online) select(now.id)}@@ -605,8 +617,84 @@ class TellyscopeViewModel(}}+ /**+ * Sends one key and waits for the TV to take it. The remote screen holds a D-pad key by+ * calling this in a loop. A lost TV shows once, not once per repeat.+ */+ suspend fun press(key: RemoteKey) {+ val id = _state.value.selectedId ?: return+ keys.withLock {+ try {+ if (!source.press(id, key)) _notice.value = Copy.KEY_REFUSED+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ _notice.value = Copy.REMOTE_LOST+ }+ }+ }++ /** Types on the TV. Returns why it can't, or null once it's on its way. */+ fun type(text: String): String? {+ if (!Remote.typeable(text)) return Copy.cantType(text)+ val id = _state.value.selectedId ?: return null+ viewModelScope.launch {+ keys.withLock {+ _notice.value = try {+ if (source.type(id, text)) null else Copy.TYPE_REFUSED+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ Copy.REMOTE_LOST+ }+ }+ }+ return null+ }++ fun reboot() {+ val id = _state.value.selectedId ?: return+ viewModelScope.launch {+ val ok = try {+ source.reboot(id)+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ _notice.value = Copy.REMOTE_LOST+ return@launch+ }+ if (ok) _state.update { it.copy(restarting = it.restarting + (id to Restart(clock()))) }+ else _notice.value = Copy.REBOOT_REFUSED+ }+ }++ /**+ * A restart ends when the TV is back online after dropping, or stops at a refusal. One still+ * online after [RESTART_GRACE_MS] never went down, so the TV ignored the request.+ */+ private fun restarts(current: Map<String, Restart>, known: List<Device>): Map<String, Restart> {+ val now = clock()+ return current.mapNotNull { (id, r) ->+ val state = known.firstOrNull { it.id == id }?.state ?: return@mapNotNull null+ when {+ state == DeviceState.Online && r.down -> null+ state == DeviceState.Online && now - r.since > RESTART_GRACE_MS -> {+ _notice.value = Copy.REBOOT_IGNORED+ null+ }+ state == DeviceState.Online -> id to r+ state == DeviceState.NotAllowed || state == DeviceState.NeedsPairing -> null+ else -> id to r.copy(down = true)+ }+ }.toMap()+ }+private fun setRow(ip: String, row: RowState) =_state.update { it.copy(scan = it.scan.copy(rows = it.scan.rows + (ip to row))) }+ private companion object {+ const val RESTART_GRACE_MS = 60_000L+ }+private fun ipKey(ip: String) = ip.split('.').fold(0L) { acc, o -> acc * 256 + (o.toLongOrNull() ?: 0) }}diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex fe4c6ee..112e0f6 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -40,6 +40,10 @@ import app.tellyscope.ui.FilesBlockimport app.tellyscope.ui.FilesUiimport app.tellyscope.ui.RestoreDialogimport app.tellyscope.ui.PermissionScreen+import app.tellyscope.ui.RebootDialog+import app.tellyscope.ui.RemoteActions+import app.tellyscope.ui.RemoteScreen+import app.tellyscope.ui.Restartimport app.tellyscope.ui.RowStateimport app.tellyscope.ui.ScanScreenimport app.tellyscope.ui.ScanUi@@ -295,4 +299,20 @@ class ScreenshotTest {}@Test fun restore() = shot("11_restore", screen = true) { RestoreDialog(2, {}, {}) }++ @Test fun remote() = shot("12_remote") { RemoteScreen(deviceState(), RemoteActions()) }++ @Test fun remote_dark() = shot("12_remote", dark = true) { RemoteScreen(deviceState(), RemoteActions()) }++ @Test fun remote_restarting() {+ val state = deviceState().let { it.copy(restarting = mapOf(it.selectedId!! to Restart(now - 25_000, down = true))) }+ shot("13_remote_restarting") { RemoteScreen(state, RemoteActions()) }+ }++ @Test fun device_restarting() {+ val state = deviceState().let { it.copy(restarting = mapOf(it.selectedId!! to Restart(now - 200_000, down = true))) }+ shot("14_device_restarting") { DeviceScreen(state, DeviceActions()) }+ }++ @Test fun reboot() = shot("15_reboot", screen = true) { RebootDialog({}, {}) }}