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: write theme files through the ThemeProvider before cp
xbsheng4d525b193f30
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 9527a4e55..816d49f6a 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -326,9 +326,18 @@ Things that bit us or contributors, so they don't bite you. Commands use `tools/`tools/tv.py 'pm enable --user 0 com.google.android.apps.tv.launcherx'`.- **`theme.sh` fails with "couldn't create file: Permission denied"**, seen on TCL G07 (Android 11): theshell is not in the group that may write `Android/data`. `theme.sh` stages the files in- `/data/local/tmp` and, when copying them in is refused, writes them through the launcher's- `ThemeProvider` instead. A launcher installed before that provider existed doesn't have it: run+ `/data/local/tmp` and writes them through the launcher's `ThemeProvider`, which creates them as the+ launcher; `cp` is only the fallback for a launcher installed before that provider existed: run`launcher/build-and-install.sh` once, then push the theme again.+- **A theme push prints "is on the TV" and nothing changes**, seen on Android 14: the shell *can* write+ `Android/data` there, so `cp` succeeded - but the file it created belonged to the shell (`ls -ln` shows+ `2000 1078` instead of the launcher's uid) and the launcher logged `W TvHome.Config: ignoring+ .../config.json: open failed: EACCES (Permission denied)`. Overwriting a file the launcher wrote itself+ keeps its owner, so this only bit files that did not exist yet: it looked fine on a set that had been+ themed before and did nothing on a fresh install or right after a reinstall. `theme.sh` now removes the+ shell's copy and writes through the `ThemeProvider` first (the provider cannot truncate a file the shell+ owns); on an older checkout, pushing the theme again after `launcher/build-and-install.sh` has written+ the files once also fixes the ownership.- **Google TV comes back after a few remote presses**, seen on XGIMI (MoGo 3 Pro, Google TV 14). Theremote's app buttons (YouTube, Netflix, Prime Video), the programmable button, the profile button and powerall send F keys that the system hands to `com.xgimi.xrmservice/.XgimiGlobalKeyBroadcast` as global keysdiff --git a/tests/test_theme_push_ownership.py b/tests/test_theme_push_ownership.pynew file mode 100644index 000000000..26f34412b--- /dev/null+++ b/tests/test_theme_push_ownership.py@@ -0,0 +1,208 @@+"""tools/theme.sh must write through the launcher's ThemeProvider before falling back to cp.++On Android 14 the adb shell can write into Android/data, so `cp` succeeds - but the file it creates belongs+to the shell (uid 2000) and the launcher then fails with EACCES, so a theme pushed to a fresh install (or after+the launcher was reinstalled) was silently ignored while the script still printed "is on the TV". The provider+creates the file as the launcher, and it cannot truncate a file the shell owns, so the fix removes our copy+first and writes through the provider; cp stays as the fallback for firmware without it.++These tests run the real tools/theme.sh against a stub tools/tv.py whose "TV shell" is /bin/sh on this machine+and a stub `content` command standing in for the provider, so the command order is what a TV would see.+"""+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+import unittest+++ROOT = Path(__file__).resolve().parents[1]+TOOLS = ROOT / "tools"+DEVICE_DIR = "/sdcard/Android/data/com.gathin.tvhome/files"+STAGE = "/data/local/tmp/cyt-theme"++# --push copies like tv.py does; shell commands run on this machine after the device paths are rewritten.+FAKE_TV = r'''+import json+import os+import subprocess+import sys++LOG = os.environ["FAKE_LOG"]+DIR = os.environ["FAKE_DIR"]+TMP = os.environ["FAKE_STAGE"]+DEVICE_DIR = "/sdcard/Android/data/com.gathin.tvhome/files"+++def local(command):+ return command.replace(DEVICE_DIR, DIR).replace("/data/local/tmp/cyt-theme", TMP)+++class Device:+ max_chunk_size = 4096++ def shell(self, command, read_timeout_s=None):+ with open(LOG, "a") as f:+ f.write(json.dumps({"shell": command}) + "\n")+ return subprocess.run(["/bin/sh", "-c", local(command)],+ capture_output=True, text=True).stdout++ def close(self):+ pass+++def connect():+ return Device()+++args = sys.argv[1:]+if args and args[0] == "--push":+ src, dst = args[1], local(args[2])+ os.makedirs(os.path.dirname(dst), exist_ok=True)+ with open(src, "rb") as f, open(dst, "wb") as g:+ g.write(f.read())+else:+ Device().shell(" ".join(args))+'''++# Stands in for `content write/delete` against content://com.gathin.tvhome.theme, which on a TV runs inside+# the launcher's process and so creates files owned by the launcher. FAKE_NO_PROVIDER models firmware or a+# launcher version without the provider.+FAKE_CONTENT = r'''#!/usr/bin/env python3+import json+import os+import sys++args = sys.argv[1:]+with open(os.environ["FAKE_CONTENT_LOG"], "a") as f:+ f.write(json.dumps({"content": args}) + "\n")+if os.environ.get("FAKE_NO_PROVIDER"):+ sys.exit(1)+action, uri = args[0], args[args.index("--uri") + 1]+path = os.path.join(os.environ["FAKE_DIR"], uri.split("com.gathin.tvhome.theme/", 1)[1])+if action == "write":+ os.makedirs(os.path.dirname(path), exist_ok=True)+ with open(path, "wb") as f:+ f.write(sys.stdin.buffer.read())+elif action == "delete":+ if os.path.isdir(path):+ for name in os.listdir(path):+ if name.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):+ os.remove(os.path.join(path, name))+ elif os.path.exists(path):+ os.remove(path)+'''+++class ThemePushTest(unittest.TestCase):+ def setUp(self):+ self.base = Path(tempfile.mkdtemp())+ self.addCleanup(shutil.rmtree, self.base, ignore_errors=True)+ self.tools = self.base / "tools"+ self.tools.mkdir()+ for name in ("theme.sh", "b64push.py"):+ shutil.copy2(TOOLS / name, self.tools / name)+ (self.tools / "tv.py").write_text(FAKE_TV)+ venv = self.tools / "venv" / "bin"+ venv.mkdir(parents=True)+ (venv / "python").symlink_to(sys.executable)+ self.bin = self.base / "bin"+ self.bin.mkdir()+ content = self.bin / "content"+ content.write_text(FAKE_CONTENT)+ content.chmod(0o755)+ self.device = self.base / "device"+ self.device.mkdir()+ self.stage = self.base / "stage"+ self.log = self.base / "log.jsonl"+ self.content_log = self.base / "content.jsonl"+ self.theme = self.base / "aurora"+ self.theme.mkdir()+ self.config = json.dumps({"background": "#101418", "app_keys": []}, indent=2).encode()+ (self.theme / "config.json").write_bytes(self.config)++ def run_theme(self, *args, **env):+ full = {k: v for k, v in os.environ.items() if k != "TV_HOST"}+ full.update({"TV_HOST": "192.0.2.10", "FAKE_LOG": str(self.log), "FAKE_DIR": str(self.device),+ "FAKE_STAGE": str(self.stage), "FAKE_CONTENT_LOG": str(self.content_log),+ "PATH": f"{self.bin}:{full.get('PATH', '')}"}, **env)+ return subprocess.run(["bash", str(self.tools / "theme.sh"), *args], env=full,+ capture_output=True, text=True, timeout=300)++ def shell_commands(self):+ if not self.log.exists():+ return []+ return [json.loads(line)["shell"] for line in self.log.read_text().splitlines()]++ def provider_calls(self):+ if not self.content_log.exists():+ return []+ return [json.loads(line)["content"] for line in self.content_log.read_text().splitlines()]++ def command_for(self, name):+ """The one device command that puts `name` on the TV, in every shape theme.sh uses it."""+ matches = [c for c in self.shell_commands() if f"{DEVICE_DIR}/{name}" in c and "content write" in c]+ self.assertEqual(len(matches), 1, f"expected exactly one put for {name}: {self.shell_commands()}")+ return matches[0]++ def test_config_is_written_through_the_provider(self):+ result = self.run_theme(str(self.theme))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual((self.device / "config.json").read_bytes(), self.config,+ "the theme has to land on the TV")+ put = self.command_for("config.json")+ self.assertTrue(put.startswith(f"rm -f {DEVICE_DIR}/config.json"),+ f"a file the shell owns stops the provider truncating it: {put}")+ self.assertLess(put.index("content write"), put.index("cp "),+ f"cp creates a shell-owned file on Android 14: {put}")+ self.assertIn(["write", "--uri", "content://com.gathin.tvhome.theme/config.json"],+ self.provider_calls())+ self.assertNotIn(f"cp {self.stage}-config.json {DEVICE_DIR}/config.json", " | ".join(self.shell_commands()),+ "the provider is available, so cp must not run")++ def test_without_the_provider_cp_still_delivers_the_theme(self):+ result = self.run_theme(str(self.theme), FAKE_NO_PROVIDER="1")+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual((self.device / "config.json").read_bytes(), self.config,+ "firmware without the provider keeps the old path")+ self.assertTrue(self.provider_calls(), "the provider is tried first")++ def test_reset_clears_the_overlay_through_the_provider(self):+ (self.device / "config.json").write_bytes(self.config)+ (self.device / "wallpaper.jpg").write_bytes(b"old wallpaper")+ result = self.run_theme("--reset")+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertFalse((self.device / "config.json").exists(), "--reset removes the overlay")+ self.assertFalse((self.device / "wallpaper.jpg").exists())+ revision = self.command_for("theme_revision")+ self.assertLess(revision.index("rm -f"), revision.index("content write"),+ f"the shell's old revision has to go before the provider writes: {revision}")+ self.assertEqual((self.device / "theme_revision").stat().st_size, 32)++ def test_wallpaper_and_captions_take_the_same_path(self):+ (self.theme / "wallpaper.jpg").write_bytes(b"\xff\xd8jpeg bytes")+ (self.theme / "wallpapers").mkdir()+ (self.theme / "wallpapers" / "dusk.jpg").write_bytes(b"\xff\xd8dusk")+ (self.theme / "wallpapers" / "captions.txt").write_text("dusk\n", encoding="utf-8")+ result = self.run_theme(str(self.theme))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual((self.device / "wallpapers" / "dusk.jpg").read_bytes(), b"\xff\xd8dusk")+ self.assertEqual((self.device / "wallpapers" / "captions.txt").read_text(), "dusk\n")+ for name in ("wallpapers/dusk.jpg", "wallpapers/captions.txt"):+ put = self.command_for(name)+ self.assertLess(put.index("content write"), put.index("cp "), put)++ def test_the_windows_script_puts_files_the_same_way(self):+ """theme.ps1 cannot run here, so pin the order that the fix depends on."""+ script = (TOOLS / "theme.ps1").read_text(encoding="utf-8")+ put = next(line for line in script.splitlines() if line.startswith("function Put("))+ self.assertIn("rm -f $dir/$name", put)+ self.assertLess(put.index("rm -f $dir/$name"), put.index("content write"), put)+ self.assertLess(put.index("content write"), put.index("cp $t $dir/$name"), put)+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/theme.ps1 b/tools/theme.ps1index 00d15ee61..43f79538e 100644--- a/tools/theme.ps1+++ b/tools/theme.ps1@@ -30,11 +30,16 @@ $restart = "a=`$(settings get secure enabled_accessibility_services); am force-s# Some firmware (TCL G07, Android 11) locks the shell out of Android/data. Files are staged in# /data/local/tmp and copied in, or written through the launcher's ThemeProvider when that is refused.+# The provider has to be tried first: on Android 14 the shell can write into Android/data, so cp "succeeds",+# but the file it creates belongs to the shell (uid 2000) and the launcher then gets EACCES opening it, which+# silently ignores the theme whenever the file did not exist yet - a fresh install, or after a reinstall.+# A provider write creates the file as the launcher, and it cannot truncate a file the shell owns either, so+# remove our copy first. cp stays as the fallback for firmware without the provider.$uri = "content://$pkg.theme"$tmp = '/data/local/tmp/cyt-theme'# A file's staging path; wallpapers/a.jpg is staged as $tmp-wallpapers-a.jpg.function Stage($name) { "$tmp-$($name -replace '/', '-')" }-function Put($name) { $t = Stage $name; "cp $t $dir/$name 2>/dev/null || content write --uri $uri/$name < $t; rm -f $t" }+function Put($name) { $t = Stage $name; "rm -f $dir/$name 2>/dev/null; content write --uri $uri/$name < $t 2>/dev/null || cp $t $dir/$name 2>/dev/null; rm -f $t" }function Drop($name) { "rm -f $dir/$name 2>/dev/null; content delete --uri $uri/$name 2>/dev/null" }if ($Reset) {diff --git a/tools/theme.sh b/tools/theme.shindex f8b08200c..9e39d55ba 100755--- a/tools/theme.sh+++ b/tools/theme.sh@@ -36,11 +36,16 @@ RESTART="a=\$(settings get secure enabled_accessibility_services); am force-stop# Some firmware (TCL G07, Android 11) locks the shell out of Android/data. Files are staged in# /data/local/tmp and copied in, or written through the launcher's ThemeProvider when that is refused.+# The provider has to be tried first: on Android 14 the shell can write into Android/data, so cp "succeeds",+# but the file it creates belongs to the shell (uid 2000) and the launcher then gets EACCES opening it, which+# silently ignores the theme whenever the file did not exist yet - a fresh install, or after a reinstall.+# A provider write creates the file as the launcher, and it cannot truncate a file the shell owns either, so+# remove our copy first. cp stays as the fallback for firmware without the provider.URI=content://$PKG.themeTMP=/data/local/tmp/cyt-theme# A file's staging path; wallpapers/a.jpg is staged as $TMP-wallpapers-a.jpg.stage() { echo "$TMP-${1//\//-}"; }-put() { echo "cp $(stage "$1") $DIR/$1 2>/dev/null || content write --uri $URI/$1 < $(stage "$1"); rm -f $(stage "$1")"; }+put() { echo "rm -f $DIR/$1 2>/dev/null; content write --uri $URI/$1 < $(stage "$1") 2>/dev/null || cp $(stage "$1") $DIR/$1 2>/dev/null; rm -f $(stage "$1")"; }del() { echo "rm -f $DIR/$1 2>/dev/null; content delete --uri $URI/$1 2>/dev/null"; }if [ "${1:-}" = --reset ]; then