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.

Advanced: a header card and a Shell terminal on the TV

jesse-agent-2321b336e65aa1d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0faa8b..7830668 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,8 @@ until this file has a section for its version.
## Unreleased
+- **New:** Advanced has a Shell: a terminal on the TV where you can paste any `adb shell` command. Commands that change the TV ask first. [#PR](../../pull/PR)
+- **Improved:** Advanced opens with the TV's name, address, Android version, last update, app count and network speed in one card. [#PR](../../pull/PR)
- **New:** The Remote has a touchpad: swipe to move, tap for OK. Switch between it and the D-pad in the Remote's ⋮ menu. [#312](../../pull/312)
- **Improved:** On the Remote, the text box stays hidden until you tap the keyboard key, which leaves more room for the keys. [#312](../../pull/312)
- **Fixed:** Reconnecting to a TV, or installing right after the file picker, no longer leaves every action saying the TV is offline. [#312](../../pull/312)
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt
index bb5afe1..23d8a99 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt
@@ -39,6 +39,9 @@ interface AdbSession : AdbShell, AdbTransfer, AutoCloseable {
/** 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 shell-v2 `sh` for [TvShell], or null when the TV has no shell v2. Throws [java.io.IOException] if the link is gone. */
+ suspend fun openShell(): ShellChannel? = null
}
/** A running command's stdin and stdout, with no terminal in between. Closing it ends the command's stdin. */
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
index 8c12806..530840d 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
@@ -6,6 +6,7 @@ import com.flyfishxu.kadb.cert.KadbCert
import com.flyfishxu.kadb.cert.KadbCertPolicy
import com.flyfishxu.kadb.cert.OkioFilePrivateKeyStore
import com.flyfishxu.kadb.exception.AdbPairAuthException
+import com.flyfishxu.kadb.shell.AdbShellPacket
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
@@ -251,5 +252,21 @@ internal class KadbSession(private val kadb: Kadb) : AdbSession {
}
}
+ override suspend fun openShell(): ShellChannel? = runInterruptible(Dispatchers.IO) {
+ val k = live()
+ if (!k.supportsFeature("shell_v2")) return@runInterruptible null
+ val stream = k.openShell()
+ object : ShellChannel {
+ override fun read(): ShellPacket = when (val p = stream.read()) {
+ is AdbShellPacket.StdOut -> ShellPacket.Out(p.payload)
+ is AdbShellPacket.StdError -> ShellPacket.Err(p.payload)
+ is AdbShellPacket.Exit -> ShellPacket.Exit(p.payload[0].toUByte().toInt())
+ }
+
+ override fun write(bytes: ByteArray) = stream.write(bytes)
+ override fun close() = stream.close()
+ }
+ }
+
override fun close() = kadb.close()
}
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/ShellInput.kt b/adb/src/main/kotlin/app/tellyscope/adb/ShellInput.kt
new file mode 100644
index 0000000..1a38e3b
--- /dev/null
+++ b/adb/src/main/kotlin/app/tellyscope/adb/ShellInput.kt
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package app.tellyscope.adb
+
+/** What the Shell terminal makes of a typed or pasted line before anything reaches the TV. */
+sealed interface ShellLine {
+ data object Empty : ShellLine
+
+ /** Runs [command]; [dropped] when a pasted `adb shell` was taken off the front. */
+ data class Run(val command: String, val dropped: Boolean) : ShellLine
+
+ /** An `adb` command that isn't `adb shell` (`adb install …`): it runs on a computer, not on the TV. */
+ data object NotShell : ShellLine
+
+ /** [program] needs a full-screen terminal, which this one isn't. */
+ data class FullScreen(val program: String) : ShellLine
+}
+
+object ShellInput {
+ private val ADB = Regex("""^adb(?:\s+-[sdeHPL]\s*\S*|\s+-[a-zA-Z])*\s+""")
+ private val SHELL = Regex("""^shell(?:\s+|$)""")
+ private val SEGMENTS = Regex("""\|\||&&|[;|&\n]""")
+
+ /** Full-screen programs that wait on a terminal forever; `top` is fine once it's told to print a set number of times. */
+ private val FULL_SCREEN = setOf("vi", "vim", "nano", "less", "more", "htop", "screen", "tmux")
+
+ /**
+ * The commands that change the TV, each with its leading words. A match asks before it runs,
+ * because Shell runs aren't in History and have no one-tap undo.
+ */
+ private val CHANGES = listOf(
+ "pm uninstall", "pm disable", "pm disable-user", "pm clear",
+ "cmd package uninstall", "cmd package disable", "cmd package disable-user", "cmd package clear",
+ "settings put", "settings delete",
+ "wm size", "wm density",
+ "reboot", "svc power reboot", "rm",
+ ).map { it.split(' ') }
+
+ fun parse(line: String): ShellLine {
+ var s = line.trim()
+ var dropped = false
+ ADB.find(s)?.let { m ->
+ val rest = s.substring(m.range.last + 1)
+ val shell = SHELL.find(rest) ?: return ShellLine.NotShell
+ s = rest.substring(shell.range.last + 1).trim()
+ dropped = true
+ }
+ if (s.isEmpty()) return ShellLine.Empty
+ segments(s).firstNotNullOfOrNull { words ->
+ val name = words.firstOrNull()?.substringAfterLast('/') ?: return@firstNotNullOfOrNull null
+ when {
+ name in FULL_SCREEN -> name
+ name == "top" && words.none { it == "-n" || it.startsWith("-n") } -> name
+ else -> null
+ }
+ }?.let { return ShellLine.FullScreen(it) }
+ return ShellLine.Run(s, dropped)
+ }
+
+ /** The part of [command] that changes the TV, as typed (`pm uninstall`), or null when nothing does. */
+ fun changesTv(command: String): String? = segments(command).firstNotNullOfOrNull { words ->
+ CHANGES.filter { it.size <= words.size && words.subList(0, it.size) == it }
+ // `wm size` on its own only prints the size.
+ .filterNot { it[0] == "wm" && words.size == it.size }
+ .maxByOrNull { it.size }
+ ?.joinToString(" ")
+ }
+
+ /** Each simple command's words, with `su -c`, `exec`-like wrappers and `VAR=x` prefixes skipped. */
+ private fun segments(command: String): List<List<String>> = command.split(SEGMENTS).map { seg ->
+ seg.trim().split(Regex("""\s+""")).filter { it.isNotEmpty() }
+ .dropWhile { it == "su" || it == "-c" || it == "0" || it == "exec" || it == "command" || it == "nohup" || it.matches(Regex("""\w+=\S*""")) }
+ .map { it.trim('\'', '"', '(', ')', '{', '}') }
+ }
+}
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/TvShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/TvShell.kt
new file mode 100644
index 0000000..b57e033
--- /dev/null
+++ b/adb/src/main/kotlin/app/tellyscope/adb/TvShell.kt
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package app.tellyscope.adb
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runInterruptible
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import java.io.IOException
+
+/** One frame of a shell-v2 stream: the TV's stdout, its stderr, or the shell's exit. */
+sealed interface ShellPacket {
+ class Out(val bytes: ByteArray) : ShellPacket
+ class Err(val bytes: ByteArray) : ShellPacket
+ data class Exit(val code: Int) : ShellPacket
+}
+
+/** A `sh` on the TV with stdin open, speaking shell v2 so stderr and the exit status come apart. Blocking; faked in tests. */
+interface ShellChannel : AutoCloseable {
+ fun read(): ShellPacket
+ fun write(bytes: ByteArray)
+}
+
+/** What a [TvShell] prints: the TV's own output, or its error output. */
+data class ShellChunk(val text: String, val error: Boolean)
+
+sealed interface ShellEnd {
+ /** The command finished with [code]. */
+ data class Done(val code: Int) : ShellEnd
+ /** [TvShell.stop] ended it. */
+ data object Stopped : ShellEnd
+ /** The user typed `exit`: the session on the TV is over. */
+ data object Exited : ShellEnd
+ /** The TV went away mid-command. */
+ data object Lost : ShellEnd
+}
+
+/**
+ * One shell session on the TV, for the Shell terminal: a single `sh` that each command is written
+ * into, so `cd` and variables carry over like a real terminal. After every command a marker line
+ * on stdout brings back its exit status and the new working directory.
+ *
+ * No terminal sits in between (raw, not a pty), so full-screen programs can't run and there's no
+ * Ctrl-C to send: [stop] closes the shell instead, and the next command opens a new one in the
+ * same directory. A TV without shell v2 (Android 6 and older) runs each command on its own through
+ * [shell], `cd`'d to the last directory, with its error output mixed into the rest.
+ */
+class TvShell(
+ private val shell: AdbShell,
+ private val open: suspend () -> ShellChannel?,
+) {
+ /** The directory the next command runs in. */
+ var cwd: String = "/"
+ private set
+
+ @Volatile private var channel: ShellChannel? = null
+ @Volatile private var stopped = false
+ /** A new shell starts in /; the first command into it goes back to [cwd] first. */
+ private var fresh = false
+ /** One command at a time: Tab's lookup and Enter share the shell. */
+ private val turn = Mutex()
+
+ suspend fun run(command: String, print: (ShellChunk) -> Unit): ShellEnd = turn.withLock {
+ stopped = false
+ val ch = try {
+ channel ?: open()?.also { opened ->
+ channel = opened
+ fresh = true
+ }
+ } catch (e: IOException) {
+ return ShellEnd.Lost
+ } ?: return oneShot(command, print)
+ // Stopped while the shell was still opening: nothing ran.
+ if (stopped) {
+ drop(ch)
+ return ShellEnd.Stopped
+ }
+ return try {
+ runInterruptible(Dispatchers.IO) { converse(ch, command, print) }
+ } catch (e: IOException) {
+ drop(ch)
+ if (stopped) ShellEnd.Stopped else ShellEnd.Lost
+ }
+ }
+
+ /** Ends the running command by closing its shell; [run] returns [ShellEnd.Stopped]. Safe from the main thread. */
+ fun stop() {
+ stopped = true
+ channel?.let(::drop)
+ }
+
+ fun close() = stop()
+
+ private fun drop(ch: ShellChannel) {
+ if (channel === ch) channel = null
+ // Closing tells adbd over the socket, so not on the caller's thread, which may be the main one.
+ Thread { runCatching { ch.close() } }.start()
+ }
+
+ private fun converse(ch: ShellChannel, command: String, print: (ShellChunk) -> Unit): ShellEnd {
+ val back = if (fresh && cwd != "/") "cd ${shellQuote(cwd)} 2>/dev/null\n" else ""
+ fresh = false
+ // Braces, not a subshell, so `cd` stays; stdin from /dev/null so a command can't eat the marker line.
+ ch.write("$back{ $command\n} </dev/null\nprintf '$MARK%s %s\\n' \"\$?\" \"\$PWD\"\n".toByteArray())
+ val out = StringBuilder()
+ val outText = Utf8()
+ val errText = Utf8()
+ while (true) {
+ when (val p = ch.read()) {
+ is ShellPacket.Err -> errText.decode(p.bytes).takeIf { it.isNotEmpty() }?.let { print(ShellChunk(it, error = true)) }
+ is ShellPacket.Exit -> {
+ if (out.isNotEmpty()) print(ShellChunk(out.toString(), error = false))
+ drop(ch)
+ return ShellEnd.Exited
+ }
+ is ShellPacket.Out -> {
+ out.append(outText.decode(p.bytes))
+ val at = out.indexOf(MARK)
+ if (at < 0) {
+ // A marker split across two frames: hold its start back until the rest comes.
+ val held = out.lastIndexOf(MARK[0]).takeIf { it >= 0 && MARK.startsWith(out.substring(it)) } ?: out.length
+ if (held > 0) print(ShellChunk(out.substring(0, held), error = false))
+ out.delete(0, held)
+ continue
+ }
+ if (at > 0) {
+ print(ShellChunk(out.substring(0, at), error = false))
+ out.delete(0, at)
+ }
+ val nl = out.indexOf("\n")
+ if (nl < 0) continue
+ marker(out.substring(MARK.length, nl))?.let { (code, dir) ->
+ cwd = dir
+ return ShellEnd.Done(code)
+ }
+ out.delete(0, nl + 1)
+ }
+ }
+ }
+ }
+
+ private suspend fun oneShot(command: String, print: (ShellChunk) -> Unit): ShellEnd {
+ val r = try {
+ shell.shell("cd ${shellQuote(cwd)} 2>/dev/null; { $command\n} </dev/null 2>&1; printf '$MARK%s %s\\n' \"\$?\" \"\$PWD\"")
+ } catch (e: IOException) {
+ return ShellEnd.Lost
+ }
+ val at = r.output.lastIndexOf(MARK)
+ val body = if (at >= 0) r.output.substring(0, at) else r.output
+ if (body.isNotEmpty()) print(ShellChunk(body, error = false))
+ val (code, dir) = (if (at >= 0) marker(r.output.substring(at + MARK.length).trimEnd()) else null) ?: return ShellEnd.Done(r.exitCode)
+ cwd = dir
+ return ShellEnd.Done(code)
+ }
+
+ private fun marker(s: String): Pair<Int, String>? {
+ val code = s.substringBefore(' ').toIntOrNull() ?: return null
+ return code to s.substringAfter(' ', "/").ifEmpty { "/" }
+ }
+
+ /** UTF-8 across frames: a character cut between two frames waits for its last bytes instead of printing as �. */
+ private class Utf8 {
+ private var held = ByteArray(0)
+
+ fun decode(bytes: ByteArray): String {
+ val all = held + bytes
+ // Back from the end to the start of the last character; keep it if it isn't all here yet.
+ var lead = all.size - 1
+ while (lead >= 0 && lead >= all.size - 4 && all[lead].toInt() and 0xC0 == 0x80) lead--
+ val need = if (lead < 0) 0 else when (all[lead].toInt() and 0xFF) {
+ in 0xF0..0xF7 -> 4
+ in 0xE0..0xEF -> 3
+ in 0xC0..0xDF -> 2
+ else -> 1
+ }
+ val cut = if (lead >= 0 && all.size - lead < need) lead else all.size
+ held = all.copyOfRange(cut, all.size)
+ return String(all, 0, cut, Charsets.UTF_8)
+ }
+ }
+
+ private companion object {
+ /** ASCII record separator: no command's output starts a line with it. */
+ const val MARK = "\u001ETELLYSCOPE "
+ }
+}
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/TvShellTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/TvShellTest.kt
new file mode 100644
index 0000000..6eefabf
--- /dev/null
+++ b/adb/src/test/kotlin/app/tellyscope/adb/TvShellTest.kt
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: GPL-3.0-only
+package app.tellyscope.adb
+
+import kotlinx.coroutines.runBlocking
+import java.io.IOException
+import java.util.concurrent.LinkedBlockingQueue
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+class TvShellTest {
+
+ /** Answers each written command with the frames [reply] gives for it. */
+ private class FakeChannel(val reply: (String) -> List<ShellPacket>) : ShellChannel {
+ val written = mutableListOf<String>()
+ val frames = LinkedBlockingQueue<ShellPacket>()
+ var closed = false
+
+ override fun read(): ShellPacket {
+ if (closed) throw IOException("closed")
+ return frames.take().also { if (it === CLOSED) throw IOException("closed") }
+ }
+
+ override fun write(bytes: ByteArray) {
+ val s = String(bytes)
+ written += s
+ frames.addAll(reply(s))
+ }
+
+ override fun close() {
+ closed = true
+ frames.add(CLOSED)
+ }
+
+ companion object {
+ val CLOSED = ShellPacket.Exit(-1)
+ }
+ }
+
+ private fun out(s: String) = ShellPacket.Out(s.toByteArray())
+ private fun err(s: String) = ShellPacket.Err(s.toByteArray())
+ private fun marker(code: Int, dir: String) = out("\u001ETELLYSCOPE $code $dir\n")
+
+ @Test fun outputErrorsAndExitStatusComeApart() = runBlocking {
+ val ch = FakeChannel { listOf(out("one\n"), err("bad\n"), out("two\n"), marker(1, "/")) }
+ val printed = mutableListOf<ShellChunk>()
+ val end = TvShell(FakeShell()) { ch }.run("ls") { printed += it }
+ assertEquals(ShellEnd.Done(1), end)
+ assertEquals(listOf(ShellChunk("one\n", false), ShellChunk("bad\n", true), ShellChunk("two\n", false)), printed)
+ }
+
+ @Test fun cdCarriesOverToTheNextCommand() = runBlocking {
+ val ch = FakeChannel { listOf(marker(0, "/sdcard")) }
+ val sh = TvShell(FakeShell()) { ch }
+ sh.run("cd /sdcard") {}
+ assertEquals("/sdcard", sh.cwd)
+ }
+
+ @Test fun aMarkerSplitAcrossFramesIsNotPrinted() = runBlocking {
+ val ch = FakeChannel { listOf(out("hi\n\u001ETELLY"), out("SCOPE 0 /\n")) }
+ val printed = StringBuilder()
+ assertEquals(ShellEnd.Done(0), TvShell(FakeShell()) { ch }.run("echo hi") { printed.append(it.text) })
+ assertEquals("hi\n", printed.toString())
+ }
+
+ @Test fun exitEndsTheSession() = runBlocking {
+ val ch = FakeChannel { listOf(ShellPacket.Exit(0)) }
+ assertEquals(ShellEnd.Exited, TvShell(FakeShell()) { ch }.run("exit") {})
+ // Closed off the caller's thread.
+ repeat(100) { if (!ch.closed) Thread.sleep(10) }
+ assertTrue(ch.closed)
+ }
+
+ @Test fun stopEndsTheCommandAndTheNextShellStartsWhereItWas() = runBlocking {
+ val first = FakeChannel { listOf(marker(0, "/data/local/tmp")) }
+ val second = FakeChannel { listOf(marker(0, "/data/local/tmp")) }
+ val channels = ArrayDeque(listOf(first, second))
+ val sh = TvShell(FakeShell()) { channels.removeFirst() }
+ sh.run("cd /data/local/tmp") {}
+ val logcat = FakeChannel { emptyList() }
+ channels.addFirst(logcat)
+ sh.stop() // nothing running: closes `first`
+ val running = Thread { Thread.sleep(200); sh.stop() }.apply { start() }
+ assertEquals(ShellEnd.Stopped, sh.run("logcat") {})
+ running.join()
+ sh.run("ls") {}
+ assertTrue(second.written.first().startsWith("cd '/data/local/tmp' 2>/dev/null\n{ ls\n}"))
+ }
+
+ @Test fun aTvWithoutShellV2RunsEachCommandOnItsOwn() = runBlocking {
+ val tv = FakeShell().apply { answer = { ShellResult("listing\n\u001ETELLYSCOPE 2 /system\n", 0) } }
+ val printed = StringBuilder()
+ val sh = TvShell(tv) { null }
+ assertEquals(ShellEnd.Done(2), sh.run("ls") { printed.append(it.text) })
+ assertEquals("listing\n", printed.toString())
+ assertEquals("/system", sh.cwd)
+ assertTrue(tv.ran.single().startsWith("cd '/' 2>/dev/null; { ls\n}"))
+ }
+
+ @Test fun aCharacterCutBetweenFramesPrintsWhole() = runBlocking {
+ val bytes = "テレビ\n".toByteArray()
+ val ch = FakeChannel { listOf(ShellPacket.Out(bytes.copyOfRange(0, 4)), ShellPacket.Out(bytes.copyOfRange(4, bytes.size)), marker(0, "/")) }
+ val printed = StringBuilder()
+ TvShell(FakeShell()) { ch }.run("echo") { printed.append(it.text) }
+ assertEquals("テレビ\n", printed.toString())
+ }
+
+ @Test fun aLostTvSaysSo() = runBlocking {
+ val sh = TvShell(FakeShell()) { throw IOException("connection closed") }
+ assertEquals(ShellEnd.Lost, sh.run("ls") {})
+ }
+
+ @Test fun pastedAdbShellIsDropped() {
+ assertEquals(ShellLine.Run("pm list packages -d", dropped = true), ShellInput.parse("adb shell pm list packages -d"))
+ assertEquals(ShellLine.Run("getprop", dropped = true), ShellInput.parse(" adb -s 192.0.2.1:5555 shell getprop"))
+ assertEquals(ShellLine.Run("ls", dropped = false), ShellInput.parse("ls"))
+ assertEquals(ShellLine.Empty, ShellInput.parse("adb shell"))
+ }
+
+ @Test fun otherAdbCommandsAreRefused() {
+ assertEquals(ShellLine.NotShell, ShellInput.parse("adb install kodi.apk"))
+ assertEquals(ShellLine.NotShell, ShellInput.parse("adb connect 192.0.2.1"))
+ }
+
+ @Test fun fullScreenProgramsAreRefused() {
+ assertEquals(ShellLine.FullScreen("top"), ShellInput.parse("top"))
+ assertEquals(ShellLine.FullScreen("vi"), ShellInput.parse("cd /sdcard && vi notes.txt"))
+ assertTrue(ShellInput.parse("top -n 1") is ShellLine.Run)
+ }
+
+ @Test fun commandsThatChangeTheTvAreFound() {
+ assertEquals("pm uninstall", ShellInput.changesTv("pm uninstall --user 0 com.google.android.tvrecommendations"))
+ assertEquals("pm disable-user", ShellInput.changesTv("pm disable-user com.example"))
+ assertEquals("settings put", ShellInput.changesTv("settings put global animator_duration_scale 0"))
+ assertEquals("wm density", ShellInput.changesTv("wm density 200"))
+ assertEquals("rm", ShellInput.changesTv("cd /sdcard; rm -rf Download"))
+ assertEquals("pm clear", ShellInput.changesTv("su -c 'pm clear com.example'"))
+ assertNull(ShellInput.changesTv("pm list packages -d"))
+ assertNull(ShellInput.changesTv("settings get global adb_enabled"))
+ assertNull(ShellInput.changesTv("am force-stop com.example"))
+ assertNull(ShellInput.changesTv("rmdir empty"))
+ assertNull(ShellInput.changesTv("wm size"))
+ }
+}
diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.kt
index 505e477..2ee5964 100644
--- a/app/src/main/java/app/tellyscope/MainActivity.kt
+++ b/app/src/main/java/app/tellyscope/MainActivity.kt
@@ -308,7 +308,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {
vm.showStats(StatsProfile.ADVANCED)
onDispose { vm.showStats(StatsProfile.OTHER) }
}
- AdvancedScreen(state, back = { advanced = false }, snackbar = snackbar)
+ AdvancedScreen(state, back = { advanced = false }, terminal = remember(state.selectedId) { vm.terminal() }, snackbar = snackbar)
} else if (history) {
BackHandler { history = false }
// Seen on the way in, and again on the way out for changes made here, so ⋮ has no dot for them.
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index 9fb61aa..4baf2d9 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -44,6 +44,7 @@ import app.tellyscope.adb.PairResult
import app.tellyscope.adb.pairOnFreshPort
import app.tellyscope.adb.Tweak
import app.tellyscope.adb.Tweaks
+import app.tellyscope.adb.TvShell
import com.flyfishxu.kadb.mdns.KadbMdnsAndroid
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
@@ -68,6 +69,7 @@ import kotlinx.coroutines.withTimeoutOrNull
import okio.Sink
import okio.Source
import java.io.File
+import java.io.IOException
import java.net.Inet4Address
import java.net.NetworkInterface
import java.util.concurrent.ConcurrentHashMap
@@ -968,6 +970,12 @@ class AdbDeviceSource(
override suspend fun reboot(deviceId: String) = Remote(session(deviceId)).reboot()
+ // An offline TV is a lost link to the terminal, which prints that rather than an error.
+ override fun shell(deviceId: String): TvShell {
+ fun live() = links[deviceId]?.session ?: throw IOException("offline")
+ return TvShell({ live().shell(it) }) { live().openShell() }
+ }
+
override suspend fun openUpdates(deviceId: String) = Remote(session(deviceId)).openUpdates()
override suspend fun launch(deviceId: String, packageName: String) =
diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
index 96f7da2..0e5895d 100644
--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
@@ -14,11 +14,13 @@ import app.tellyscope.adb.TvFacts
import app.tellyscope.adb.TvFile
import app.tellyscope.adb.TvFolder
import app.tellyscope.adb.Tweak
+import app.tellyscope.adb.TvShell
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import okio.Sink
import okio.Source
import java.io.File
+import java.io.IOException
/**
* Everything the screens need from a TV. The UI only talks to this; an
@@ -182,6 +184,9 @@ interface DeviceSource {
/** 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
+ /** A shell session on the TV, for Advanced's Shell; each command reaches the TV over whatever link is up then. */
+ fun shell(deviceId: String): TvShell = TvShell({ throw IOException("no shell") }) { throw IOException("no shell") }
+
/** Opens [packageName] on the TV, the way its launcher icon would. False when it has nothing to open. Not history. */
suspend fun launch(deviceId: String, packageName: String): Boolean
diff --git a/app/src/main/java/app/tellyscope/ui/AdvancedScreen.kt b/app/src/main/java/app/tellyscope/ui/AdvancedScreen.kt
index 15c58fd..f70295f 100644
--- a/app/src/main/java/app/tellyscope/ui/AdvancedScreen.kt
+++ b/app/src/main/java/app/tellyscope/ui/AdvancedScreen.kt
@@ -18,6 +18,16 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.layout.boundsInRoot
+import androidx.compose.ui.layout.onGloballyPositioned
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.font.FontFamily
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
@@ -68,6 +78,7 @@ import app.tellyscope.ui.theme.StatNumber
fun AdvancedScreen(
state: UiState,
back: () -> Unit,
+ terminal: ShellTerminal? = null,
snackbar: SnackbarHostState = remember { SnackbarHostState() },
) {
val device = state.selected ?: return
@@ -81,55 +92,123 @@ fun AdvancedScreen(
procs.groupBy { p -> p.packageName?.let { labels[it] ?: AppNames.fallback(it) } ?: androidSystem }
}
val res = LocalContext.current.resources
+ var shellOpen by rememberSaveable { mutableStateOf(false) }
+ var shellFrom by remember { mutableStateOf(Offset.Zero) }
- Scaffold(
- snackbarHost = { SnackbarHost(snackbar) },
- topBar = {
- TopAppBar(
- title = { Text(Copy.ADVANCED_MONITOR.resolve()) },
- navigationIcon = {
- IconButton(onClick = back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.advanced_back)) }
- },
- )
- },
- ) { pad ->
- LazyColumn(
- Modifier.fillMaxSize().padding(pad),
- contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp),
- verticalArrangement = Arrangement.spacedBy(12.dp),
- ) {
- item {
- Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer)) {
- Column(Modifier.fillMaxWidth().padding(16.dp)) {
- Text(stringResource(R.string.advanced_this_tv), style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(bottom = 4.dp))
- listOfNotNull(
- stringResource(R.string.advanced_ip_address) to device.hit.ip,
- stringResource(R.string.advanced_port) to device.hit.port.toString(),
- (device.manufacturer ?: device.hit.maker)?.let { stringResource(R.string.advanced_maker) to it },
- device.hit.hostname?.let { stringResource(R.string.advanced_network_name) to it },
- ).forEach { (k, v) -> KeyValue(k, v) }
+ Box(Modifier.fillMaxSize()) {
+ Scaffold(
+ snackbarHost = { SnackbarHost(snackbar) },
+ topBar = {
+ TopAppBar(
+ title = { Text(Copy.ADVANCED_MONITOR.resolve()) },
+ navigationIcon = {
+ IconButton(onClick = back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.advanced_back)) }
+ },
+ )
+ },
+ ) { pad ->
+ LazyColumn(
+ Modifier.fillMaxSize().padding(pad),
+ contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ item {
+ Header(state, snap, onShell = { shellFrom = it; shellOpen = true })
+ }
+ if (snap != null) {
+ // Offline: the last stats this phone saw, greyed and dated, rather than a grid of blanks.
+ item { Stats(snap, if (offline) state.clock() else null) }
+ } else {
+ item {
+ Text(
+ if (offline) Copy.noStats(device.state).resolve() else stringResource(R.string.advanced_loading),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
}
}
+ // A TV that lists no processes gets no charts: no bars beats an empty card.
+ if (byApp.isNotEmpty()) {
+ item { UsageCard(stringResource(R.string.advanced_cpu_by_app), byApp.map { (n, ps) -> n to ps.sumOf { it.cpuPercent } }, fmt = { res.getString(R.string.advanced_percent_whole, it) }) }
+ item { UsageCard(stringResource(R.string.advanced_ram_by_app), byApp.map { (n, ps) -> n to ps.sumOf { it.ramMb }.toDouble() }, fmt = { Copy.mb(it.toInt()).resolve(res) }) }
+ item { Block(stringResource(R.string.advanced_processes)) { ProcessTable(snap?.procs.orEmpty(), ui.apps) } }
+ }
+ ui.network?.let { n -> item { Block(stringResource(R.string.advanced_network)) { NetworkBlock(n) } } }
}
- if (snap != null) {
- // Offline: the last stats this phone saw, greyed and dated, rather than a grid of blanks.
- item { Stats(snap, if (offline) state.clock() else null) }
- } else {
- item {
- Text(
- if (offline) Copy.noStats(device.state).resolve() else stringResource(R.string.advanced_loading),
- style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
+ }
+ terminal?.let { t -> ShellOverlay(shellOpen, shellFrom, device, !offline, t, onClose = { shellOpen = false }) }
+ }
+}
+
+/**
+ * Which TV this is, at the top: its cookie, name and maker with the Shell button, then where it is
+ * on the network, then the facts the app already has. [onShell] gets the button's centre in the
+ * root, where Shell grows from.
+ */
+@Composable
+private fun Header(state: UiState, snap: Snapshot?, onShell: (Offset) -> Unit) {
+ val device = state.selected ?: return
+ val c = MaterialTheme.colorScheme
+ val clipboard = LocalClipboardManager.current
+ val address = stringResource(R.string.advanced_address, device.hit.ip, device.hit.port)
+ var center by remember { mutableStateOf(Offset.Zero) }
+ Card(colors = CardDefaults.cardColors(containerColor = c.surfaceContainer)) {
+ Column(Modifier.fillMaxWidth().padding(16.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Cookie(device, 48.dp)
+ Spacer(Modifier.width(12.dp))
+ Column(Modifier.weight(1f)) {
+ Text(name(device), style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ makerLine(device).takeIf { it.isNotEmpty() }?.let {
+ Text(it, style = MaterialTheme.typography.bodyMedium, color = c.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ Spacer(Modifier.width(8.dp))
+ Button(
+ onClick = { onShell(center) },
+ modifier = Modifier.onGloballyPositioned { center = it.boundsInRoot().center },
+ ) {
+ Icon(TerminalIcon, null, Modifier.size(ButtonDefaults.IconSize))
+ Spacer(Modifier.width(ButtonDefaults.IconSpacing))
+ Text(stringResource(R.string.shell_open))
+ }
+ }
+ HorizontalDivider(Modifier.padding(vertical = 12.dp), color = c.outlineVariant)
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ // The name the TV gives itself on the Wi-Fi; left out when it's the name above already.
+ val network = device.hit.hostname?.takeIf { it != name(device) }
+ Text(
+ network.orEmpty(),
+ Modifier.weight(1f),
+ style = MaterialTheme.typography.bodyMedium,
+ color = c.onSurfaceVariant,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Spacer(Modifier.width(8.dp))
+ Text(address, style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace), maxLines = 1)
+ IconButton(onClick = { clipboard.setText(AnnotatedString(address)) }) {
+ Icon(CopyIcon, stringResource(R.string.advanced_copy_address), Modifier.size(18.dp), tint = c.onSurfaceVariant)
}
}
- // A TV that lists no processes gets no charts: no bars beats an empty card.
- if (byApp.isNotEmpty()) {
- item { UsageCard(stringResource(R.string.advanced_cpu_by_app), byApp.map { (n, ps) -> n to ps.sumOf { it.cpuPercent } }, fmt = { res.getString(R.string.advanced_percent_whole, it) }) }
- item { UsageCard(stringResource(R.string.advanced_ram_by_app), byApp.map { (n, ps) -> n to ps.sumOf { it.ramMb }.toDouble() }, fmt = { Copy.mb(it.toInt()).resolve(res) }) }
- item { Block(stringResource(R.string.advanced_processes)) { ProcessTable(snap?.procs.orEmpty(), ui.apps) } }
+ val dash = "—"
+ val facts = listOf(
+ stringResource(R.string.advanced_android) to ((device.android ?: device.lastKnown?.android)?.let { stringResource(R.string.tabs_android_version, it) } ?: dash),
+ stringResource(R.string.advanced_updated) to ((snap?.softwareMonth ?: device.lastKnown?.softwareMonth)?.let(Copy::shortMonth) ?: dash),
+ stringResource(R.string.advanced_your_apps) to (state.device.apps.takeIf { it.isNotEmpty() }?.count { !it.system }?.toString() ?: dash),
+ stringResource(R.string.device_network) to (snap?.netBytesPerSec?.takeIf { device.state == DeviceState.Online }?.let { Copy.speed(it).resolve() } ?: dash),
+ )
+ Spacer(Modifier.height(8.dp))
+ facts.chunked(2).forEach { pair ->
+ Row(Modifier.fillMaxWidth().padding(top = 8.dp)) {
+ pair.forEach { (label, value) ->
+ Column(Modifier.weight(1f)) {
+ Text(label, style = MaterialTheme.typography.labelMedium, color = c.onSurfaceVariant)
+ Text(value, style = MaterialTheme.typography.titleLarge.copy(fontFeatureSettings = "tnum"), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ }
}
- ui.network?.let { n -> item { Block(stringResource(R.string.advanced_network)) { NetworkBlock(n) } } }
}
}
}
diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.kt
index e8399dc..55bea2f 100644
--- a/app/src/main/java/app/tellyscope/ui/Copy.kt
+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt
@@ -362,6 +362,9 @@ object Copy {
/** "May 2023", in the phone's language. */
fun month(m: YearMonth): String = m.format(DateTimeFormatter.ofPattern("MMMM yyyy"))
+ /** "Sep 2025", for a half-width cell. */
+ fun shortMonth(m: YearMonth): String = m.format(DateTimeFormatter.ofPattern("MMM yyyy"))
+
/** Network speed in the same units as [bytes], so a download's size and speed line up. */
fun speed(bytesPerSec: Long) = UiText(R.string.copy_speed, bytes(bytesPerSec))
diff --git a/app/src/main/java/app/tellyscope/ui/ReportScreen.kt b/app/src/main/java/app/tellyscope/ui/ReportScreen.kt
index 31641ef..45993f4 100644
--- a/app/src/main/java/app/tellyscope/ui/ReportScreen.kt
+++ b/app/src/main/java/app/tellyscope/ui/ReportScreen.kt
@@ -324,7 +324,7 @@ private fun icon(name: String, path: String) = ImageVector.Builder(name, 24.dp,
.addPath(PathParser().parsePathString(path).toNodes(), pathFillType = PathFillType.NonZero, fill = SolidColor(Color.Black))
.build()
-private val CopyIcon = icon(
+internal val CopyIcon = icon(
"ContentCopy",
"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z",
)
diff --git a/app/src/main/java/app/tellyscope/ui/ShellScreen.kt b/app/src/main/java/app/tellyscope/ui/ShellScreen.kt
new file mode 100644
index 0000000..8ec7b37
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/ShellScreen.kt
@@ -0,0 +1,236 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.core.Animatable
+import androidx.compose.foundation.background
+import androidx.compose.foundation.horizontalScroll
+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.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.KeyboardArrowDown
+import androidx.compose.material.icons.filled.KeyboardArrowUp
+import androidx.compose.material3.AssistChip
+import androidx.compose.material3.AssistChipDefaults
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.SuggestionChip
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.GenericShape
+import androidx.compose.ui.graphics.PathFillType
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.graphics.vector.PathParser
+import androidx.compose.ui.layout.onGloballyPositioned
+import androidx.compose.ui.layout.positionInRoot
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.TextRange
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.TextFieldValue
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.tellyscope.R
+import app.tellyscope.data.Device
+import app.tellyscope.data.resolve
+import app.tellyscope.ui.theme.TellyscopeTheme
+import kotlin.math.hypot
+
+/**
+ * Advanced's Shell: a black terminal that grows out of the Shell button ([from], in the root) and
+ * shrinks back into it on ✕, Back or `exit`. Commands go to [terminal]; it's always dark, whatever
+ * the app's theme.
+ */
+@Composable
+fun ShellOverlay(open: Boolean, from: Offset, device: Device, online: Boolean, terminal: ShellTerminal, onClose: () -> Unit) {
+ val reveal = remember { Animatable(if (open) 1f else 0f) }
+ val spec = MaterialTheme.motionScheme.slowSpatialSpec<Float>()
+ LaunchedEffect(open) {
+ if (open) terminal.opened()
+ reveal.animateTo(if (open) 1f else 0f, spec)
+ }
+ if (!open && reveal.value == 0f) return
+ BackHandler(open, onClose)
+ val state by terminal.state.collectAsState()
+ LaunchedEffect(state.exited) { if (state.exited) onClose() }
+ var origin by remember { mutableStateOf(Offset.Zero) }
+ val center = from - origin
+ val circle = GenericShape { size, _ ->
+ val r = maxOf(hypot(center.x, center.y), hypot(size.width - center.x, center.y), hypot(center.x, size.height - center.y), hypot(size.width - center.x, size.height - center.y))
+ addOval(Rect(center, r * reveal.value))
+ }
+ TellyscopeTheme(dark = true) {
+ Box(
+ Modifier.fillMaxSize()
+ .onGloballyPositioned { origin = it.positionInRoot() }
+ .clip(circle)
+ .background(MaterialTheme.colorScheme.surfaceContainerLowest),
+ ) {
+ Terminal(device, online, terminal, state, onClose)
+ }
+ }
+}
+
+@Composable
+private fun Terminal(device: Device, online: Boolean, terminal: ShellTerminal, state: TerminalState, onClose: () -> Unit) {
+ val c = MaterialTheme.colorScheme
+ val mono = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = c.onSurface)
+ val address = stringResource(R.string.advanced_address, device.hit.ip, device.hit.port)
+ var input by remember { mutableStateOf(TextFieldValue()) }
+ // Steps back through Recent with ↑; -1 is the line being typed.
+ var back by remember { mutableIntStateOf(-1) }
+ val list = rememberLazyListState()
+ val focus = remember { FocusRequester() }
+ val clipboard = LocalClipboardManager.current
+
+ fun set(text: String) { input = TextFieldValue(text, TextRange(text.length)) }
+ fun type(s: String) {
+ val t = input.text.replaceRange(input.selection.min, input.selection.max, s)
+ input = TextFieldValue(t, TextRange(input.selection.min + s.length))
+ }
+ fun enter() {
+ terminal.submit(input.text, online)
+ // Offline, Enter does nothing, so the line stays to run once the TV is back.
+ if (online || state.confirming != null) set("")
+ back = -1
+ }
+
+ LaunchedEffect(state.lines.size, state.running, state.confirming) { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1)) }
+ LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
+
+ Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding().imePadding()) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ IconButton(onClick = onClose) { Icon(Icons.Default.Close, stringResource(R.string.shell_close), tint = c.onSurface) }
+ Text(stringResource(R.string.shell_title, name(device), address), style = mono.copy(color = c.onSurfaceVariant), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ LazyColumn(Modifier.weight(1f).fillMaxWidth(), state = list, contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)) {
+ item { Text(stringResource(R.string.shell_banner, name(device), address), style = mono.copy(color = c.onSurfaceVariant)) }
+ if (state.trimmed) item { Text(stringResource(R.string.shell_trimmed, ShellTerminal.MAX_LINES), style = mono.copy(color = c.onSurfaceVariant)) }
+ items(state.lines.size) { i ->
+ when (val l = state.lines[i]) {
+ is TermLine.Typed -> Row {
+ Text(stringResource(R.string.shell_prompt, l.cwd), style = mono.copy(color = c.primary))
+ Text(" " + l.command, style = mono)
+ }
+ is TermLine.Out -> Text(l.text, style = mono)
+ is TermLine.Err -> Text(l.text, style = mono.copy(color = c.error))
+ is TermLine.Note -> Text(l.text.resolve(), style = mono.copy(color = c.onSurfaceVariant))
+ is TermLine.Warn -> Text(l.text.resolve(), style = mono.copy(color = c.error))
+ }
+ }
+ // The line being typed sits under the output, as in a terminal; there's none while a command runs.
+ if (!state.running) item {
+ Row(verticalAlignment = Alignment.Top) {
+ when {
+ state.confirming != null -> Text(stringResource(R.string.shell_confirm) + " ", style = mono.copy(color = c.error))
+ !online -> Text(stringResource(R.string.shell_offline_prompt) + " ", style = mono.copy(color = c.onSurfaceVariant))
+ else -> Text(stringResource(R.string.shell_prompt, state.cwd) + " ", style = mono.copy(color = c.primary))
+ }
+ BasicTextField(
+ input,
+ { input = it },
+ Modifier.weight(1f).focusRequester(focus),
+ textStyle = mono,
+ cursorBrush = SolidColor(c.primary),
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(
+ capitalization = KeyboardCapitalization.None,
+ autoCorrectEnabled = false,
+ keyboardType = KeyboardType.Ascii,
+ imeAction = ImeAction.Go,
+ ),
+ keyboardActions = KeyboardActions(onGo = { enter() }),
+ )
+ }
+ }
+ if (!online && !state.running) item { Text(stringResource(R.string.shell_offline_hint), style = mono.copy(color = c.onSurfaceVariant)) }
+ }
+ // Termux-style keys for what a phone keyboard hides on its symbols page.
+ Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Key(stringResource(R.string.shell_key_paste)) { clipboard.getText()?.text?.let { type(it.trim().replace("\n", "; ")) } }
+ Key(stringResource(R.string.shell_key_tab)) { terminal.complete(input.text) { set(it) } }
+ Key(stringResource(R.string.shell_key_ctrl_c), stop = state.running) {
+ if (state.running || state.confirming != null) terminal.interrupt() else set("")
+ }
+ Key(icon = Icons.Default.KeyboardArrowUp, label = stringResource(R.string.shell_key_up)) {
+ if (back + 1 < state.recent.size) { back++; set(state.recent[back]) }
+ }
+ Key(icon = Icons.Default.KeyboardArrowDown, label = stringResource(R.string.shell_key_down)) {
+ if (back > 0) { back--; set(state.recent[back]) } else { back = -1; set("") }
+ }
+ listOf("|", "-", "/").forEach { s -> Key(s) { type(s) } }
+ }
+ LazyRow(Modifier.fillMaxWidth(), contentPadding = PaddingValues(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (state.confirming != null) {
+ item { SuggestionChip(onClick = { set("y"); enter() }, label = { Text(stringResource(R.string.shell_answer_yes), style = mono) }) }
+ item { SuggestionChip(onClick = { set(""); enter() }, label = { Text(stringResource(R.string.shell_answer_no), style = mono) }) }
+ } else {
+ items(state.recent) { r ->
+ SuggestionChip(onClick = { set(r); back = -1 }, label = { Text(r, style = mono, maxLines = 1, overflow = TextOverflow.Ellipsis) })
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun Key(text: String = "", icon: ImageVector? = null, label: String = text, stop: Boolean = false, onClick: () -> Unit) {
+ val c = MaterialTheme.colorScheme
+ AssistChip(
+ onClick = onClick,
+ label = { if (icon == null) Text(text, fontFamily = FontFamily.Monospace) },
+ leadingIcon = icon?.let { { Icon(it, label) } },
+ colors = if (stop) AssistChipDefaults.assistChipColors(containerColor = c.error, labelColor = c.onError) else AssistChipDefaults.assistChipColors(),
+ border = if (stop) null else AssistChipDefaults.assistChipBorder(enabled = true),
+ )
+}
+
+private fun icon(name: String, path: String) = ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f)
+ .addPath(PathParser().parsePathString(path).toNodes(), pathFillType = PathFillType.NonZero, fill = SolidColor(Color.Black))
+ .build()
+
+internal val TerminalIcon = icon(
+ "Terminal",
+ "M20 4H4c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H4V8h16v10zm-2-1h-6v-2h6v2zM7.5 17l-1.41-1.41L8.67 13l-2.59-2.59L7.5 9l4 4-4 4z",
+)
diff --git a/app/src/main/java/app/tellyscope/ui/ShellTerminal.kt b/app/src/main/java/app/tellyscope/ui/ShellTerminal.kt
new file mode 100644
index 0000000..d9d3c37
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/ShellTerminal.kt
@@ -0,0 +1,181 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import app.tellyscope.R
+import app.tellyscope.adb.ShellEnd
+import app.tellyscope.adb.ShellInput
+import app.tellyscope.adb.ShellLine
+import app.tellyscope.adb.TvShell
+import app.tellyscope.data.UiText
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+/** One line of the terminal. */
+sealed interface TermLine {
+ /** A command as it was entered, after the prompt it was entered at. */
+ data class Typed(val cwd: String, val command: String) : TermLine
+ data class Out(val text: String) : TermLine
+ data class Err(val text: String) : TermLine
+ /** Tellyscope talking, dim: notes, refusals, `[exit 1]`. */
+ data class Note(val text: UiText) : TermLine
+ /** Tellyscope talking, in the error colour: the TV was lost, a confirm question. */
+ data class Warn(val text: UiText) : TermLine
+}
+
+data class TerminalState(
+ val lines: List<TermLine> = emptyList(),
+ val cwd: String = "/",
+ val running: Boolean = false,
+ /** A command that changes the TV, waiting on y/N; the part that matched is [confirmMatch]. */
+ val confirming: String? = null,
+ val confirmMatch: String? = null,
+ /** Lines dropped off the top to keep [MAX_LINES]. */
+ val trimmed: Boolean = false,
+ /** Newest first, no repeats. */
+ val recent: List<String> = emptyList(),
+ /** The user typed `exit`: the screen closes. */
+ val exited: Boolean = false,
+)
+
+/**
+ * Advanced's Shell: a terminal on one TV. Holds the lines, the y/N confirm and the recent
+ * commands, so they outlive the screen; the session itself is [TvShell], one `sh` on the TV.
+ */
+class ShellTerminal(private val shell: TvShell, private val scope: CoroutineScope) {
+ private val _state = MutableStateFlow(TerminalState())
+ val state: StateFlow<TerminalState> = _state.asStateFlow()
+ private var job: Job? = null
+
+ /** Enter on [line]. While a confirm waits, it's the answer: only `y` runs it. */
+ fun submit(line: String, online: Boolean) {
+ val s = _state.value
+ if (s.running) return
+ s.confirming?.let { pending ->
+ val yes = line.trim().equals("y", ignoreCase = true) || line.trim().equals("yes", ignoreCase = true)
+ _state.update { it.copy(confirming = null, confirmMatch = null) }
+ print(TermLine.Warn(UiText(R.string.shell_confirm_answered, if (yes) "y" else "N")))
+ if (yes && online) start(pending) else print(TermLine.Note(UiText(R.string.shell_not_run)))
+ return
+ }
+ // Enter does nothing while the TV is away: the line stays to run once it's back.
+ if (!online) return
+ when (val parsed = ShellInput.parse(line)) {
+ ShellLine.Empty -> print(TermLine.Typed(s.cwd, ""))
+ ShellLine.NotShell -> {
+ print(TermLine.Typed(s.cwd, line.trim()))
+ print(TermLine.Warn(UiText(R.string.shell_not_shell)))
+ }
+ is ShellLine.FullScreen -> {
+ print(TermLine.Typed(s.cwd, line.trim()))
+ print(TermLine.Warn(UiText(R.string.shell_full_screen, parsed.program)))
+ }
+ is ShellLine.Run -> {
+ remember(parsed.command)
+ print(TermLine.Typed(s.cwd, parsed.command))
+ if (parsed.dropped) print(TermLine.Note(UiText(R.string.shell_dropped_prefix)))
+ val match = ShellInput.changesTv(parsed.command)
+ if (match != null) {
+ print(TermLine.Note(UiText(R.string.shell_no_history)))
+ _state.update { it.copy(confirming = parsed.command, confirmMatch = match) }
+ } else {
+ start(parsed.command)
+ }
+ }
+ }
+ }
+
+ /** Shell opened again after `exit` closed it: the next command starts a new session. */
+ fun opened() = _state.update { it.copy(exited = false) }
+
+ /** Ctrl-C: stops what's running, or drops the confirm. */
+ fun interrupt() {
+ when {
+ _state.value.running -> shell.stop()
+ _state.value.confirming != null -> {
+ _state.update { it.copy(confirming = null, confirmMatch = null) }
+ print(TermLine.Note(UiText(R.string.shell_not_run)))
+ }
+ }
+ }
+
+ /** Tab on [input]: its last word completed from what's on the TV; several matches are printed. */
+ fun complete(input: String, done: (String) -> Unit) {
+ if (_state.value.running) return
+ val word = input.substringAfterLast(' ')
+ val head = input.dropLast(word.length)
+ scope.launch {
+ val found = mutableListOf<String>()
+ shell.run("ls -d -p -- ${quote(word)}* 2>/dev/null") { c -> if (!c.error) found += c.text.lines().filter { it.isNotBlank() } }
+ when {
+ found.size == 1 -> done(head + found.single().let { if (it.endsWith('/')) it else "$it " })
+ found.size > 1 -> {
+ print(TermLine.Typed(_state.value.cwd, input), TermLine.Out(found.joinToString(" ") { it.trimEnd('/').substringAfterLast('/') + if (it.endsWith('/')) "/" else "" }))
+ done(head + found.reduce { a, b -> a.commonPrefixWith(b) })
+ }
+ }
+ }
+ }
+
+ fun close() {
+ job?.cancel()
+ shell.close()
+ }
+
+ private fun start(command: String) {
+ _state.update { it.copy(running = true) }
+ job = scope.launch {
+ // Output comes in chunks that can end mid-line: print whole lines, the rest once more arrives.
+ val held = mapOf(false to StringBuilder(), true to StringBuilder())
+ fun flush(error: Boolean, all: Boolean) {
+ val b = held.getValue(error)
+ val cut = if (all) b.length else b.lastIndexOf("\n") + 1
+ if (cut == 0 || b.isEmpty()) return
+ val text = b.substring(0, cut).removeSuffix("\n")
+ b.delete(0, cut)
+ print(if (error) TermLine.Err(text) else TermLine.Out(text))
+ }
+ val end = shell.run(command) { chunk ->
+ held.getValue(chunk.error).append(chunk.text)
+ flush(chunk.error, all = false)
+ }
+ flush(false, all = true)
+ flush(true, all = true)
+ _state.update { it.copy(running = false, cwd = shell.cwd, exited = end == ShellEnd.Exited) }
+ when (end) {
+ is ShellEnd.Done -> if (end.code != 0) print(TermLine.Note(UiText(R.string.shell_exit_code, end.code)))
+ ShellEnd.Stopped -> print(TermLine.Note(UiText(R.string.shell_stopped)))
+ ShellEnd.Lost -> print(TermLine.Warn(UiText(R.string.shell_lost)))
+ ShellEnd.Exited -> {}
+ }
+ }
+ }
+
+ private fun remember(command: String) =
+ _state.update { it.copy(recent = (listOf(command) + it.recent.filter { r -> r != command }).take(MAX_RECENT)) }
+
+ private fun print(vararg add: TermLine) = _state.update {
+ // One row per line, so the cap counts what's on screen.
+ val lines = it.lines + add.flatMap { l ->
+ when (l) {
+ is TermLine.Out -> l.text.split('\n').map(TermLine::Out)
+ is TermLine.Err -> l.text.split('\n').map(TermLine::Err)
+ else -> listOf(l)
+ }
+ }
+ if (lines.size > MAX_LINES) it.copy(lines = lines.takeLast(MAX_LINES), trimmed = true) else it.copy(lines = lines)
+ }
+
+ private fun quote(s: String) = "'" + s.replace("'", "'\\''") + "'"
+
+ companion object {
+ /** Long output (`logcat`) keeps its last 2,000 lines. */
+ const val MAX_LINES = 2_000
+ const val MAX_RECENT = 8
+ }
+}
diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
index 131699b..cbbc575 100644
--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
@@ -702,6 +702,19 @@ class TellyscopeViewModel(
/** The TV on screen refreshes at the open screen's rates; the others at the slowest. */
fun showStats(profile: StatsProfile) = source.showStats(_state.value.selectedId, profile)
+ private val terminals = mutableMapOf<String, ShellTerminal>()
+
+ /** The selected TV's Shell. Its lines and recent commands stay while the app runs, so closing Shell and opening it again picks up where it was. */
+ fun terminal(): ShellTerminal? {
+ val id = _state.value.selectedId ?: return null
+ return terminals.getOrPut(id) { ShellTerminal(source.shell(id), viewModelScope) }
+ }
+
+ override fun onCleared() {
+ terminals.values.forEach(ShellTerminal::close)
+ super.onCleared()
+ }
+
fun select(id: String?) {
stopWatching()
launcherJob?.cancel()
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 425a85d..c503669 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -793,11 +793,7 @@
<string name="lists_about_libraries">Usa Kadb (Apache 2.0) y spake2-java (GPL v3). Los textos completos de las licencias están en el archivo NOTICE.</string>
<string name="lists_about_close">Cerrar</string>
<string name="advanced_back">Volver a la página de la TV</string>
- <string name="advanced_this_tv">Esta TV</string>
<string name="advanced_ip_address">Dirección IP</string>
- <string name="advanced_port">Puerto</string>
- <string name="advanced_maker">Fabricante</string>
- <string name="advanced_network_name">Nombre de red</string>
<string name="advanced_loading">Cargando estadísticas…</string>
<string name="advanced_cpu_by_app">CPU por app</string>
<string name="advanced_ram_by_app">RAM por app</string>
@@ -831,6 +827,27 @@
<string name="advanced_mbps">%1$d Mbps</string>
<string name="advanced_data_used">Datos usados</string>
<string name="advanced_open_connections">Conexiones abiertas</string>
+ <string name="advanced_copy_address">Copiar dirección</string>
+ <string name="advanced_android">Android</string>
+ <string name="advanced_updated">Actualizado</string>
+ <string name="advanced_your_apps">Tus apps</string>
+ <string name="shell_open">Shell</string>
+ <string name="shell_close">Cerrar Shell</string>
+ <string name="shell_title">%1$s · %2$s</string>
+ <string name="shell_banner">Conectado a %1$s (%2$s).\nEscribe exit o toca ✕ para cerrar.</string>
+ <string name="shell_trimmed">Se quitaron líneas anteriores: se muestran las últimas %1$d.</string>
+ <string name="shell_offline_hint">Los comandos vuelven a funcionar cuando la TV regrese.</string>
+ <string name="shell_key_paste">Pegar</string>
+ <string name="shell_key_up">Comando anterior</string>
+ <string name="shell_key_down">Comando siguiente</string>
+ <string name="shell_confirm">Esto cambia la TV. ¿Ejecutarlo? [y/N]</string>
+ <string name="shell_confirm_answered">Esto cambia la TV. ¿Ejecutarlo? [y/N] %1$s</string>
+ <string name="shell_no_history">Lo que se ejecuta en Shell no va al Historial, así que no se puede deshacer con un toque.</string>
+ <string name="shell_not_run">No se ejecutó.</string>
+ <string name="shell_not_shell">Aquí solo se ejecutan comandos de adb shell.</string>
+ <string name="shell_full_screen">%1$s necesita una terminal a pantalla completa. Aquí no funciona.</string>
+ <string name="shell_dropped_prefix">(se quitó \"adb shell\")</string>
+ <string name="shell_lost">Se perdió la TV antes de que terminara el comando. Puede que solo se ejecutara en parte.</string>
<string name="report_title_new_tv">Ayuda a añadir esta TV</string>
<string name="report_title_problem">Informar de un problema</string>
<string name="report_subtitle_new_tv">Abre el formulario “My TV” de cleanyourtv en GitHub</string>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 89a27e9..4690143 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -753,11 +753,7 @@
<string name="lists_about_libraries">Kadb (Apache 2.0) और spake2-java (GPL v3) का इस्तेमाल करता है। पूरे लाइसेंस टेक्स्ट NOTICE फ़ाइल में हैं।</string>
<string name="lists_about_close">बंद करें</string>
<string name="advanced_back">TV के पेज पर वापस जाएं</string>
- <string name="advanced_this_tv">यह TV</string>
<string name="advanced_ip_address">IP पता</string>
- <string name="advanced_port">पोर्ट</string>
- <string name="advanced_maker">कंपनी</string>
- <string name="advanced_network_name">नेटवर्क का नाम</string>
<string name="advanced_loading">आंकड़े लोड हो रहे हैं…</string>
<string name="advanced_cpu_by_app">ऐप के हिसाब से CPU</string>
<string name="advanced_ram_by_app">ऐप के हिसाब से RAM</string>
@@ -791,6 +787,27 @@
<string name="advanced_mbps">%1$d Mbps</string>
<string name="advanced_data_used">इस्तेमाल हुआ डेटा</string>
<string name="advanced_open_connections">खुले कनेक्शन</string>
+ <string name="advanced_copy_address">पता कॉपी करें</string>
+ <string name="advanced_android">Android</string>
+ <string name="advanced_updated">अपडेट</string>
+ <string name="advanced_your_apps">आपके ऐप</string>
+ <string name="shell_open">Shell</string>
+ <string name="shell_close">Shell बंद करें</string>
+ <string name="shell_title">%1$s · %2$s</string>
+ <string name="shell_banner">%1$s (%2$s) से जुड़ा है।\nबंद करने के लिए exit टाइप करें या ✕ पर टैप करें।</string>
+ <string name="shell_trimmed">पुरानी लाइनें हटा दी गईं: आख़िरी %1$d दिख रही हैं।</string>
+ <string name="shell_offline_hint">TV वापस आने पर कमांड फिर से चलेंगी।</string>
+ <string name="shell_key_paste">पेस्ट करें</string>
+ <string name="shell_key_up">पिछली कमांड</string>
+ <string name="shell_key_down">अगली कमांड</string>
+ <string name="shell_confirm">इससे TV बदलेगा। चलाएँ? [y/N]</string>
+ <string name="shell_confirm_answered">इससे TV बदलेगा। चलाएँ? [y/N] %1$s</string>
+ <string name="shell_no_history">Shell में चलाई गई कमांड इतिहास में नहीं जातीं, इसलिए एक टैप से पहले जैसा नहीं होता।</string>
+ <string name="shell_not_run">नहीं चलाया।</string>
+ <string name="shell_not_shell">यहाँ सिर्फ़ adb shell कमांड चलती हैं।</string>
+ <string name="shell_full_screen">%1$s को फ़ुल-स्क्रीन टर्मिनल चाहिए। यह यहाँ काम नहीं करता।</string>
+ <string name="shell_dropped_prefix">(\"adb shell\" हटाया)</string>
+ <string name="shell_lost">कमांड पूरी होने से पहले TV से कनेक्शन टूट गया। हो सकता है वह सिर्फ़ आधी चली हो।</string>
<string name="report_title_new_tv">इस TV को जोड़ने में मदद करें</string>
<string name="report_title_problem">समस्या की शिकायत करें</string>
<string name="report_subtitle_new_tv">GitHub पर cleanyourtv का “My TV” फ़ॉर्म खोलता है</string>
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index 586a530..0804c71 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -713,11 +713,7 @@
<string name="lists_about_libraries">Kadb(Apache 2.0)と spake2-java(GPL v3)を使用しています。ライセンスの全文は NOTICE ファイルにあります。</string>
<string name="lists_about_close">閉じる</string>
<string name="advanced_back">テレビのページに戻る</string>
- <string name="advanced_this_tv">このテレビ</string>
<string name="advanced_ip_address">IP アドレス</string>
- <string name="advanced_port">ポート</string>
- <string name="advanced_maker">メーカー</string>
- <string name="advanced_network_name">ネットワーク名</string>
<string name="advanced_loading">統計情報を読み込んでいます…</string>
<string name="advanced_cpu_by_app">アプリ別 CPU</string>
<string name="advanced_ram_by_app">アプリ別 RAM</string>
@@ -751,6 +747,27 @@
<string name="advanced_mbps">%1$d Mbps</string>
<string name="advanced_data_used">データ使用量</string>
<string name="advanced_open_connections">開いている接続</string>
+ <string name="advanced_copy_address">アドレスをコピー</string>
+ <string name="advanced_android">Android</string>
+ <string name="advanced_updated">更新</string>
+ <string name="advanced_your_apps">追加したアプリ</string>
+ <string name="shell_open">シェル</string>
+ <string name="shell_close">シェルを閉じる</string>
+ <string name="shell_title">%1$s · %2$s</string>
+ <string name="shell_banner">%1$s(%2$s)に接続しました。\n閉じるには exit と入力するか ✕ をタップします。</string>
+ <string name="shell_trimmed">古い行は削除されました:最後の %1$d 行を表示しています。</string>
+ <string name="shell_offline_hint">テレビが戻るとコマンドを再び実行できます。</string>
+ <string name="shell_key_paste">貼り付け</string>
+ <string name="shell_key_up">前のコマンド</string>
+ <string name="shell_key_down">次のコマンド</string>
+ <string name="shell_confirm">テレビが変更されます。実行しますか? [y/N]</string>
+ <string name="shell_confirm_answered">テレビが変更されます。実行しますか? [y/N] %1$s</string>
+ <string name="shell_no_history">シェルでの実行は履歴に残らないため、ワンタップで元に戻せません。</string>
+ <string name="shell_not_run">実行しませんでした。</string>
+ <string name="shell_not_shell">ここで実行できるのは adb shell のコマンドだけです。</string>
+ <string name="shell_full_screen">%1$s には全画面のターミナルが必要です。ここでは使えません。</string>
+ <string name="shell_dropped_prefix">(「adb shell」を省きました)</string>
+ <string name="shell_lost">コマンドが終わる前にテレビとの接続が切れました。一部だけ実行された可能性があります。</string>
<string name="report_title_new_tv">このテレビの追加に協力する</string>
<string name="report_title_problem">問題を報告</string>
<string name="report_subtitle_new_tv">GitHub で cleanyourtv の「My TV」フォームを開きます</string>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 99523b6..dc89eb1 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -833,11 +833,7 @@
<string name="lists_about_libraries">Используются Kadb (Apache 2.0) и spake2-java (GPL v3). Полные тексты лицензий — в файле NOTICE.</string>
<string name="lists_about_close">Закрыть</string>
<string name="advanced_back">Назад к странице телевизора</string>
- <string name="advanced_this_tv">Этот телевизор</string>
<string name="advanced_ip_address">IP-адрес</string>
- <string name="advanced_port">Порт</string>
- <string name="advanced_maker">Производитель</string>
- <string name="advanced_network_name">Имя сети</string>
<string name="advanced_loading">Загрузка статистики…</string>
<string name="advanced_cpu_by_app">ЦП по приложениям</string>
<string name="advanced_ram_by_app">ОЗУ по приложениям</string>
@@ -871,6 +867,27 @@
<string name="advanced_mbps">%1$d Мбит/с</string>
<string name="advanced_data_used">Трафик</string>
<string name="advanced_open_connections">Открытые подключения</string>
+ <string name="advanced_copy_address">Скопировать адрес</string>
+ <string name="advanced_android">Android</string>
+ <string name="advanced_updated">Обновление</string>
+ <string name="advanced_your_apps">Ваши приложения</string>
+ <string name="shell_open">Shell</string>
+ <string name="shell_close">Закрыть Shell</string>
+ <string name="shell_title">%1$s · %2$s</string>
+ <string name="shell_banner">Подключено к %1$s (%2$s).\nВведите exit или нажмите ✕, чтобы закрыть.</string>
+ <string name="shell_trimmed">Ранние строки убраны: показаны последние %1$d.</string>
+ <string name="shell_offline_hint">Команды снова заработают, когда телевизор вернётся.</string>
+ <string name="shell_key_paste">Вставить</string>
+ <string name="shell_key_up">Предыдущая команда</string>
+ <string name="shell_key_down">Следующая команда</string>
+ <string name="shell_confirm">Это изменит телевизор. Выполнить? [y/N]</string>
+ <string name="shell_confirm_answered">Это изменит телевизор. Выполнить? [y/N] %1$s</string>
+ <string name="shell_no_history">Команды Shell не попадают в Историю, поэтому их нельзя отменить одним касанием.</string>
+ <string name="shell_not_run">Не выполнено.</string>
+ <string name="shell_not_shell">Здесь работают только команды adb shell.</string>
+ <string name="shell_full_screen">%1$s нужен полноэкранный терминал. Здесь он не поддерживается.</string>
+ <string name="shell_dropped_prefix">(убрано «adb shell»)</string>
+ <string name="shell_lost">Связь с телевизором пропала до конца команды. Возможно, она выполнилась только частично.</string>
<string name="report_title_new_tv">Помогите добавить этот телевизор</string>
<string name="report_title_problem">Сообщить о проблеме</string>
<string name="report_subtitle_new_tv">Открывает форму «My TV» от cleanyourtv на GitHub</string>
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index b745db4..f55a4e2 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -713,11 +713,7 @@
<string name="lists_about_libraries">使用了 Kadb(Apache 2.0)和 spake2-java(GPL v3)。完整许可文本见 NOTICE 文件。</string>
<string name="lists_about_close">关闭</string>
<string name="advanced_back">返回电视页面</string>
- <string name="advanced_this_tv">此电视</string>
<string name="advanced_ip_address">IP 地址</string>
- <string name="advanced_port">端口</string>
- <string name="advanced_maker">制造商</string>
- <string name="advanced_network_name">网络名称</string>
<string name="advanced_loading">正在加载统计信息…</string>
<string name="advanced_cpu_by_app">各应用 CPU 占用</string>
<string name="advanced_ram_by_app">各应用 RAM 占用</string>
@@ -751,6 +747,27 @@
<string name="advanced_mbps">%1$d Mbps</string>
<string name="advanced_data_used">已用流量</string>
<string name="advanced_open_connections">活动连接</string>
+ <string name="advanced_copy_address">复制地址</string>
+ <string name="advanced_android">Android</string>
+ <string name="advanced_updated">更新于</string>
+ <string name="advanced_your_apps">你的应用</string>
+ <string name="shell_open">Shell</string>
+ <string name="shell_close">关闭 Shell</string>
+ <string name="shell_title">%1$s · %2$s</string>
+ <string name="shell_banner">已连接到 %1$s(%2$s)。\n输入 exit 或点按 ✕ 关闭。</string>
+ <string name="shell_trimmed">较早的行已移除:只显示最后 %1$d 行。</string>
+ <string name="shell_offline_hint">电视恢复连接后即可再次运行命令。</string>
+ <string name="shell_key_paste">粘贴</string>
+ <string name="shell_key_up">上一条命令</string>
+ <string name="shell_key_down">下一条命令</string>
+ <string name="shell_confirm">这会更改电视。要运行吗?[y/N]</string>
+ <string name="shell_confirm_answered">这会更改电视。要运行吗?[y/N] %1$s</string>
+ <string name="shell_no_history">Shell 中运行的命令不会记入历史记录,因此无法一键撤消。</string>
+ <string name="shell_not_run">未运行。</string>
+ <string name="shell_not_shell">这里只能运行 adb shell 命令。</string>
+ <string name="shell_full_screen">%1$s 需要全屏终端,这里不支持。</string>
+ <string name="shell_dropped_prefix">(已去掉“adb shell”)</string>
+ <string name="shell_lost">命令完成前与电视断开连接。它可能只运行了一部分。</string>
<string name="report_title_new_tv">帮忙添加这台电视</string>
<string name="report_title_problem">报告问题</string>
<string name="report_subtitle_new_tv">在 GitHub 上打开 cleanyourtv 的“My TV”表单</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 20cb875..9991cb7 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -938,11 +938,7 @@
<!-- AdvancedScreen.kt: Advanced monitor -->
<string name="advanced_back">Back to the TV\'s page</string>
- <string name="advanced_this_tv">This TV</string>
<string name="advanced_ip_address">IP address</string>
- <string name="advanced_port">Port</string>
- <string name="advanced_maker">Maker</string>
- <string name="advanced_network_name">Network name</string>
<string name="advanced_loading">Loading stats…</string>
<string name="advanced_cpu_by_app">CPU by app</string>
<string name="advanced_ram_by_app">RAM by app</string>
@@ -979,6 +975,36 @@
<string name="advanced_mbps">%1$d Mbps</string>
<string name="advanced_data_used">Data used</string>
<string name="advanced_open_connections">Open connections</string>
+ <string name="advanced_address" translatable="false">%1$s:%2$d</string>
+ <string name="shell_prompt" translatable="false">tv:%1$s $</string>
+ <string name="shell_offline_prompt" translatable="false">tv offline $</string>
+ <string name="shell_key_tab" translatable="false">Tab</string>
+ <string name="shell_key_ctrl_c" translatable="false">Ctrl-C</string>
+ <string name="shell_answer_yes" translatable="false">y</string>
+ <string name="shell_answer_no" translatable="false">N</string>
+ <string name="shell_exit_code" translatable="false">[exit %1$d]</string>
+ <string name="shell_stopped" translatable="false">^C</string>
+ <string name="advanced_copy_address">Copy address</string>
+ <string name="advanced_android">Android</string>
+ <string name="advanced_updated">Updated</string>
+ <string name="advanced_your_apps">Your apps</string>
+ <string name="shell_open">Shell</string>
+ <string name="shell_close">Close Shell</string>
+ <string name="shell_title">%1$s · %2$s</string>
+ <string name="shell_banner">Connected to %1$s (%2$s).\nType exit or tap ✕ to close.</string>
+ <string name="shell_trimmed">Earlier lines dropped: showing the last %1$d.</string>
+ <string name="shell_offline_hint">Commands run again once the TV is back.</string>
+ <string name="shell_key_paste">Paste</string>
+ <string name="shell_key_up">Previous command</string>
+ <string name="shell_key_down">Next command</string>
+ <string name="shell_confirm">This changes the TV. Run it? [y/N]</string>
+ <string name="shell_confirm_answered">This changes the TV. Run it? [y/N] %1$s</string>
+ <string name="shell_no_history">Shell runs don\'t go in History, so there\'s no one-tap undo.</string>
+ <string name="shell_not_run">Not run.</string>
+ <string name="shell_not_shell">Only adb shell commands run here.</string>
+ <string name="shell_full_screen">%1$s needs a full-screen terminal. It isn\'t supported here.</string>
+ <string name="shell_dropped_prefix">(dropped \"adb shell\")</string>
+ <string name="shell_lost">Lost the TV before the command finished. It may have run only partly.</string>
<!-- ReportScreen.kt: Report a problem, Help add this TV -->
<string name="report_title_new_tv">Help add this TV</string>