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.
TV tweaks: ad-blocking Private DNS, faster animations, clear caches, screenshot
jesse-agent-2328fe92ddecbbc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2257af4..2b1eff1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,10 @@ until this file has a section for its version.- **New:** Uninstall apps you installed yourself; apps that came with the TV can only be disabled. [#33](../../pull/33)- **Improved:** Apps that can't be changed fold into their own section below the list. [#33](../../pull/33)- **Fixed:** App icons that failed to load once now come back, with a fallback to the banner. [#34](../../pull/34)+- **New:** Block ads on the whole TV with Private DNS, AdGuard by default. [#35](../../pull/35)+- **New:** Faster animations: menus move at twice the speed. [#35](../../pull/35)+- **New:** Clear every app's cache in one tap; app data stays. [#35](../../pull/35)+- **New:** Save a screenshot of the TV to your phone. [#35](../../pull/35)## 0.1.0 — 2026-10-23diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Tweaks.kt b/adb/src/main/kotlin/app/tellyscope/adb/Tweaks.ktnew file mode 100644index 0000000..5f0c315--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Tweaks.kt@@ -0,0 +1,78 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.withContext+import okio.Sink+import java.io.IOException++/**+ * A group of global settings read and written together, so a change can be put back exactly: a+ * key that wasn't set before is deleted again, never set to a guess at the default.+ */+enum class Tweak(val keys: List<String>) {+ /** Android 9+. Mode `hostname` sends every lookup to `private_dns_specifier` over TLS. */+ PRIVATE_DNS(listOf("private_dns_mode", "private_dns_specifier")),+ ANIMATIONS(listOf("window_animation_scale", "transition_animation_scale", "animator_duration_scale")),+}++/** Settings and housekeeping that touch the whole TV rather than one app. */+class Tweaks(private val session: AdbSession) {++ /** Every key of [tweak]; null for a key that isn't set. */+ suspend fun read(tweak: Tweak): Map<String, String?> {+ val out = session.shell(tweak.keys.joinToString("; ") { "settings get global $it" }).output.lines()+ return tweak.keys.withIndex().associate { (i, k) ->+ k to out.getOrNull(i)?.trim()?.takeUnless { it.isEmpty() || it == "null" }+ }+ }++ /** Writes [values] (keys of [tweak] only); null deletes the key. False when the TV refused. */+ suspend fun write(tweak: Tweak, values: Map<String, String?>): Boolean {+ require(values.isNotEmpty() && tweak.keys.containsAll(values.keys)) { "not keys of $tweak: ${values.keys}" }+ val cmd = values.entries.joinToString(" && ") { (k, v) ->+ if (v == null) "settings delete global $k" else "settings put global $k ${shellQuote(v)}"+ }+ val r = session.shell("$cmd 2>&1")+ return r.exitCode == 0 && "Exception" !in r.output+ }++ /**+ * Asks Android to free cache space from every app (`pm trim-caches` with more than any TV+ * has); app data and sign-ins stay. Returns the space freed in KB, or null when the TV+ * doesn't report its storage.+ */+ suspend fun clearCaches(): Long? {+ val before = freeKb()+ val r = session.shell("pm trim-caches 999G 2>&1")+ if (r.exitCode != 0 || "Exception" in r.output || "Error" in r.output) {+ throw IOException(r.output.trim().ifEmpty { "the TV refused" })+ }+ val after = freeKb()+ return if (before != null && after != null) (after - before).coerceAtLeast(0) else null+ }++ private suspend fun freeKb() = Parsers.storage(session.shell("df -k /data").output)?.let { it.totalKb - it.usedKb }++ /**+ * A PNG of what the TV shows, into [sink]. `screencap` writes to a file on the TV first: shell+ * output is text, and a PNG through it would be mangled. Protected video shows as black.+ */+ suspend fun screenshot(sink: Sink) {+ val r = session.shell("screencap -p $SHOT 2>&1")+ if (r.exitCode != 0) throw IOException(r.output.trim().ifEmpty { "the TV couldn't take a screenshot" })+ try {+ runTransfer { session.pull(sink, SHOT) }+ } finally {+ withContext(NonCancellable) { runCatching { session.shell("rm -f $SHOT") } }+ }+ }++ companion object {+ private const val SHOT = "/data/local/tmp/tellyscope-shot.png"+ private val HOSTNAME = Regex("(?=.{1,253}$)([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z]{2,63}")++ /** A Private DNS provider must be a hostname: Android doesn't take an IP address there. */+ fun isHostname(s: String) = HOSTNAME.matches(s)+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/TweaksTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/TweaksTest.ktnew file mode 100644index 0000000..06e277c--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/TweaksTest.kt@@ -0,0 +1,92 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.test.runTest+import okio.Buffer+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class TweaksTest {++ @Test fun unsetKeysReadAsNull() = runTest {+ val sh = FakeShell(mapOf("settings get global private_dns_mode" to ok("hostname\nnull\n")))+ assertEquals(+ mapOf("private_dns_mode" to "hostname", "private_dns_specifier" to null),+ Tweaks(sh).read(Tweak.PRIVATE_DNS),+ )+ }++ @Test fun writeDeletesWhatWasUnset() = runTest {+ val sh = FakeShell()+ assertTrue(Tweaks(sh).write(Tweak.PRIVATE_DNS, mapOf("private_dns_mode" to "hostname", "private_dns_specifier" to null)))+ assertEquals(+ listOf("settings put global private_dns_mode 'hostname' && settings delete global private_dns_specifier 2>&1"),+ sh.ran,+ )+ }++ @Test fun valuesStayInsideTheQuotes() = runTest {+ val sh = FakeShell()+ Tweaks(sh).write(Tweak.PRIVATE_DNS, mapOf("private_dns_specifier" to "x;reboot"))+ assertEquals("settings put global private_dns_specifier 'x;reboot' 2>&1", sh.ran.single())+ }++ @Test fun foreignKeysAreRejected() = runTest {+ assertFailsWith<IllegalArgumentException> { Tweaks(FakeShell()).write(Tweak.ANIMATIONS, mapOf("adb_enabled" to "0")) }+ }++ @Test fun exceptionFromSettingsIsARefusal() = runTest {+ val sh = FakeShell(mapOf("settings put" to ok("java.lang.SecurityException: Permission denial")))+ assertFalse(Tweaks(sh).write(Tweak.ANIMATIONS, mapOf("window_animation_scale" to "0.5")))+ }++ @Test fun clearCachesReportsSpaceFreed() = runTest {+ var calls = 0+ val sh = object : AdbSession by FakeShell() {+ override suspend fun shell(command: String): ShellResult = when {+ command.startsWith("df") -> ok("Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/block/dm-0 1000 ${if (calls++ == 0) 900 else 600} 100 90% /data\n")+ else -> ok("")+ }+ }+ assertEquals(300, Tweaks(sh).clearCaches())+ }++ @Test fun clearCachesWithoutStorageStillRuns() = runTest {+ val sh = FakeShell()+ assertNull(Tweaks(sh).clearCaches())+ assertTrue("pm trim-caches 999G 2>&1" in sh.ran)+ }++ @Test fun clearCachesRefusedThrows() = runTest {+ val sh = FakeShell(mapOf("pm trim-caches" to ShellResult("Error: no", 1)))+ assertFailsWith<IOException> { Tweaks(sh).clearCaches() }+ }++ @Test fun screenshotIsPulledAndRemoved() = runTest {+ val png = byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte())+ val sh = FakeShell()+ sh.transfer.files["/data/local/tmp/tellyscope-shot.png"] = png+ val out = Buffer()+ Tweaks(sh).screenshot(out)+ assertContentEquals(png, out.readByteArray())+ assertEquals("rm -f /data/local/tmp/tellyscope-shot.png", sh.ran.last())+ }++ @Test fun failedScreencapThrows() = runTest {+ val sh = FakeShell(mapOf("screencap" to ShellResult("Error: no display", 1)))+ assertFailsWith<IOException> { Tweaks(sh).screenshot(Buffer()) }+ }++ @Test fun hostnames() {+ assertTrue(Tweaks.isHostname("dns.adguard-dns.com"))+ assertFalse(Tweaks.isHostname("94.140.14.14"))+ assertFalse(Tweaks.isHostname("dns adguard.com"))+ assertFalse(Tweaks.isHostname("-bad.com"))+ }+}diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex f7b60cf..5eeda05 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -132,6 +132,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {val pickApp = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { vm.pickedApp(it) }val pickFile = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let(vm::push) }val saveFile = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream"), vm::saveTo)+ val saveScreenshot = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("image/png"), vm::screenshotTo)Snackbars(snackbar, vm.done, vm.notice, vm::doneShown, vm::noticeShown) { vm.undo(it.entry, it.deviceId) }@@ -203,6 +204,10 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {remote = { remote = true },debloat = { debloat = true },advanced = { advanced = true },+ setDns = vm::setDns,+ setFastAnimations = vm::setFastAnimations,+ clearCaches = vm::clearCaches,+ screenshot = { saveScreenshot.launch(Copy.screenshotName(System.currentTimeMillis())) },),)}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 3dea1a1..3d9be56 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -25,6 +25,8 @@ import app.tellyscope.adb.ProtectedReasonimport app.tellyscope.adb.Remoteimport app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.PairResult+import app.tellyscope.adb.Tweak+import app.tellyscope.adb.Tweaksimport com.flyfishxu.kadb.mdns.KadbMdnsAndroidimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineScope@@ -398,6 +400,36 @@ class AdbDeviceSource(context: Context) : DeviceSource {override suspend fun reboot(deviceId: String) = Remote(session(deviceId)).reboot()+ override suspend fun tweaks(deviceId: String): TvTweaks {+ val t = Tweaks(session(deviceId))+ return TvSettings.tweaks(t.read(Tweak.PRIVATE_DNS), t.read(Tweak.ANIMATIONS))+ }++ override suspend fun change(deviceId: String, tweak: Tweak, values: Map<String, String?>, undoing: Long?): HistoryEntry {+ val t = Tweaks(session(deviceId))+ // Only the keys being written: Undo must not touch the ones this change left alone.+ val before = t.read(tweak).filterKeys { it in values }+ if (!t.write(tweak, values)) throw IllegalStateException("the TV didn't accept the change")+ return book.record(+ deviceId = key(deviceId),+ at = System.currentTimeMillis(),+ action = Action.Change,+ packageName = tweak.name,+ label = TvSettings.label(tweak, t.read(tweak)),+ undo = Action.Change,+ undoing = undoing,+ previous = before,+ )+ }++ override suspend fun clearCaches(deviceId: String): Long? {+ val freed = Tweaks(session(deviceId)).clearCaches()+ book.record(key(deviceId), System.currentTimeMillis(), Action.ClearCaches, "", TvSettings.CACHES, undo = null)+ return freed+ }++ override suspend fun screenshot(deviceId: String, sink: Sink) = Tweaks(session(deviceId)).screenshot(sink)+/*** The history key for a TV, read from it once connected and saved with it. Until it has* answered (offline since install) the address stands in, and that history moves over whendiff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 08fb2ea..a3f7adf 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -9,6 +9,7 @@ import app.tellyscope.adb.Progressimport app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFileimport app.tellyscope.adb.TvFolder+import app.tellyscope.adb.Tweakimport kotlinx.coroutines.flow.Flowimport okio.Sinkimport okio.Source@@ -98,4 +99,19 @@ 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++ /** Private DNS and animation speed as the TV has them now. */+ suspend fun tweaks(deviceId: String): TvTweaks++ /**+ * Writes [values] for [tweak] and records the values from before, so Undo puts them back+ * exactly. [undoing] is the history entry this reverses. Throws with the reason when refused.+ */+ suspend fun change(deviceId: String, tweak: Tweak, values: Map<String, String?>, undoing: Long? = null): HistoryEntry++ /** Frees every app's cache, keeping app data and sign-ins, and records it. Returns KB freed, or null when the TV can't say. */+ suspend fun clearCaches(deviceId: String): Long?++ /** A PNG of what the TV shows right now, into [sink]. */+ suspend fun screenshot(deviceId: String, sink: Sink)}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex 7115d5d..bccc9da 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -9,7 +9,9 @@ import app.tellyscope.adb.Progressimport app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFileimport app.tellyscope.adb.TvFolder+import app.tellyscope.adb.Tweakimport java.io.File+import java.io.IOExceptionimport java.time.YearMonthimport kotlin.random.Randomimport kotlinx.coroutines.currentCoroutineContext@@ -199,13 +201,13 @@ class FakeDeviceSource(Action.Disable -> list[i] = app.copy(enabled = false)Action.Enable -> list[i] = app.copy(enabled = true)Action.Uninstall -> list.removeAt(i)- Action.Stop, Action.Open -> Unit+ Action.Stop, Action.Open, Action.Change, Action.ClearCaches -> Unit}val undo = when (action) {Action.Stop -> Action.OpenAction.Disable -> Action.EnableAction.Enable -> Action.Disable- Action.Open, Action.Uninstall -> null+ Action.Open, Action.Uninstall, Action.Change, Action.ClearCaches -> null}return book.record(deviceId, clock(), action, packageName, app.label, undo, undoing)}@@ -302,6 +304,35 @@ class FakeDeviceSource(return true}+ /** Global settings per TV, for the tweaks card. */+ private val settings = mutableMapOf<String, MutableMap<String, String?>>()++ private fun settingsFor(deviceId: String) = settings.getOrPut(deviceId) { mutableMapOf("private_dns_mode" to "opportunistic") }++ override suspend fun tweaks(deviceId: String): TvTweaks {+ val s = settingsFor(deviceId)+ return TvSettings.tweaks(s, s)+ }++ override suspend fun change(deviceId: String, tweak: Tweak, values: Map<String, String?>, undoing: Long?): HistoryEntry {+ delay(300)+ val s = settingsFor(deviceId)+ val before = values.keys.associateWith { s[it] }+ s.putAll(values)+ return book.record(deviceId, clock(), Action.Change, tweak.name, TvSettings.label(tweak, s), Action.Change, undoing, before)+ }++ override suspend fun clearCaches(deviceId: String): Long {+ delay(800)+ book.record(deviceId, clock(), Action.ClearCaches, "", TvSettings.CACHES, undo = null)+ return 1_340_000+ }++ override suspend fun screenshot(deviceId: String, sink: Sink) {+ delay(500)+ throw IOException("the demo TV has no screen to capture")+ }+private companion object {val fakeList = DeviceList(id = "xgimi-horizon-pro",diff --git a/app/src/main/java/app/tellyscope/data/HistoryBook.kt b/app/src/main/java/app/tellyscope/data/HistoryBook.ktindex ca0c32a..b2715a6 100644--- a/app/src/main/java/app/tellyscope/data/HistoryBook.kt+++ b/app/src/main/java/app/tellyscope/data/HistoryBook.kt@@ -3,6 +3,8 @@package app.tellyscope.dataimport java.io.File+import java.net.URLDecoder+import java.net.URLEncoderimport kotlinx.coroutines.CancellationException/**@@ -42,12 +44,13 @@ class HistoryBook(private val file: File? = null) {label: String,undo: Action?,undoing: Long? = null,+ previous: Map<String, String?>? = null,): HistoryEntry {if (undoing != null) {val i = entries.indexOfFirst { it.id == undoing }if (i >= 0) entries[i] = entries[i].copy(undoneAt = at)}- val entry = HistoryEntry((entries.maxOfOrNull { it.id } ?: 0) + 1, deviceId, at, action, packageName, label, undo, null)+ val entry = HistoryEntry((entries.maxOfOrNull { it.id } ?: 0) + 1, deviceId, at, action, packageName, label, undo, null, previous)entries += entrysave()return entry@@ -100,7 +103,7 @@ class HistoryBook(private val file: File? = null) {listOf(VERSION, "e", e.deviceId, e.id.toString(), e.at.toString(), e.action.name, e.packageName,clean(e.label), e.undo?.name.orEmpty(), e.undoneAt?.toString().orEmpty(),- )+ ) + listOfNotNull(e.previous?.let(::encode))}val tmp = File(f.path + ".tmp")tmp.writeText(lines.joinToString("") { it.joinToString("\t") + "\n" })@@ -116,7 +119,8 @@ class HistoryBook(private val file: File? = null) {if (f.size < 4 || f[0] != VERSION) returnwhen (f[1]) {"b" -> baselines[f[2]] = f[3].split(',').filter { it.isNotEmpty() }.toSet()- "e" -> if (f.size == 10) {+ // An 11th field carries a setting's previous values; older entries have 10.+ "e" -> if (f.size == 10 || f.size == 11) {entries += HistoryEntry(id = f[3].toLongOrNull() ?: return,deviceId = f[2],@@ -126,6 +130,7 @@ class HistoryBook(private val file: File? = null) {label = f[7],undo = action(f[8]),undoneAt = f[9].toLongOrNull(),+ previous = f.getOrNull(10)?.let(::decode),)}}@@ -134,6 +139,14 @@ class HistoryBook(private val file: File? = null) {private fun action(s: String) = Action.entries.firstOrNull { it.name == s }private fun clean(s: String) = s.replace(Regex("[\\t\\r\\n]"), " ")++ /** "key=value,key" with values URL-encoded; a bare key was unset. */+ private fun encode(m: Map<String, String?>) =+ m.entries.joinToString(",") { (k, v) -> if (v == null) k else "$k=" + URLEncoder.encode(v, "UTF-8") }++ private fun decode(s: String): Map<String, String?> = s.split(',').filter { it.isNotEmpty() }.associate {+ it.substringBefore('=') to (if ('=' in it) URLDecoder.decode(it.substringAfter('='), "UTF-8") else null)+ }}private const val VERSION = "v1"diff --git a/app/src/main/java/app/tellyscope/data/Model.kt b/app/src/main/java/app/tellyscope/data/Model.ktindex 5385060..dd06814 100644--- a/app/src/main/java/app/tellyscope/data/Model.kt+++ b/app/src/main/java/app/tellyscope/data/Model.kt@@ -116,7 +116,11 @@ data class NetworkInfo(val traffic: List<AppTraffic>,)-enum class Action { Stop, Disable, Enable, Open, Uninstall }+/**+ * [Change] sets one [app.tellyscope.adb.Tweak]: its entry's packageName is the tweak's name and+ * [HistoryEntry.previous] holds what Undo writes back. [ClearCaches] has no undo.+ */+enum class Action { Stop, Disable, Enable, Open, Uninstall, Change, ClearCaches }data class HistoryEntry(val id: Long,@@ -128,4 +132,14 @@ data class HistoryEntry(/** What the undo button runs; null when there is nothing to undo. */val undo: Action?,val undoneAt: Long?,+ /** For [Action.Change]: the settings as they were before, null for a key that wasn't set. */+ val previous: Map<String, String?>? = null,+)++/** The TV-wide settings shown on its page; null for one the TV doesn't report. */+data class TvTweaks(+ /** The Private DNS provider, when one is set and in use; null means Automatic or Off. */+ val dnsHost: String?,+ /** Window animation scale, e.g. "1.0"; null when unset (Android's 1×). */+ val animationScale: String?,)diff --git a/app/src/main/java/app/tellyscope/data/TvSettings.kt b/app/src/main/java/app/tellyscope/data/TvSettings.ktnew file mode 100644index 0000000..f88a7e2--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/TvSettings.kt@@ -0,0 +1,40 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import app.tellyscope.adb.Tweak++/** What each TV tweak writes, and how History names it afterwards. */+object TvSettings {+ /** AdGuard's public ad-blocking resolver: what the ad-blocking switch offers first. */+ const val ADGUARD = "dns.adguard-dns.com"+ const val FAST = "0.5"+ /** History's name for a cache clear: "Cleared app caches". */+ const val CACHES = "app caches"++ /** Off goes back to Automatic, Android's default, rather than turning encrypted DNS off. */+ fun dns(host: String?): Map<String, String?> =+ if (host == null) mapOf("private_dns_mode" to "opportunistic")+ else mapOf("private_dns_mode" to "hostname", "private_dns_specifier" to host)++ fun animations(fast: Boolean): Map<String, String?> = Tweak.ANIMATIONS.keys.associateWith { if (fast) FAST else "1.0" }++ fun tweaks(dns: Map<String, String?>, animations: Map<String, String?>) = TvTweaks(+ dnsHost = dns["private_dns_specifier"]?.takeIf { dns["private_dns_mode"] == "hostname" },+ animationScale = animations["window_animation_scale"],+ )++ /** History's line for a change that left the TV at [values]. */+ fun label(tweak: Tweak, values: Map<String, String?>): String = when (tweak) {+ Tweak.PRIVATE_DNS -> when (values["private_dns_mode"]) {+ "hostname" -> "Private DNS set to ${values["private_dns_specifier"]}"+ "off" -> "Private DNS turned off"+ else -> "Private DNS set to Automatic"+ }+ Tweak.ANIMATIONS -> when (val v = values["window_animation_scale"]?.toFloatOrNull()) {+ null, 1f -> "Animations at normal speed"+ 0f -> "Animations turned off"+ else -> "Animations at ${v.toString().removeSuffix(".0")}×"+ }+ }+}diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex a19e499..232ba0f 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -9,8 +9,12 @@ import app.tellyscope.data.Actionimport app.tellyscope.data.AppNamesimport app.tellyscope.data.DeviceStateimport app.tellyscope.data.Snapshot+import app.tellyscope.data.TvSettings+import java.text.SimpleDateFormatimport java.time.YearMonthimport java.time.format.DateTimeFormatter+import java.util.Date+import java.util.Locale/*** Every user-facing sentence about actions and time lives here so wording is@@ -23,6 +27,7 @@ object Copy {Action.Enable -> "Turn on"Action.Open -> "Open"Action.Uninstall -> "Uninstall"+ Action.Change, Action.ClearCaches -> error("$action isn't an app action")}fun confirm(action: Action) = when (action) {@@ -31,6 +36,7 @@ object Copy {Action.Enable -> "Yes, turn it on"Action.Open -> "Yes, open it"Action.Uninstall -> "Yes, uninstall it"+ Action.Change, Action.ClearCaches -> error("$action isn't an app action")}/**@@ -44,6 +50,7 @@ object Copy {Action.Enable -> "Turns $who back on."Action.Open -> "Opens $who on the TV."Action.Uninstall -> "Removes $who and everything saved in it. This can't be undone; to get it back, install it again."+ Action.Change, Action.ClearCaches -> error("$action isn't an app action")}}@@ -53,6 +60,9 @@ object Copy {Action.Enable -> "Turned on $app"Action.Open -> "Opened $app"Action.Uninstall -> "Uninstalled $app"+ // A setting's label is the whole sentence: "Private DNS set to …".+ Action.Change -> app+ Action.ClearCaches -> "Cleared $app"}/**@@ -276,4 +286,30 @@ object Copy {fun restarting(minutes: Long) =if (minutes < 3) "Tellyscope reconnects on its own when the TV is back, usually within a couple of minutes."else "Taking a while. Some TVs turn network debugging off when they restart. If it doesn't come back, turn it on again in the TV's Developer options."++ const val TWEAKS = "TV tweaks"+ const val DNS_TITLE = "Block ads with Private DNS"+ fun dnsState(host: String?) = host?.let { "On: $it" } ?: "Off. Turn on to block ads and trackers in every app on the TV."+ const val DNS_DIALOG = "Block ads on the whole TV?"+ const val DNS_TEXT = "The TV will look up every address through this ad-blocking DNS provider. AdGuard is free and needs no account. " ++ "If the TV loses its internet afterwards, tap Undo in History to put it back."+ const val DNS_FIELD = "DNS provider"+ const val DNS_BAD = "Enter a hostname like dns.adguard-dns.com. An IP address won't work here."+ const val DNS_CONFIRM = "Turn on"+ const val ANIMATIONS_TITLE = "Faster animations"+ fun animationsState(scale: String?) =+ if (scale == TvSettings.FAST) "On: menus move at twice the speed"+ else "Off. Turn on to make menus feel snappier."+ const val CACHES_TITLE = "Clear all app caches"+ const val CACHES_TEXT = "Frees space by clearing every app's temporary files. App data and sign-ins stay."+ const val CACHES_BUTTON = "Clear caches"+ fun cachesCleared(freedKb: Long?) =+ if (freedKb == null || freedKb <= 0) "Cleared app caches" else "Cleared app caches, freed ${bytes(freedKb * 1024)}"+ const val SCREENSHOT_TITLE = "Screenshot"+ const val SCREENSHOT_TEXT = "Saves what the TV shows to your phone. Protected video, like most streaming apps, shows as black."+ const val SCREENSHOT_BUTTON = "Take screenshot"+ fun screenshotName(at: Long) =+ "TV screenshot " + SimpleDateFormat("yyyy-MM-dd HH.mm.ss", Locale.ROOT).format(Date(at)) + ".png"+ const val SCREENSHOT_SAVED = "Screenshot saved to your phone"+ const val SCREENSHOT_FAILED = "Couldn't take a screenshot. Check the TV is still connected."}diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex 7960280..0ade683 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -122,6 +122,12 @@ data class DeviceActions(val debloat: () -> Unit = {},/** Opens the Advanced screen: every number, per-app CPU and RAM, processes and network. */val advanced: () -> Unit = {},+ /** Ad-blocking Private DNS through the given hostname; null goes back to Automatic. */+ val setDns: (String?) -> Unit = {},+ val setFastAnimations: (Boolean) -> Unit = {},+ val clearCaches: () -> Unit = {},+ /** Asks where to save a screenshot of the TV on the phone, then takes it. */+ val screenshot: () -> Unit = {},)/** Off while the remote is made faster: the device page hides its Remote button. */@@ -250,6 +256,9 @@ fun DeviceScreen(if (!offline && q.isEmpty()) section("files", "Files on the TV", ui.files.list?.size ?: 0) {FilesBlock(ui.files, state.now, actions)}+ if (!offline && q.isEmpty()) section("tweaks", Copy.TWEAKS, 0) {+ TweaksBlock(ui, actions)+ }section("history", "History", ui.history.size) {HistoryList(ui.history, state.now, actions.undo, restoring = ui.busy == RESTORING, onRestoreAll = actions.restoreAll)}diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 2eddd23..62f27a2 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -13,6 +13,7 @@ import app.tellyscope.adb.Remoteimport app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFileimport app.tellyscope.adb.TvFolder+import app.tellyscope.adb.Tweakimport app.tellyscope.adb.installKindimport app.tellyscope.data.Actionimport app.tellyscope.data.AppInfo@@ -30,6 +31,8 @@ import app.tellyscope.data.ScanHitimport app.tellyscope.data.ScanProgressimport app.tellyscope.data.Snapshotimport app.tellyscope.data.Suggestions+import app.tellyscope.data.TvSettings+import app.tellyscope.data.TvTweaksimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Jobimport kotlinx.coroutines.delay@@ -75,6 +78,8 @@ data class DeviceUi(val transfer: TransferUi? = null,/** The TV's debloat list; null while it loads. */val lists: Suggestions? = null,+ /** Private DNS and animation speed; null until read, or when the TV wouldn't say. */+ val tweaks: TvTweaks? = null,)data class SideloadUi(@@ -129,6 +134,10 @@ const val RESTORING = "restore"/** [DeviceUi.busy] value while the ticked suggestions are being disabled. */const val DISABLING = "lists"+/** [DeviceUi.busy] values for the TV tweaks; a setting change uses its [Tweak] name. */+const val CLEARING = "caches"+const val SCREENSHOT = "screenshot"+class TellyscopeViewModel(private val source: DeviceSource,private val storage: PhoneStorage? = null,@@ -290,6 +299,8 @@ class TellyscopeViewModel(// Read first: update {} may run its block again, and must never call the TV.val apps = source.apps(id!!)updateDevice(id) { it.copy(apps = apps) }+ val tweaks = source.tweaks(id)+ updateDevice(id) { it.copy(tweaks = tweaks) }loadFiles()while (true) {val net = source.network(id!!)@@ -360,7 +371,73 @@ class TellyscopeViewModel(*/fun undo(entry: HistoryEntry, deviceId: String? = _state.value.selectedId) {val undo = entry.undo ?: return- run(entry.packageName, undo, undoing = entry.id, id = deviceId)+ if (entry.action == Action.Change) {+ change(Tweak.valueOf(entry.packageName), entry.previous.orEmpty(), undoing = entry.id, id = deviceId)+ } else {+ run(entry.packageName, undo, undoing = entry.id, id = deviceId)+ }+ }++ /** Ad-blocking Private DNS through [host], or back to Automatic with null. */+ fun setDns(host: String?) = change(Tweak.PRIVATE_DNS, TvSettings.dns(host))++ fun setFastAnimations(fast: Boolean) = change(Tweak.ANIMATIONS, TvSettings.animations(fast))++ private fun change(tweak: Tweak, values: Map<String, String?>, undoing: Long? = null, id: String? = _state.value.selectedId) {+ if (id == null) return+ updateDevice(id) { it.copy(busy = tweak.name) }+ viewModelScope.launch {+ val (entry, tweaks) = try {+ source.change(id, tweak, values, undoing) to source.tweaks(id)+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ updateDevice(id) { it.copy(busy = null) }+ _notice.value = e.message?.replaceFirstChar(Char::uppercase) ?: "That didn't work."+ return@launch+ }+ val history = source.history(id)+ updateDevice(id) { it.copy(tweaks = tweaks, busy = null, history = history) }+ if (undoing == null) _done.value = Done(id, entry)+ }+ }++ fun clearCaches() {+ val id = _state.value.selectedId ?: return+ updateDevice(id) { it.copy(busy = CLEARING) }+ viewModelScope.launch {+ _notice.value = try {+ Copy.cachesCleared(source.clearCaches(id))+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ e.message?.replaceFirstChar(Char::uppercase) ?: "That didn't work."+ }+ val history = source.history(id)+ updateDevice(id) { it.copy(busy = null, history = history) }+ }+ }++ /** The "save as" picker's answer for a screenshot; null when the user backed out. */+ fun screenshotTo(uri: Uri?) {+ val id = _state.value.selectedId ?: return+ val storage = storage ?: return+ if (uri == null) return+ updateDevice(id) { it.copy(busy = SCREENSHOT) }+ viewModelScope.launch {+ try {+ storage.create(uri).use { sink -> source.screenshot(id, sink) }+ _notice.value = Copy.SCREENSHOT_SAVED+ } catch (e: CancellationException) {+ storage.delete(uri)+ throw e+ } catch (_: Exception) {+ storage.delete(uri)+ _notice.value = Copy.SCREENSHOT_FAILED+ } finally {+ updateDevice(id) { it.copy(busy = null) }+ }+ }}/** Changes [id]'s page only while it is still the one shown; a result for another TV is dropped. */diff --git a/app/src/main/java/app/tellyscope/ui/TweaksBlock.kt b/app/src/main/java/app/tellyscope/ui/TweaksBlock.ktnew file mode 100644index 0000000..f853529--- /dev/null+++ b/app/src/main/java/app/tellyscope/ui/TweaksBlock.kt@@ -0,0 +1,108 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.selection.toggleable+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.unit.dp+import app.tellyscope.adb.Tweak+import app.tellyscope.adb.Tweaks+import app.tellyscope.data.TvSettings++/**+ * Whole-TV settings and housekeeping. The two switches land in History with Undo; clearing+ * caches says up front what it keeps; a screenshot asks where to save it first.+ */+@Composable+fun TweaksBlock(ui: DeviceUi, actions: DeviceActions) {+ val tweaks = ui.tweaks+ var askDns by rememberSaveable { mutableStateOf(false) }+ val dnsOn = tweaks?.dnsHost != null+ if (ui.busy in TWEAK_BUSY) LinearProgressIndicator(Modifier.fillMaxWidth())+ SwitchRow(Copy.DNS_TITLE, Copy.dnsState(tweaks?.dnsHost), dnsOn, enabled = tweaks != null && ui.busy == null) { on ->+ if (on) askDns = true else actions.setDns(null)+ }+ val fast = tweaks?.animationScale == TvSettings.FAST+ SwitchRow(Copy.ANIMATIONS_TITLE, Copy.animationsState(tweaks?.animationScale), fast, enabled = tweaks != null && ui.busy == null) {+ actions.setFastAnimations(it)+ }+ ButtonRow(Copy.CACHES_TITLE, Copy.CACHES_TEXT, Copy.CACHES_BUTTON, enabled = ui.busy == null, actions.clearCaches)+ ButtonRow(Copy.SCREENSHOT_TITLE, Copy.SCREENSHOT_TEXT, Copy.SCREENSHOT_BUTTON, enabled = ui.busy == null, actions.screenshot)+ if (askDns) DnsDialog(onDismiss = { askDns = false }) { host -> askDns = false; actions.setDns(host) }+}++@Composable+private fun SwitchRow(title: String, state: String, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) {+ // The whole row toggles, not just the thumb: a bigger target, read as one switch by TalkBack.+ Row(+ Modifier.fillMaxWidth().toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChange).padding(vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(title, style = MaterialTheme.typography.bodyLarge)+ Text(state, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ Spacer(Modifier.width(12.dp))+ Switch(checked = checked, onCheckedChange = null, enabled = enabled)+ }+}++@Composable+private fun ButtonRow(title: String, text: String, button: String, enabled: Boolean, onClick: () -> Unit) {+ Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(title, style = MaterialTheme.typography.bodyLarge)+ Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ FilledTonalButton(onClick = onClick, enabled = enabled) { Text(button) }+ }+}++/** AdGuard is filled in; any other DoT hostname works too. */+@Composable+private fun DnsDialog(onDismiss: () -> Unit, onConfirm: (String) -> Unit) {+ var host by rememberSaveable { mutableStateOf(TvSettings.ADGUARD) }+ val valid = Tweaks.isHostname(host.trim())+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(Copy.DNS_DIALOG) },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(Copy.DNS_TEXT)+ OutlinedTextField(+ value = host,+ onValueChange = { host = it },+ label = { Text(Copy.DNS_FIELD) },+ singleLine = true,+ isError = !valid,+ supportingText = { if (!valid) Text(Copy.DNS_BAD) },+ )+ }+ },+ confirmButton = { TextButton(onClick = { onConfirm(host.trim()) }, enabled = valid) { Text(Copy.DNS_CONFIRM) } },+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },+ )+}++/** [DeviceUi.busy] values that belong to this block. */+private val TWEAK_BUSY = Tweak.entries.map { it.name } + listOf(CLEARING, SCREENSHOT)diff --git a/app/src/test/java/app/tellyscope/HistoryBookTest.kt b/app/src/test/java/app/tellyscope/HistoryBookTest.ktindex bb7bdd9..86248de 100644--- a/app/src/test/java/app/tellyscope/HistoryBookTest.kt+++ b/app/src/test/java/app/tellyscope/HistoryBookTest.kt@@ -22,6 +22,13 @@ class HistoryBookTest {private val tv = "tv-1"+ @Test fun aSettingsPreviousValuesSurviveARestart() {+ val file = tmp.root.resolve("history.tsv")+ val previous = mapOf("private_dns_mode" to "opportunistic", "private_dns_specifier" to null, "odd" to "a=b,c")+ val change = HistoryBook(file).record(tv, 1_000, Action.Change, "PRIVATE_DNS", "Private DNS set to x", Action.Change, previous = previous)+ assertEquals(listOf(change), HistoryBook(file).entries(tv))+ }+@Test fun historyAndUndoSurviveARestart() {val file = tmp.root.resolve("history.tsv")val before = HistoryBook(file)diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex 4fbc866..1f0b7e7 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -33,6 +33,8 @@ import app.tellyscope.data.Deviceimport app.tellyscope.data.DeviceStateimport app.tellyscope.data.FakeDeviceSourceimport app.tellyscope.data.HistoryEntry+import app.tellyscope.data.TvSettings+import app.tellyscope.data.TvTweaksimport app.tellyscope.data.ListEntryimport app.tellyscope.data.PickedAppimport app.tellyscope.data.ScanHit@@ -46,6 +48,7 @@ import app.tellyscope.ui.DebloatScreenimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceScreenimport app.tellyscope.ui.Copy+import app.tellyscope.ui.TweaksBlockimport app.tellyscope.ui.DeviceUiimport app.tellyscope.ui.DisableDialogimport app.tellyscope.ui.ForgetDialog@@ -396,6 +399,32 @@ class ScreenshotTest {Surface { Column(Modifier.padding(16.dp)) { FilesBlock(FilesUi(TvFolder.DOWNLOAD, files), now, DeviceActions()) } }}+ @Test fun device_tweaks() = shot("16_device_tweaks") {+ val ui = DeviceUi(tweaks = TvTweaks(dnsHost = TvSettings.ADGUARD, animationScale = null))+ Surface { Column(Modifier.padding(16.dp)) { TweaksBlock(ui, DeviceActions()) } }+ }++ @Test fun device_tweaksDns() = shot("16_device_tweaks_dns", screen = true, before = {+ compose.onNodeWithText(Copy.DNS_TITLE).performClick()+ Unit+ }) {+ Surface { Column(Modifier.padding(16.dp)) { TweaksBlock(DeviceUi(tweaks = TvTweaks(null, null)), DeviceActions()) } }+ }++ @Config(qualifiers = "w411dp-h2600dp-xxhdpi")+ @Test fun device_tweaksInHistory() {+ val history = listOf(+ HistoryEntry(3, xgimi.ip, now - 20_000, Action.ClearCaches, "", TvSettings.CACHES, null, null),+ HistoryEntry(2, xgimi.ip, now - 60_000, Action.Change, "ANIMATIONS", "Animations at 0.5×", Action.Change, null, mapOf("window_animation_scale" to null)),+ HistoryEntry(1, xgimi.ip, now - 90_000, Action.Change, "PRIVATE_DNS", "Private DNS set to ${TvSettings.ADGUARD}", Action.Change, null, mapOf("private_dns_mode" to "opportunistic")),+ )+ shot("16_device_tweaks_history", before = {+ compose.onNodeWithText("Apps").performClick()+ compose.onNodeWithText("History").performClick()+ Unit+ }) { DeviceScreen(deviceState { copy(history = history) }, DeviceActions()) }+ }+private val dir = Files.createTempDirectory("shots").toFile()private fun apk(name: String, bytes: Long) = File(dir, name).also { RandomAccessFile(it, "rw").use { f -> f.setLength(bytes) } }private val kodi = PickedApp(listOf(apk("kodi.apk", 74_000_000)), ApkInfo("org.xbmc.kodi", 2101, "21.1"), "Kodi")