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: press remote keys first, and tell a failed capture from an empty one
sim4b026f841b24
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e6e74fe45..4e6d96a3b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -31,9 +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'` 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.+ screenshot: `tools/tv.py --screenshot shots/after.png DPAD_DOWN` presses the key, waits a second+ (`--wait` changes that), captures on the TV and pulls the PNG, creating 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 9b192574b..a85046dca 100644--- a/PROMPT.md+++ b/PROMPT.md@@ -135,10 +135,11 @@ LauncherVerify- 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.+ `tools/tv.py --screenshot shots/01-after.png DPAD_RIGHT` presses the key, then captures on the TV and+ pulls the PNG (leave the keys off to capture what is already on screen).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, and- `--screenshot` exits 1 with that message. Check+- Live TV, HDMI and some streaming apps (Netflix) give empty screenshots (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 the screen looks enlarged and clipped after an install or a reboot, check the display overridesbefore editing the launcher grid: `wm size` and `wm density` show a physical value next to andiff --git a/README.md b/README.mdindex 9e9645859..37834d378 100644--- a/README.md+++ b/README.md@@ -285,7 +285,7 @@ tools/theme.sh themes/aurora # push a theme; --r| Tool | What it does ||---|---|-| [`tools/tv.py`](tools/tv.py) | Pure-Python ADB client: shell, batch, push, pull. Works where the stock `adb` binary is blocked. |+| [`tools/tv.py`](tools/tv.py) | Pure-Python ADB client: shell, batch, push, pull, and screenshots, optionally pressing remote keys first. Works where the stock `adb` binary is blocked. || [`tools/b64push.py`](tools/b64push.py) | Uploads large files such as APKs in base64 chunks and verifies the checksum. || [`tools/relay.py`](tools/relay.py) | Forwards a local port to the TV's ADB port, for assistants whose sandbox can't reach your network. Listens on this computer only. [Guide](tools/relay.md). || [`tools/disable.sh`](tools/disable.sh), [`restore.sh`](tools/restore.sh) | Apply or undo a debloat list, the undo from the state recorded before the change. |diff --git a/tests/test_tv_screenshot.py b/tests/test_tv_screenshot.pyindex 49fa49418..2158656b6 100644--- a/tests/test_tv_screenshot.py+++ b/tests/test_tv_screenshot.py@@ -8,6 +8,9 @@ folder, run `screencap` on the TV and pull the PNG (never `exec-out`, which retusome MediaTek sets), leave nothing behind on the TV, and name the 0-byte case for what it is: LiveTV and HDMI inputs capture empty.+It can also press remote keys first (#560), so one command shows what a key did: key names are checked+before anything reaches the TV, since they end up in a shell command there.+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@@ -32,14 +35,15 @@ PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 32class FakeDevice:"""Stands in for adb_shell's AdbDeviceTcp and records what tv.py asked it to do."""- def __init__(self, capture=PNG):+ def __init__(self, capture=PNG, screencap_says="rc=0\n"):self.capture = capture+ self.screencap_says = screencap_saysself.calls = []self.closed = Falsedef shell(self, command, read_timeout_s=None):self.calls.append(("shell", command))- return ""+ return self.screencap_says if "screencap" in command else ""def pull(self, remote, local, transport_timeout_s=None, read_timeout_s=None):self.calls.append(("pull", remote, local))@@ -80,11 +84,13 @@ TV = load_tv()class ScreenshotTest(unittest.TestCase):- def run_tv(self, args, capture=PNG):- device = FakeDevice(capture)+ def run_tv(self, args, capture=PNG, screencap_says="rc=0\n"):+ device = FakeDevice(capture, screencap_says)+ self.sleeps = []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(TV.time, "sleep", side_effect=self.sleeps.append), \mock.patch.object(sys, "argv", ["tv.py", *args]), \contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):try:@@ -108,7 +114,7 @@ class ScreenshotTest(unittest.TestCase):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[0][1], f"rm -f {TV.SHOT_REMOTE}; screencap -p {TV.SHOT_REMOTE}; echo rc=$?")self.assertEqual(steps[1][1], TV.SHOT_REMOTE)self.assertEqual(steps[2][1], f"rm -f {TV.SHOT_REMOTE}")self.assertTrue(device.closed)@@ -122,6 +128,61 @@ class ScreenshotTest(unittest.TestCase):self.assertIn("Live TV and HDMI", err)self.assertTrue(local.exists(), "the empty file stays for the user to look at")+ def test_netflix_style_capture_exit_1_with_no_bytes_is_the_empty_case(self):+ with tempfile.TemporaryDirectory() as tmp:+ code, _, err, _ = self.run_tv(["--screenshot", str(Path(tmp) / "netflix.png")],+ capture=b"", screencap_says="rc=1\n")+ self.assertEqual(code, 1)+ self.assertIn("0 bytes", err)+ self.assertIn("Netflix", err)++ def test_failed_screencap_says_so_and_pulls_nothing(self):+ with tempfile.TemporaryDirectory() as tmp:+ local = Path(tmp) / "home.png"+ code, _, err, device = self.run_tv(["--screenshot", str(local)],+ screencap_says="screencap: not found\nrc=127\n")+ self.assertEqual(code, 1)+ self.assertIn("screencap failed on the TV (exit status 127): screencap: not found", err)+ self.assertNotIn("pull", [c[0] for c in device.calls])+ self.assertEqual(device.calls[-1], ("shell", f"rm -f {TV.SHOT_REMOTE}"))++ def test_a_damaged_pull_is_not_passed_off_as_a_png(self):+ with tempfile.TemporaryDirectory() as tmp:+ code, _, err, _ = self.run_tv(["--screenshot", str(Path(tmp) / "home.png")], capture=b"garbage")+ self.assertEqual(code, 1)+ self.assertIn("is not a PNG", err)++ def test_keys_are_pressed_in_order_before_the_capture(self):+ with tempfile.TemporaryDirectory() as tmp:+ local = Path(tmp) / "right.png"+ code, _, err, device = self.run_tv(["--screenshot", str(local), "HOME", "KEYCODE_DPAD_RIGHT", "83"])+ self.assertEqual(code, 0, err)+ shells = [c[1] for c in device.calls if c[0] == "shell"]+ self.assertEqual(shells[:3], ["input keyevent KEYCODE_HOME", "input keyevent KEYCODE_DPAD_RIGHT",+ "input keyevent 83"])+ self.assertIn("screencap", shells[3])+ self.assertEqual(self.sleeps, [TV.KEY_GAP_S, TV.KEY_GAP_S, 1.0])++ def test_wait_sets_the_pause_after_the_last_key(self):+ with tempfile.TemporaryDirectory() as tmp:+ code, _, err, _ = self.run_tv(["--screenshot", str(Path(tmp) / "a.png"), "BACK", "--wait", "2.5"])+ self.assertEqual(code, 0, err)+ self.assertEqual(self.sleeps, [2.5])++ def test_no_keys_means_no_pause(self):+ with tempfile.TemporaryDirectory() as tmp:+ self.run_tv(["--screenshot", str(Path(tmp) / "a.png")])+ self.assertEqual(self.sleeps, [])++ def test_bad_key_names_and_waits_never_reach_the_tv(self):+ for args in (["--screenshot", "a.png", "home"], ["--screenshot", "a.png", "HOME;reboot"],+ ["--screenshot", "a.png", "--wait", "-1"], ["--screenshot", "a.png", "--wait", "soon"]):+ 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_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):diff --git a/tools/tv.py b/tools/tv.pyindex aafbd91d1..601b0d400 100644--- a/tools/tv.py+++ b/tools/tv.py@@ -4,13 +4,16 @@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 it+ tv.py --screenshot <local.png> [KEY ...] [--wait SECONDS]+ capture the screen on the TV, then pull it; press remote keys firsttv.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>"""import os+import reimport sys+import timefrom adb_shell.adb_device import AdbDeviceTcpfrom adb_shell.auth.keygen import keygen@@ -74,7 +77,7 @@ def connect(timeout=120):USAGE = """usage:tv.py --probe- tv.py --screenshot <local.png>+ tv.py --screenshot <local.png> [KEY ...] [--wait SECONDS]tv.py --push <local> <remote>tv.py --pull <remote> <local>tv.py --batch < commands.txt@@ -82,12 +85,17 @@ USAGE = """usage:"""# 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}+# --screenshot takes its file and then any number of keys, so it is checked by screenshot_args instead.+ARITY = {"--probe": 1, "--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"+PNG = b"\x89PNG\r\n\x1a\n"+# Key names go into a shell command on the TV, so only plain key names and numeric keycodes get through.+KEY_NAME = re.compile(r"^[A-Z0-9_]+$")+KEY_GAP_S = 0.6 # between two keys, so the UI has finished reacting to the firstdef check_arity(args):@@ -98,24 +106,86 @@ def check_arity(args):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."""+ if args and args[0] == "--screenshot":+ screenshot_args(args[1:])+++def screenshot_args(rest):+ """`<local.png> [KEY ...] [--wait SECONDS]` into (local, keys, wait), or a usage error before connecting.++ KEY is an Android key name without the KEYCODE_ prefix (HOME, DPAD_RIGHT), a full name (KEYCODE_BACK)+ or a numeric keycode (83). The screenshot is taken --wait seconds after the last key (default 1)."""+ local, keys, wait = None, [], 1.0+ i = 0+ while i < len(rest):+ arg = rest[i]+ if arg == "--wait" and i + 1 < len(rest):+ try:+ wait = float(rest[i + 1])+ except ValueError:+ wait = -1+ if wait < 0:+ usage_error(f"--wait needs a number of seconds, not {rest[i + 1]!r}")+ i += 2+ continue+ if local is None and not arg.startswith("--"):+ local = arg+ elif KEY_NAME.match(arg):+ keys.append(arg)+ else:+ usage_error(f"not a key name: {arg!r} (use names such as HOME or DPAD_RIGHT, in capitals, "+ "or a numeric keycode)")+ i += 1+ if local is None:+ usage_error("--screenshot needs the file to save to")+ return local, keys, wait+++def usage_error(message):+ sys.stderr.write(f"{message}\n{USAGE}")+ sys.exit(2)+++def keyevent(name):+ """The `input keyevent` argument for a key name or keycode that already matched KEY_NAME."""+ return name if name.isdigit() or name.startswith("KEYCODE_") else "KEYCODE_" + name+++def screenshot(dev, local, keys=(), wait=1.0):+ """Press `keys`, then capture the TV screen into `local`. Returns 0, or 1 when the capture failed or+ 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)+ for i, key in enumerate(keys):+ if i:+ time.sleep(KEY_GAP_S)+ dev.shell(f"input keyevent {keyevent(key)}")+ if keys:+ time.sleep(wait)+ # The exit status tells a capture that failed (no file to pull) from one that came back empty: with+ # Netflix in front a TCL C755 exits 1 and leaves a 0-byte file, which is the empty case below.+ said = dev.shell(f"rm -f {SHOT_REMOTE}; screencap -p {SHOT_REMOTE}; echo rc=$?", read_timeout_s=120.0)+ rc = next((int(line[3:]) for line in said.splitlines() if re.fullmatch(r"rc=-?\d+", line.strip())), None)+ if rc not in (None, 0, 1):+ other = " ".join(line.strip() for line in said.splitlines() if line.strip() and not line.startswith("rc="))+ dev.shell(f"rm -f {SHOT_REMOTE}", read_timeout_s=60.0)+ print(f"screencap failed on the TV (exit status {rc}): {other or 'no output'}", file=sys.stderr)+ return 1dev.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 TVsize = os.path.getsize(local) if os.path.exists(local) else 0if 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)+ print(f"captured 0 bytes into {local}: Live TV and HDMI inputs come back empty on most TVs, as do "+ "some streaming apps (Netflix), so check what is on screen before the ADB connection "+ "(see docs/TROUBLESHOOTING.md)", file=sys.stderr)return 1+ with open(local, "rb") as f:+ if f.read(len(PNG)) != PNG:+ print(f"{local} is not a PNG: the pull from the TV came back damaged; try again", file=sys.stderr)+ return 1print(f"screenshot {local} ({size} bytes)")return 0@@ -131,7 +201,8 @@ def main():"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])+ local, keys, wait = screenshot_args(args[1:])+ status = screenshot(dev, local, keys, wait)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]}")