Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
tools: tv.py --screenshot captures on the TV and pulls the file (#364)
xbsheng3553031909d8
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a6541836c..e6e74fe45 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -31,8 +31,9 @@ DynamicAnimation, no Kotlin, no Compose, no network. It targets TVs with 1 GB of- Anything that depends on a specific TV goes in `app/src/main/res/values/config.xml`, not in code.- Keep D-pad navigation deterministic. Test Up/Down/Left/Right from every edge.- Verify on a real TV, not only the emulator. The easiest way is remote key injection plus a- screenshot: `tools/tv.py 'input keyevent KEYCODE_DPAD_DOWN; screencap -p /sdcard/s.png'` then- `tools/tv.py --pull /sdcard/s.png s.png`. Include a screenshot in your pull request.+ screenshot: `tools/tv.py 'input keyevent KEYCODE_DPAD_DOWN'` then+ `tools/tv.py --screenshot shots/after.png` (the command captures on the TV and pulls the PNG, and+ creates the folder if it is missing). Include a screenshot in your pull request.- Long presses (hold OK on Settings or on a tile) can't always be injected: `input keyevent --longpress`arrives as a short press on some firmware (Android TV 8.0 on a Philips opens the app instead). Writingto the remote's own input device works, because Android then repeats the held key itself. Find thediff --git a/PROMPT.md b/PROMPT.mdindex a3766df22..443f41585 100644--- a/PROMPT.md+++ b/PROMPT.md@@ -120,9 +120,11 @@ Launcher- Keep it light: the TV has about 1 GB of RAM. No blur, no video, no network polling.Verify-- After each change, inject remote key presses over ADB, take a screenshot from the TV and look at it.+- After each change, inject remote key presses over ADB, take a screenshot from the TV and look at it:+ `tools/tv.py --screenshot shots/01-after.png` captures on the TV and pulls the PNG.Fix what you see before moving on.-- Live TV and HDMI screenshots come back empty (0 bytes); that is the TV, not a broken debloat. Check+- Live TV and HDMI screenshots come back empty (0 bytes); that is the TV, not a broken debloat, and+ `--screenshot` exits 1 with that message. Check`dumpsys activity activities | grep topResumedActivity` instead (see `docs/TROUBLESHOOTING.md`).- If a remote button relies on an accessibility helper, check that the service is enabled and boundfor the current user, then ask me to press the real button; an injected key is not proof (seediff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex b23592a85..c6a8359c5 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -77,7 +77,8 @@ Things that bit us or contributors, so they don't bite you. Commands use `tools/- **`adb exec-out screencap -p` gives a broken PNG** on some MediaTek sets (Xiaomi, and Amazon'sown Fire TV smart TVs): the binary prints `Init wrapper sys mutex successful` on stdout first.Save on the TV and pull the file instead: `screencap -p /data/local/tmp/s.png`, or cut- everything before the `\x89PNG` header.+ everything before the `\x89PNG` header. `tools/tv.py --screenshot shots/home.png` does the save,+ the pull and the cleanup in one command, and says so when the capture is 0 bytes.- **Play Protect blocked the launcher** ("unsafe app blocked, built for an older version of Android")and `pm install` hung, then failed with `INSTALL_FAILED_VERIFICATION_FAILURE`, while it targetedSDK 29. It targets 34 now; if you built an old checkout, rebuild.diff --git a/tests/test_tv_screenshot.py b/tests/test_tv_screenshot.pynew file mode 100644index 000000000..49fa49418--- /dev/null+++ b/tests/test_tv_screenshot.py@@ -0,0 +1,141 @@+"""tools/tv.py --screenshot: capture on the TV, pull the file, and say when it is empty.++PROMPT.md tells the agent to look at a screenshot after every change, and CONTRIBUTING.md asks for+one in a launcher PR, but tools/tv.py had no screenshot command, so every agent wrote its own. In+#364 (CHiQ AI PONT, Android 11) that hand-rolled helper crashed on a `shots/` folder that did not+exist yet, and the capture step stopped the whole prompt. The command therefore has to create the+folder, run `screencap` on the TV and pull the PNG (never `exec-out`, which returns a broken file on+some MediaTek sets), leave nothing behind on the TV, and name the 0-byte case for what it is: Live+TV and HDMI inputs capture empty.++The TV itself is faked, so these run anywhere adb_shell is installed or not.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import contextlib+import importlib.util+import io+import os+from pathlib import Path+import sys+import tempfile+import types+import unittest+from unittest import mock+++ROOT = Path(__file__).resolve().parents[1]+SCRIPT = ROOT / "tools" / "tv.py"+PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 32+++class FakeDevice:+ """Stands in for adb_shell's AdbDeviceTcp and records what tv.py asked it to do."""++ def __init__(self, capture=PNG):+ self.capture = capture+ self.calls = []+ self.closed = False++ def shell(self, command, read_timeout_s=None):+ self.calls.append(("shell", command))+ return ""++ def pull(self, remote, local, transport_timeout_s=None, read_timeout_s=None):+ self.calls.append(("pull", remote, local))+ Path(local).write_bytes(self.capture)++ def push(self, local, remote, transport_timeout_s=None, read_timeout_s=None):+ self.calls.append(("push", local, remote))++ def connect(self, **kwargs):+ self.calls.append(("connect",))++ def close(self):+ self.closed = True+++def load_tv():+ """Import tools/tv.py with adb_shell stubbed: these tests never open a socket."""+ stubs = {}+ for name in ("adb_shell", "adb_shell.auth"):+ stubs[name] = types.ModuleType(name)+ device = types.ModuleType("adb_shell.adb_device")+ device.AdbDeviceTcp = object+ keygen = types.ModuleType("adb_shell.auth.keygen")+ keygen.keygen = lambda path: None+ signer = types.ModuleType("adb_shell.auth.sign_pythonrsa")+ signer.PythonRSASigner = lambda pub, priv: None+ stubs.update({"adb_shell.adb_device": device, "adb_shell.auth.keygen": keygen,+ "adb_shell.auth.sign_pythonrsa": signer})+ spec = importlib.util.spec_from_file_location("cyt_tv", SCRIPT)+ module = importlib.util.module_from_spec(spec)+ os.environ.setdefault("TV_HOST", "192.0.2.1") # TEST-NET-1: nothing ever answers there+ with mock.patch.dict(sys.modules, stubs):+ spec.loader.exec_module(module)+ return module+++TV = load_tv()+++class ScreenshotTest(unittest.TestCase):+ def run_tv(self, args, capture=PNG):+ device = FakeDevice(capture)+ out, err = io.StringIO(), io.StringIO()+ with mock.patch.object(TV, "AdbDeviceTcp", return_value=device), \+ mock.patch.object(TV, "get_signer", return_value=None), \+ mock.patch.object(sys, "argv", ["tv.py", *args]), \+ contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):+ try:+ code = TV.main()+ except SystemExit as e:+ code = e.code+ return code, out.getvalue(), err.getvalue(), device++ def test_creates_the_folder_and_pulls_the_png(self):+ with tempfile.TemporaryDirectory() as tmp:+ local = Path(tmp) / "shots" / "00-stock-home.png" # the folder does not exist yet+ code, out, err, device = self.run_tv(["--screenshot", str(local)])+ self.assertEqual(code, 0, err)+ self.assertEqual(local.read_bytes(), PNG)+ self.assertIn(f"screenshot {local} ({len(PNG)} bytes)", out)++ def test_capture_runs_on_the_tv_then_pull_then_cleanup(self):+ with tempfile.TemporaryDirectory() as tmp:+ local = Path(tmp) / "home.png"+ _, _, err, device = self.run_tv(["--screenshot", str(local)])+ self.assertEqual(err, "")+ steps = [c for c in device.calls if c[0] != "connect"]+ self.assertEqual([c[0] for c in steps], ["shell", "pull", "shell"])+ self.assertEqual(steps[0][1], f"screencap -p {TV.SHOT_REMOTE}")+ self.assertEqual(steps[1][1], TV.SHOT_REMOTE)+ self.assertEqual(steps[2][1], f"rm -f {TV.SHOT_REMOTE}")+ self.assertTrue(device.closed)++ def test_empty_capture_names_the_input_and_fails(self):+ with tempfile.TemporaryDirectory() as tmp:+ local = Path(tmp) / "live-tv.png"+ code, out, err, _ = self.run_tv(["--screenshot", str(local)], capture=b"")+ self.assertEqual(code, 1)+ self.assertIn("0 bytes", err)+ self.assertIn("Live TV and HDMI", err)+ self.assertTrue(local.exists(), "the empty file stays for the user to look at")++ def test_a_flag_without_its_argument_is_a_usage_error_not_a_tv_command(self):+ for args in (["--screenshot"], ["--push", "only-one"], ["--pull"]):+ with self.subTest(args=args):+ code, _, err, device = self.run_tv(args)+ self.assertEqual(code, 2)+ self.assertIn("usage:", err)+ self.assertEqual(device.calls, [], "nothing may reach the TV")++ def test_plain_shell_command_is_unchanged(self):+ code, _, _, device = self.run_tv(["input keyevent KEYCODE_DPAD_DOWN"])+ self.assertEqual(code, 0)+ self.assertEqual([c for c in device.calls if c[0] != "connect"],+ [("shell", "input keyevent KEYCODE_DPAD_DOWN")])+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/tv.py b/tools/tv.pyindex f5d4ee231..aafbd91d1 100644--- a/tools/tv.py+++ b/tools/tv.py@@ -4,6 +4,7 @@Set TV_HOST to the TV's IP. Usage:tv.py --probe connect and print model / Android versiontv.py <shell command...> run one shell command+ tv.py --screenshot <local.png> capture the screen on the TV, then pull ittv.py --batch < commands.txt one command per line, same connectiontv.py --push <local> <remote> small files only (see b64push.py for larger ones)tv.py --pull <remote> <local>@@ -71,14 +72,66 @@ def connect(timeout=120):return dev+USAGE = """usage:+ tv.py --probe+ tv.py --screenshot <local.png>+ tv.py --push <local> <remote>+ tv.py --pull <remote> <local>+ tv.py --batch < commands.txt+ tv.py <shell command...>+"""+# Arguments each known flag takes, the flag included. The shell branch takes anything, so a flag+# with the wrong count listed here is a typo, not a command for the TV.+ARITY = {"--probe": 1, "--screenshot": 2, "--push": 3, "--pull": 3, "--batch": 1}++# screencap writes the PNG on the TV and we pull the file afterwards: adb_shell's shell() decodes+# what comes back as text, which corrupts an image, and `exec-out screencap -p` returns a broken+# PNG on some MediaTek sets (docs/TROUBLESHOOTING.md). /data/local/tmp is writable from shell.+SHOT_REMOTE = "/data/local/tmp/cleanyourtv-shot.png"+++def check_arity(args):+ """Reject a known flag with the wrong argument count before connecting.++ Without this, `--screenshot` with a destination missing falls through to the shell branch and+ the TV tries to run `--screenshot` as a command."""+ if args and args[0] in ARITY and len(args) != ARITY[args[0]]:+ sys.stderr.write(USAGE)+ sys.exit(2)+++def screenshot(dev, local):+ """Capture the TV screen into `local`. Returns 0, or 1 when the capture came back empty."""+ # Agents pass paths like shots/01-home.png before that folder exists, and the pull then fails+ # after the capture has already run on the TV (#364). Create it first.+ os.makedirs(os.path.dirname(os.path.abspath(local)), exist_ok=True)+ dev.shell(f"screencap -p {SHOT_REMOTE}", read_timeout_s=120.0)+ dev.pull(SHOT_REMOTE, local, transport_timeout_s=300.0, read_timeout_s=300.0)+ dev.shell(f"rm -f {SHOT_REMOTE}", read_timeout_s=60.0) # leave nothing behind on the TV+ size = os.path.getsize(local) if os.path.exists(local) else 0+ if size == 0:+ # 0 bytes means the input, not the connection: Live TV and HDMI captures come back empty on+ # most sets, and PROMPT.md tells the agent to look at the screen rather than the ADB link.+ print(f"captured 0 bytes into {local}: Live TV and HDMI inputs come back empty on most TVs, "+ "so check the input before the ADB connection (see docs/TROUBLESHOOTING.md)",+ file=sys.stderr)+ return 1+ print(f"screenshot {local} ({size} bytes)")+ return 0++def main():args = sys.argv[1:]+ check_arity(args)dev = connect()+ status = 0if not args or args == ["--probe"]:for p in ("ro.product.model", "ro.product.device", "ro.build.version.release","ro.build.version.sdk", "ro.build.display.id", "ro.product.manufacturer","ro.adb.secure", "service.adb.tcp.port"):print(f"{p} = {dev.shell(f'getprop {p}').strip()}")+ elif args[0] == "--screenshot":+ status = screenshot(dev, args[1])elif args[0] == "--push" and len(args) == 3:dev.push(args[1], args[2], transport_timeout_s=300.0, read_timeout_s=300.0)print(f"pushed {args[1]} -> {args[2]}")@@ -102,7 +155,8 @@ def main():out = dev.shell(" ".join(args), read_timeout_s=120.0)sys.stdout.write(out)dev.close()+ return statusif __name__ == "__main__":- main()+ sys.exit(main())