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.
Bring the Remote back, with keys and text sent by a helper that stays up
jesse-agent-362900f8a99b3ca
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ec7fcc6..fb7d187 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ until this file has a section for its version.## Unreleased+- **New:** The Remote is back, and keys land in about 50 ms.+- **Improved:** Typing from the Remote takes a fraction of a second.- **Fixed:** Apps no longer crashes on TVs that list an app twice. [#109](../../pull/109)## 0.6.3 — 2026-10-25diff --git a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.ktindex 8c020bf..bb5afe1 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt@@ -1,6 +1,8 @@// SPDX-License-Identifier: GPL-3.0-onlypackage app.tellyscope.adb+import okio.BufferedSink+import okio.BufferedSourceimport okio.Sinkimport okio.Sourceimport java.io.File@@ -34,4 +36,13 @@ interface AdbSession : AdbShell, AdbTransfer, AutoCloseable {/** Asks adbd to restart the device (the `reboot:` service, what `adb reboot` uses). */suspend fun reboot()++ /** Starts [command] with its stdin and stdout left open, for a helper that stays up. Throws [java.io.IOException] if the link is gone. */+ suspend fun exec(command: String): AdbPipe+}++/** A running command's stdin and stdout, with no terminal in between. Closing it ends the command's stdin. */+interface AdbPipe : AutoCloseable {+ val stdin: BufferedSink+ val stdout: BufferedSource}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.ktindex 3aec841..9bcf138 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt@@ -192,5 +192,16 @@ internal class KadbSession(private val kadb: Kadb) : AdbSession {runInterruptible(Dispatchers.IO) { kadb.open("reboot:").close() }}+ /** `exec:` is adbd's raw service: no pty, so bytes go both ways untouched. */+ override suspend fun exec(command: String): AdbPipe {+ val stream = runInterruptible(Dispatchers.IO) { kadb.open("exec:$command") }+ return object : AdbPipe {+ // Already buffered: `.buffer()` here would be their internal Buffer, cut off from the TV.+ override val stdin = stream.sink+ override val stdout = stream.source+ override fun close() = stream.close()+ }+ }+override fun close() = kadb.close()}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/KeyHelper.kt b/adb/src/main/kotlin/app/tellyscope/adb/KeyHelper.ktnew file mode 100644index 0000000..d0789d2--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/KeyHelper.kt@@ -0,0 +1,112 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.runInterruptible+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import kotlin.time.Duration.Companion.seconds++/**+ * The remote's keys, sent by the helper dex (`app/src/helper`, `Keys`) kept running on the TV.+ * `input keyevent` starts a new VM for every key, and that start was the remote's lag; the helper+ * pays it once, on the first key. [dex] is the helper jar bundled in the app's assets.+ *+ * A helper that can't start (push refused, `app_process` blocked by the OEM) or stops answering is+ * not tried again on this [session]: [press] returns null and the caller sends `input keyevent`.+ */+class KeyHelper(val session: AdbSession, private val dex: ByteArray) : AutoCloseable {+ private val lock = Mutex()+ private var pipe: AdbPipe? = null+ private var failed = false++ /**+ * Sends [code] and waits for the TV to take it. True or false is the TV's answer; null means+ * the helper isn't running and the key wasn't sent. Throws if the link is gone.+ */+ suspend fun press(code: Int): Boolean? = send("$code")++ /** Types [text], already checked with [Remote.typeable]; answers like [press]. */+ suspend fun type(text: String): Boolean? = send("t$text")++ private suspend fun send(line: String): Boolean? = lock.withLock {+ if (failed) return null+ val p = pipe ?: start() ?: return null+ val answer = try {+ withTimeoutOrNull(ANSWER_TIMEOUT) {+ runInterruptible(Dispatchers.IO) {+ p.stdin.writeUtf8("$line\n").flush()+ // A helper that exited answers "", not null: null is the timeout below.+ p.stdout.readUtf8Line() ?: ""+ }+ }+ } catch (e: CancellationException) {+ // Its answer would be read as the next key's; start a fresh helper next time.+ drop()+ throw e+ } catch (e: Exception) {+ drop()+ failed = true+ // A link that is gone fails the caller's fallback too, so the user still sees it.+ return null+ }+ when (answer) {+ "1" -> true+ "0" -> false+ null -> {+ // Timed out: the key may still land, so sending it again could press it twice.+ drop()+ failed = true+ false+ }+ else -> {+ drop()+ failed = true+ null+ }+ }+ }++ private suspend fun start(): AdbPipe? {+ var p: AdbPipe? = null+ try {+ session.push(dex, PATH)+ val started = session.exec("CLASSPATH=$PATH app_process / $MAIN $PATH 2>/dev/null; rm -f $PATH")+ p = started+ val first = withTimeoutOrNull(START_TIMEOUT) { runInterruptible(Dispatchers.IO) { started.stdout.readUtf8Line() } }+ if (first == READY) return started.also { pipe = it }+ } catch (e: CancellationException) {+ p?.close()+ throw e+ } catch (_: Exception) {+ // Falls through to the fallback.+ }+ p?.close()+ failed = true+ // The shell line removes it too; this covers a run that never got that far.+ withContext(NonCancellable) { runCatching { session.shell("rm -f $PATH") } }+ return null+ }++ private fun drop() {+ pipe?.let { runCatching { it.close() } }+ pipe = null+ }++ /** Ends the helper: its stdin closes and it exits. */+ override fun close() = drop()++ companion object {+ const val PATH = "/data/local/tmp/tellyscope-keys.jar"+ const val MAIN = "app.tellyscope.helper.Keys"+ const val READY = "ready"+ /** A VM start on a slow TV; the label helper starts the same way. */+ val START_TIMEOUT = 15.seconds+ /** Past Android's own 5 s input dispatch timeout, so a key the TV dropped shows as dropped. */+ val ANSWER_TIMEOUT = 6.seconds+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt b/adb/src/main/kotlin/app/tellyscope/adb/Remote.ktindex 630964e..7ec79d0 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Remote.kt@@ -24,10 +24,14 @@ enum class RemoteKey(val code: Int, val repeats: Boolean = false) {SLEEP(223),}-class Remote(private val session: AdbSession) {+class Remote(private val session: AdbSession, private val keys: KeyHelper? = null) {- /** 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+ /**+ * False when the TV answered with an error. Throws if the link is gone. Goes through [keys]+ * while its helper runs, and `input keyevent` when it can't.+ */+ suspend fun press(key: RemoteKey): Boolean =+ keys?.press(key.code) ?: (session.shell("input keyevent ${key.code}").exitCode == 0)/*** Opens the TV's own system update screen. Some builds have none, and older `am` reports a@@ -38,8 +42,8 @@ class Remote(private val session: AdbSession) {return r.exitCode == 0 && !r.output.contains("Error")}- /** 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+ /** Types [text] into whatever box has focus on the TV, through [keys] like [press]. Check [typeable] first. */+ suspend fun type(text: String): Boolean = keys?.type(text) ?: (session.shell(typeCommand(text)).exitCode == 0)/*** Restarts the TV. adbd's `reboot:` service works for the shell user on stock builds; where adiff --git a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.ktindex 2ce3971..085d525 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt@@ -7,6 +7,7 @@ import okio.Sourceimport okio.bufferimport okio.sourceimport java.io.File+import java.io.IOException/** Answers by the first matching command prefix and records what ran. */class FakeShell(@@ -42,6 +43,24 @@ class FakeShell(rebooted = true}+ /** The helper's whole stdout for the next [exec], read as it goes; null refuses the exec. */+ var execOutput: String? = null+ val execs = mutableListOf<String>()+ /** Everything written to an [exec]'s stdin. */+ val execInput = Buffer()+ var execClosed = false++ override suspend fun exec(command: String): AdbPipe {+ failWith?.let { throw it }+ execs += command+ val out = Buffer().writeUtf8(execOutput ?: throw IOException("exec refused"))+ return object : AdbPipe {+ override val stdin = execInput+ override val stdout = out+ override fun close() { execClosed = true }+ }+ }+override fun close() { closed = true }}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/KeyHelperTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/KeyHelperTest.ktnew file mode 100644index 0000000..57e4146--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/KeyHelperTest.kt@@ -0,0 +1,79 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * runBlocking, not runTest: the helper's reads run on a real IO thread under real timeouts, and+ * runTest's virtual clock would fire those timeouts before the fake pipe answers.+ */+class KeyHelperTest {+ private val dex = byteArrayOf(1, 2, 3)++ @Test fun startsOnceAndSendsEachCode() = runBlocking {+ val sh = FakeShell().apply { execOutput = "ready\n1\n1\n" }+ val keys = KeyHelper(sh, dex)+ assertEquals(true, keys.press(20))+ assertEquals(true, keys.press(23))+ assertContentEquals(dex, sh.pushed[KeyHelper.PATH])+ val run = sh.execs.single()+ assertTrue(run.startsWith("CLASSPATH=${KeyHelper.PATH} app_process / ${KeyHelper.MAIN} ${KeyHelper.PATH} "))+ assertTrue(run.endsWith("rm -f ${KeyHelper.PATH}"))+ assertEquals("20\n23\n", sh.execInput.readUtf8())+ }++ @Test fun textGoesOnItsOwnLine() = runBlocking {+ val sh = FakeShell().apply { execOutput = "ready\n1\n1\n" }+ val keys = KeyHelper(sh, dex)+ assertEquals(true, keys.press(20))+ assertEquals(true, keys.type(" hello tv "))+ assertEquals("20\nt hello tv \n", sh.execInput.readUtf8())+ }++ @Test fun tvRefusingAKeyIsFalse() = runBlocking {+ val sh = FakeShell().apply { execOutput = "ready\n0\n" }+ assertEquals(false, KeyHelper(sh, dex).press(4))+ }++ @Test fun helperThatNeverSaysReadyIsNotTriedAgain() = runBlocking {+ // An OEM that blocks app_process for the shell user: the run ends and prints nothing.+ val sh = FakeShell().apply { execOutput = "" }+ val keys = KeyHelper(sh, dex)+ assertNull(keys.press(20))+ assertNull(keys.press(20))+ assertEquals(1, sh.execs.size)+ assertTrue(sh.execClosed)+ assertEquals("rm -f ${KeyHelper.PATH}", sh.ran.last())+ }++ @Test fun refusedExecFallsBack() = runBlocking {+ val sh = FakeShell()+ assertNull(KeyHelper(sh, dex).press(20))+ assertEquals("rm -f ${KeyHelper.PATH}", sh.ran.last())+ }++ @Test fun helperThatDiesHandsBackToTheFallback() = runBlocking {+ val sh = FakeShell().apply { execOutput = "ready\n1\n" }+ val keys = KeyHelper(sh, dex)+ assertEquals(true, keys.press(20))+ assertNull(keys.press(20))+ assertNull(keys.press(20))+ assertEquals(1, sh.execs.size)+ assertTrue(sh.execClosed)+ }++ @Test fun closeEndsTheHelper() = runBlocking {+ val sh = FakeShell().apply { execOutput = "ready\n1\n" }+ val keys = KeyHelper(sh, dex)+ keys.press(20)+ assertFalse(sh.execClosed)+ keys.close()+ assertTrue(sh.execClosed)+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/RemoteTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/RemoteTest.ktindex 405dcce..e444a19 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/RemoteTest.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/RemoteTest.kt@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-3.0-onlypackage app.tellyscope.adb+import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.test.runTestimport java.io.IOExceptionimport kotlin.test.Test@@ -18,6 +19,32 @@ class RemoteTest {assertEquals(listOf("input keyevent 20", "input keyevent 223"), sh.ran)}+ @Test fun keysGoThroughTheHelperWhileItRuns() = runBlocking { // see KeyHelperTest+ val sh = FakeShell().apply { execOutput = "ready\n1\n" }+ assertTrue(Remote(sh, KeyHelper(sh, byteArrayOf(1))).press(RemoteKey.LEFT))+ assertEquals("21\n", sh.execInput.readUtf8())+ assertTrue(sh.ran.none { it.startsWith("input") })+ }++ @Test fun textGoesThroughTheHelperWhileItRuns() = runBlocking { // see KeyHelperTest+ val sh = FakeShell().apply { execOutput = "ready\n1\n" }+ assertTrue(Remote(sh, KeyHelper(sh, byteArrayOf(1))).type("hello tv"))+ assertEquals("thello tv\n", sh.execInput.readUtf8())+ assertTrue(sh.ran.none { it.startsWith("input") })+ }++ @Test fun textFallsBackToInputWhenTheHelperCannotStart() = runBlocking { // see KeyHelperTest+ val sh = FakeShell().apply { execOutput = "" }+ assertTrue(Remote(sh, KeyHelper(sh, byteArrayOf(1))).type("hi"))+ assertEquals(Remote.typeCommand("hi"), sh.ran.last())+ }++ @Test fun keysFallBackToInputWhenTheHelperCannotStart() = runBlocking { // see KeyHelperTest+ val sh = FakeShell().apply { execOutput = "" }+ assertTrue(Remote(sh, KeyHelper(sh, byteArrayOf(1))).press(RemoteKey.HOME))+ assertEquals("input keyevent 3", sh.ran.last())+ }+@Test fun keyRefusedByTheTvIsFalse() = runTest {val sh = FakeShell(mapOf("input keyevent" to ShellResult("Error: Unknown command", 1)))assertFalse(Remote(sh).press(RemoteKey.HOME))diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 418a5b3..6ffcfc3 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -78,8 +78,9 @@ android {}}-// The label helper (src/helper): plain Java against android.jar, dexed on its own and shipped as-// an asset. It runs on the TV through app_process, so it must not touch app code or libraries.+// The TV helpers (src/helper: Labels, and the remote's Keys): plain Java against android.jar, dexed on+// their own and shipped as one asset. They run on the TV through app_process, so they must not touch+// app code or libraries.val compileLabelHelper by tasks.registering(JavaCompile::class) {source = fileTree("src/helper/java")classpath = files(androidComponents.sdkComponents.bootClasspath)diff --git a/app/src/helper/java/app/tellyscope/helper/Keys.java b/app/src/helper/java/app/tellyscope/helper/Keys.javanew file mode 100644index 0000000..fcef720--- /dev/null+++ b/app/src/helper/java/app/tellyscope/helper/Keys.java@@ -0,0 +1,91 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.helper;++import android.os.SystemClock;+import android.view.InputDevice;+import android.view.InputEvent;+import android.view.KeyCharacterMap;+import android.view.KeyEvent;++import java.io.BufferedReader;+import java.io.File;+import java.io.InputStreamReader;+import java.io.PrintStream;+import java.lang.reflect.Method;++/**+ * The remote's key sender. Runs on the TV as the shell user, through {@code app_process}, and stays+ * up for as long as the remote is open: {@code input keyevent} starts a fresh VM for every key,+ * which is most of a second on a slow TV. Reads one Android key code per line on stdin, injects a+ * press and release the way {@code input} does, and answers {@code 1} when the TV took both or+ * {@code 0} when it didn't. Prints {@code ready} first. Only key codes are read, so nothing typed+ * reaches a shell. The argument is the jar's own path, deleted once the helper is up; it exits at+ * the end of stdin. A line starting with {@code t} is text instead: the rest is typed the way+ * {@code input text} types it, one key press per character.+ */+public final class Keys {+ /** InputManager's INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH: answers once the focused app is done with it. */+ private static final int WAIT_FOR_FINISH = 2;++ public static void main(String[] args) throws Exception {+ Object manager;+ Method inject;+ try {+ // Android 14 moved injection to InputManagerGlobal; older builds have it on InputManager.+ Class<?> global = Class.forName("android.hardware.input.InputManagerGlobal");+ manager = global.getDeclaredMethod("getInstance").invoke(null);+ inject = global.getMethod("injectInputEvent", InputEvent.class, int.class);+ } catch (ClassNotFoundException e) {+ Class<?> im = Class.forName("android.hardware.input.InputManager");+ manager = im.getDeclaredMethod("getInstance").invoke(null);+ inject = im.getMethod("injectInputEvent", InputEvent.class, int.class);+ }+ if (args.length == 1) new File(args[0]).delete();++ PrintStream out = new PrintStream(System.out, false, "UTF-8");+ out.print("ready\n");+ out.flush();+ KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));+ for (String line; (line = in.readLine()) != null; ) {+ boolean ok;+ try {+ if (line.startsWith("t")) {+ out.print(type(manager, inject, keymap, line.substring(1)) ? "1\n" : "0\n");+ out.flush();+ continue;+ }+ int code = Integer.parseInt(line.trim());+ long now = SystemClock.uptimeMillis();+ ok = send(manager, inject, now, KeyEvent.ACTION_DOWN, code)+ && send(manager, inject, now, KeyEvent.ACTION_UP, code);+ } catch (Throwable t) {+ ok = false;+ }+ out.print(ok ? "1\n" : "0\n");+ out.flush();+ }+ }++ /** Null from getEvents means a character the keymap has no key for. */+ private static boolean type(Object manager, Method inject, KeyCharacterMap keymap, String text) {+ try {+ KeyEvent[] events = keymap.getEvents(text.toCharArray());+ if (events == null) return false;+ for (KeyEvent e : events) {+ KeyEvent now = KeyEvent.changeTimeRepeat(e, SystemClock.uptimeMillis(), 0);+ now.setSource(InputDevice.SOURCE_KEYBOARD);+ if (!(Boolean) inject.invoke(manager, now, WAIT_FOR_FINISH)) return false;+ }+ return true;+ } catch (Throwable t) {+ return false;+ }+ }++ private static boolean send(Object manager, Method inject, long downTime, int action, int code) throws Exception {+ KeyEvent e = new KeyEvent(downTime, SystemClock.uptimeMillis(), action, code, 0, 0,+ KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, InputDevice.SOURCE_KEYBOARD);+ return (Boolean) inject.invoke(manager, e, WAIT_FOR_FINISH);+ }+}diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex c3c963d..0d9f453 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -199,6 +199,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {)} else if (remote) {BackHandler { remote = false }+ DisposableEffect(Unit) { onDispose { vm.closeRemote() } }RemoteScreen(state = state,snackbar = snackbar,diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 176efb3..6047be2 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -22,6 +22,7 @@ import app.tellyscope.adb.ConnectionPromptimport app.tellyscope.adb.ConnectionRequestimport app.tellyscope.adb.Connectorimport app.tellyscope.adb.DeviceLink+import app.tellyscope.adb.KeyHelperimport app.tellyscope.adb.LabelHelperimport app.tellyscope.adb.LanScannerimport app.tellyscope.adb.NetworkStats@@ -87,6 +88,8 @@ class AdbDeviceSource(context: Context) : DeviceSource {private val names = NameBook(File(appContext.filesDir, "names.tsv"))/** Last label seen per package, so history entries read like the app list. */private val labels = ConcurrentHashMap<String, String>()+ /** The remote's key helper on each TV, while the remote is open. */+ private val keyHelpers = ConcurrentHashMap<String, KeyHelper>()private val helperDex by lazy { appContext.assets.open("label-helper.jar").use { it.readBytes() } }private val appNames = AppNames(File(appContext.filesDir, "app-names"))private val lists = DeviceLists(File(appContext.filesDir, "lists"))@@ -188,6 +191,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {override suspend fun forget(deviceId: String) {restored.await()watchers.remove(deviceId)?.cancel()+ keyHelpers.remove(deviceId)?.close()links.remove(deviceId)?.disconnect()hits.remove(deviceId)restoring -= deviceId@@ -550,9 +554,22 @@ class AdbDeviceSource(context: Context) : DeviceSource {return Resolved(index, match, list, out.getOrNull(MATCH_KEYS.size)?.toIntOrNull())}- override suspend fun press(deviceId: String, key: RemoteKey) = busy(deviceId) { Remote(session(deviceId)).press(key) }+ override suspend fun press(deviceId: String, key: RemoteKey) = busy(deviceId) { remote(deviceId).press(key) }- override suspend fun type(deviceId: String, text: String) = busy(deviceId) { Remote(session(deviceId)).type(text) }+ /** One helper per link: a reconnect brings a new session, and the old helper went with the old one. */+ private suspend fun remote(deviceId: String): Remote {+ val session = session(deviceId)+ val keys = keyHelpers.compute(deviceId) { _, k ->+ if (k?.session === session) k else KeyHelper(session, helperDex).also { k?.close() }+ }+ return Remote(session, keys)+ }++ override fun closeRemote() {+ keyHelpers.keys.toList().forEach { keyHelpers.remove(it)?.close() }+ }++ override suspend fun type(deviceId: String, text: String) = busy(deviceId) { remote(deviceId).type(text) }override suspend fun reboot(deviceId: String) = Remote(session(deviceId)).reboot()diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 53dc6a8..8d15393 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -113,6 +113,9 @@ interface DeviceSource {/** One remote key. False when the TV answered with an error; throws when it's gone. */suspend fun press(deviceId: String, key: RemoteKey): Boolean+ /** The remote screen closed: stop anything [press] left running on the TVs. */+ fun closeRemote() {}+/** Types into the focused box on the TV. The caller checks [app.tellyscope.adb.Remote.typeable] first. */suspend fun type(deviceId: String, text: String): Booleandiff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex 05e6a36..dc37cd3 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -114,9 +114,6 @@ data class DeviceActions(val showStats: (StatsProfile) -> Unit = {},)-/** Off while the remote is made faster: the device page hides its Remote button. */-internal const val REMOTE_ENABLED = false-/*** The TV's vitals in one small card: internal storage as a full bar, since it decides whether an* install fits, then CPU, RAM, temperature and network speed as plain numbers.diff --git a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt b/app/src/main/java/app/tellyscope/ui/DeviceTabs.ktindex 7aa5498..14817e9 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt@@ -223,7 +223,7 @@ fun DeviceTabsScreen(containerColor = lerp(MaterialTheme.colorScheme.surface, MaterialTheme.colorScheme.surfaceContainer, collapse),),actions = {- if (REMOTE_ENABLED) TextButton(onClick = actions.remote, enabled = !offline) { Text("Remote") }+ TextButton(onClick = actions.remote, enabled = !offline) { Text("Remote") }AppMenu(state, actions)},)diff --git a/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt b/app/src/main/java/app/tellyscope/ui/RemoteScreen.ktindex 670cbe5..efe7f67 100644--- a/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/RemoteScreen.kt@@ -81,7 +81,6 @@ import app.tellyscope.adb.RemoteKeyimport app.tellyscope.data.DeviceStateimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch-import kotlinx.coroutines.yielddata class RemoteActions(/** Suspends until the TV answers, so a held key never queues up presses. False when it didn't take the key. */@@ -92,18 +91,24 @@ data class RemoteActions(val back: () -> Unit = {},)-/** A held key repeats after this, then as fast as the TV takes them. */+/** A held key repeats after this, then every [REPEAT_EVERY_MS], or slower if the TV is slower. */private const val REPEAT_AFTER_MS = 400L+/** Android's own key repeat rate. The key helper answers in about 20 ms, which would skip whole lists. */+internal const val REPEAT_EVERY_MS = 50L+/*** One press, then repeats while [held] for keys that repeat. Stops at the first key the TV didn't- * take (refused, dropped, or no TV selected), and yields between repeats, so a press that answers- * at once can't keep the main thread busy.+ * take (refused, dropped, or no TV selected).*/internal suspend fun repeatWhileHeld(key: RemoteKey, held: () -> Boolean, press: suspend (RemoteKey) -> Boolean) {if (!press(key) || !key.repeats) returndelay(REPEAT_AFTER_MS)- while (held() && press(key)) yield()+ var last = System.nanoTime()+ while (held() && press(key)) {+ delay((REPEAT_EVERY_MS - (System.nanoTime() - last) / 1_000_000).coerceAtLeast(0))+ last = System.nanoTime()+ }}@OptIn(ExperimentalMaterial3Api::class)diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex b46c081..72baf1b 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -915,6 +915,8 @@ class TellyscopeViewModel(}}+ fun closeRemote() = source.closeRemote()+/** 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)diff --git a/app/src/test/java/app/tellyscope/DnsRollbackTest.kt b/app/src/test/java/app/tellyscope/DnsRollbackTest.ktindex bc56c3a..59aa593 100644--- a/app/src/test/java/app/tellyscope/DnsRollbackTest.kt+++ b/app/src/test/java/app/tellyscope/DnsRollbackTest.kt@@ -2,6 +2,7 @@package app.tellyscope+import app.tellyscope.adb.AdbPipeimport app.tellyscope.adb.AdbSessionimport app.tellyscope.adb.RemoteEntryimport app.tellyscope.adb.ShellResult@@ -32,6 +33,7 @@ private class NoDnsTv(private val failing: Set<Int>) : AdbSession {override suspend fun push(bytes: ByteArray, remotePath: String) = Unitoverride suspend fun reboot() = Unit+ override suspend fun exec(command: String): AdbPipe = throw IOException("no exec")override fun install(source: Source, size: Long, vararg options: String) = Unitoverride fun installMultiple(apks: List<File>, vararg options: String) = Unitoverride fun push(source: Source, remotePath: String, mode: Int, lastModifiedMs: Long) = Unitdiff --git a/app/src/test/java/app/tellyscope/RemoteRepeatTest.kt b/app/src/test/java/app/tellyscope/RemoteRepeatTest.ktindex d84a1fe..ebed9b6 100644--- a/app/src/test/java/app/tellyscope/RemoteRepeatTest.kt+++ b/app/src/test/java/app/tellyscope/RemoteRepeatTest.kt@@ -3,6 +3,7 @@package app.tellyscopeimport app.tellyscope.adb.RemoteKey+import app.tellyscope.ui.REPEAT_EVERY_MSimport app.tellyscope.ui.repeatWhileHeldimport kotlinx.coroutines.test.runTestimport org.junit.Assert.assertEquals@@ -29,6 +30,13 @@ class RemoteRepeatTest {assertEquals(5, presses)}+ @Test fun aKeyTheTvTakesAtOnceRepeatsAtAndroidsRate() = runTest {+ var presses = 0+ // Held for one second after the first repeat: the TV answering at once must not skip a list.+ repeatWhileHeld(RemoteKey.DOWN, held = { testScheduler.currentTime < 400 + 1000 }) { presses++; true }+ assertEquals(1 + 1000 / REPEAT_EVERY_MS.toInt(), presses)+ }+@Test fun okNeverRepeats() = runTest {var presses = 0repeatWhileHeld(RemoteKey.OK, held = { true }) { presses++; true }diff --git a/cli/src/main/kotlin/app/tellyscope/cli/Main.kt b/cli/src/main/kotlin/app/tellyscope/cli/Main.ktindex 21f2194..629c032 100644--- a/cli/src/main/kotlin/app/tellyscope/cli/Main.kt+++ b/cli/src/main/kotlin/app/tellyscope/cli/Main.kt@@ -1,9 +1,16 @@// SPDX-License-Identifier: GPL-3.0-onlypackage app.tellyscope.cli+import app.tellyscope.adb.Action+import app.tellyscope.adb.ActionResult+import app.tellyscope.adb.Actions+import app.tellyscope.adb.ConnectResultimport app.tellyscope.adb.Connectorimport app.tellyscope.adb.DeviceLink+import app.tellyscope.adb.KeyHelperimport app.tellyscope.adb.LanScanner+import app.tellyscope.adb.Remote+import app.tellyscope.adb.RemoteKeyimport com.flyfishxu.kadb.mdns.KadbMdnsJvmimport kotlinx.coroutines.flow.collectimport kotlinx.coroutines.flow.filterNotNull@@ -17,8 +24,12 @@ import java.io.File* scan list ADB devices* stats <host> [port] connect (press Allow on the TV) and print live stats* pair <host> <port> <code>+ * remote <host> <port> <helper.jar> <step>...+ * run each step and print how long the TV took: a RemoteKey name (sent+ * through the key helper), input=<KEY> (through `input keyevent`, to+ * compare), text=<text>, open=<package>, or hold=<KEY>:<ms>*/-fun main(args: Array<String>) = runBlocking {+fun main(args: Array<String>): Unit = runBlocking {Connector.init(File(System.getProperty("user.home"), ".tellyscope/adbkey.pem"))when (args.firstOrNull()) {"scan" -> LanScanner(KadbMdnsJvm()).scan(LanScanner.lanHosts()).collect { println("${it.host}:${it.port} ${it.kind} ${it.name ?: "-"}") }@@ -29,6 +40,31 @@ fun main(args: Array<String>) = runBlocking {launch { link.stats.filterNotNull().onEach { println(it) }.collect() }link.connect()}- else -> println("usage: scan | stats <host> [port] | pair <host> <port> <code>")+ "remote" -> {+ val session = (Connector.connect(args[1], args[2].toInt()) as ConnectResult.Online).session+ KeyHelper(session, File(args[3]).readBytes()).use { helper ->+ val remote = Remote(session, helper)+ for (step in args.drop(4)) {+ val start = System.nanoTime()+ val (what, ok) = when {+ step.startsWith("text=") -> "type" to remote.type(step.removePrefix("text="))+ step.startsWith("open=") -> "open" to (Actions(session).run(Action.OPEN, step.removePrefix("open=")) is ActionResult.Done)+ step.startsWith("hold=") -> {+ // hold=DOWN:2000 presses DOWN back to back for 2000 ms, like a held remote key.+ val (name, ms) = step.removePrefix("hold=").split(':')+ var n = 0+ while ((System.nanoTime() - start) / 1_000_000 < ms.toLong() && remote.press(RemoteKey.valueOf(name))) n+++ "hold x$n" to (n > 0)+ }+ // The old path, to compare against.+ step.startsWith("input=") -> "input" to Remote(session).press(RemoteKey.valueOf(step.removePrefix("input=")))+ else -> "helper" to remote.press(RemoteKey.valueOf(step))+ }+ println("$what ${(System.nanoTime() - start) / 1_000_000} ms ${if (ok) "ok" else "FAILED"} $step")+ }+ }+ session.close()+ }+ else -> println("usage: scan | stats <host> [port] | pair <host> <port> <code> | remote <host> <port> <helper.jar> <key>...")}}