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: verify key helpers after a theme restart (#994)
SaviorOneZero9702675da66f
diff --git a/README.md b/README.mdindex 587181723..e6498a893 100644--- a/README.md+++ b/README.md@@ -484,7 +484,7 @@ tools/theme.sh themes/aurora # push a theme; --r| [`tools/check.py`](tools/check.py) | Compares the TV with the list that was applied, for what a firmware update undid; `--fix` puts it back. || [`tools/adb-closed.py`](tools/adb-closed.py) | Checks that the TV's network ADB port is closed once debugging is off: exits 0 when nothing answers, 1 while it is still open, 2 when the check itself could not run. No `nc` needed. || [`tools/privacy.py`](tools/privacy.py) | Audits the TV for voice, ACR and telemetry candidates and prints the evidence for each; `--write` turns the findings into a list `disable.sh` and `restore.sh` already understand. |-| [`tools/theme.sh`](tools/theme.sh) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. |+| [`tools/theme.sh`](tools/theme.sh), [`theme_restart.py`](tools/theme_restart.py) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. || [`tools/manage.py`](tools/manage.py) | List every add-on, theme and switch with its screenshot, see what is on the TV, and install, update or remove one by running its creator's own script. || [`tools/bench.py`](tools/bench.py) | Measures the launcher that answers HOME: key latency, how far the focus moved, janky frames, cold start, return to Home, and the idle CPU and PSS it costs. Changes nothing on the TV and writes the raw per-key numbers to JSON; no extra install. || [`tools/trace.py`](tools/trace.py), [`trace_report.py`](tools/trace_report.py) | Records Perfetto traces of the launcher (return to Home, cold start, D-pad) and reports where its time goes, per run and before against after. Optional: needs [`requirements-perf.txt`](tools/requirements-perf.txt). [Guide](tools/trace.md). |diff --git a/tests/test_theme_push_ownership.py b/tests/test_theme_push_ownership.pyindex 41e06574c..deef706a8 100644--- a/tests/test_theme_push_ownership.py+++ b/tests/test_theme_push_ownership.py@@ -108,7 +108,7 @@ class ThemePushTest(unittest.TestCase):self.addCleanup(shutil.rmtree, self.base, ignore_errors=True)self.tools = self.base / "tools"self.tools.mkdir()- for name in ("theme.sh", "b64push.py"):+ for name in ("theme.sh", "b64push.py", "theme_restart.py"):shutil.copy2(TOOLS / name, self.tools / name)(self.tools / "tv.py").write_text(FAKE_TV)venv = self.tools / "venv" / "bin"@@ -119,6 +119,16 @@ class ThemePushTest(unittest.TestCase):content = self.bin / "content"content.write_text(FAKE_CONTENT)content.chmod(0o755)+ # The recovery helper runs real shell status checks. Model framework reads+ # and starts too, while keeping this fixture focused on provider ownership.+ for name, body in {+ "am": 'if [ "$FAKE_RESTART_FAIL" = 1 ]; then exit 1; fi; if [ "$1" = get-current-user ]; then echo 0; fi',+ "settings": 'if [ "$3" = get ]; then echo null; fi',+ "cmd": 'echo com.gathin.tvhome/.MainActivity',+ }.items():+ command = self.bin / name+ command.write_text('#!/bin/sh\n' + body + '\n')+ command.chmod(0o755)self.device = self.base / "device"self.device.mkdir()self.stage = self.base / "stage"@@ -273,6 +283,22 @@ class ThemePushTest(unittest.TestCase):self.assertEqual(list(device_collection.iterdir()), [],"reset must remove mixed-case images even without the provider")+ def test_restart_failure_stops_apply_and_reset_success_messages(self):+ for arguments in ((str(self.theme),), ("--reset",)):+ with self.subTest(arguments=arguments):+ result = self.run_theme(*arguments, FAKE_RESTART_FAIL="1")+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("Theme restart failed", result.stderr)+ self.assertNotIn("is on the TV", result.stdout)+ self.assertNotIn("applied", result.stdout)+ self.assertNotIn("reset", result.stdout)++ def test_both_windows_paths_check_the_shared_helper_exit_code(self):+ script = (TOOLS / "theme.ps1").read_text(encoding="utf-8")+ self.assertEqual(script.count("& $py -I theme_restart.py"), 2)+ self.assertEqual(script.count("if ($LASTEXITCODE) { throw 'Home restart recovery failed' }"), 2)+ self.assertNotIn("$restart =", script)+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")diff --git a/tests/test_theme_restart.py b/tests/test_theme_restart.pynew file mode 100644index 000000000..c67611fab--- /dev/null+++ b/tests/test_theme_restart.py@@ -0,0 +1,357 @@+"""Theme restart recovery against a clocked fake TV and AOSP-shaped service dumps.++No connection to a real TV. Delays model the two independent reports in #994;+fixtures exercise component-specific ActivityManager binding evidence, not labels.+"""+import contextlib+import io+import os+from pathlib import Path+import tempfile+import re+import shlex+import subprocess+import sys+import types+import unittest+from unittest.mock import patch++from tools import theme_restart as restart++HOME = 'com.gathin.tvhome/.HomeKeyService'+INPUT = 'com.gathin.tvhome/.InputKeyService'+OTHER = 'com.example.mapper/.Service'+EXTRA = 'com.example.reader/.Service'+++def service(component=HOME, user=0, connected=True):+ # ServiceRecord.dump/IntentBindRecord.dumpInService in AOSP Android 8/11/14.+ return f''' * ServiceRecord{{a1 u{user} {component}}}+ intent={{cmp={component}}}+ app=ProcessRecord{{b2 1234:com.gathin.tvhome/u{user}a101}}+ Bindings:+ * IntentBindRecord{{c3 CREATE}}:+ intent={{cmp={component}}}+ binder={'android.os.BinderProxy@d4' if connected else 'null'}+ requested=true received={'true' if connected else 'false'} hasBound=true doRebind=false+ * Client AppBindRecord{{e5 ProcessRecord{{f6 222:system/1000}}}}+ Per-process Connections:+ ConnectionRecord{{d7 u{user} CR com.gathin.tvhome/.HomeKeyService:@d4}}+ All Connections:+ ConnectionRecord{{d7 u{user} CR com.gathin.tvhome/.HomeKeyService:@d4}}+'''+++class TV:+ def __init__(self, saved=OTHER + ':' + HOME, delay=1, minimum_off=2, late=None,+ never=False, user=0, flag='1', home='com.gathin.tvhome/.MainActivity'):+ self.saved = saved+ self.value = saved+ self.flag = flag+ self.now = 0+ self.off_at = None+ self.ready = None+ self.delay = delay+ self.minimum_off = minimum_off+ self.late = late+ self.never = never+ self.user = user+ self.home = home+ self.calls = []+ self.bound = set(restart.components(saved))+ self.clear_count = 0+ self.closed = False+ self.fail = None++ def close(self):+ self.closed = True++ def pause(self, duration):+ self.now += duration+ if self.late is not None and self.now >= self.late:+ self.value = ':'.join(x for x in self.value.split(':')+ if not x.startswith('com.gathin.tvhome/'))+ self.bound = set()+ self.late = None+ if self.ready is not None and self.now >= self.ready and not self.never:+ self.bound = set(restart.components(self.value)) if self.flag == '1' else set()++ def shell(self, command, read_timeout_s=None):+ self.calls.append(command)+ cmd = command.split('; rc=$?;', 1)[0]+ if self.fail and self.fail in cmd:+ raise OSError('simulated broken transport')+ if cmd.startswith('cyt_restore() { '):+ restore = cmd.split('cyt_restore() { ', 1)[1].split('; };', 1)[0]+ off = re.search(r"(settings --user \d+ put secure enabled_accessibility_services '' && settings --user \d+ put secure accessibility_enabled 0) && sleep 2", cmd)[1]+ try:+ self.shell(off)+ getattr(self, 'remote_pause', self.pause)(2)+ finally:+ self.shell(restore)+ return '\n__CYT_THEME_RC__0\n'+ output = ''+ for piece in cmd.split(' && '):+ args = shlex.split(piece)+ if args[:2] == ['am', 'get-current-user']:+ output += str(self.user)+ elif args[:3] == ['cmd', 'package', 'resolve-activity']:+ output += self.home+ elif args[:2] == ['am', 'force-stop']:+ self.value = ':'.join(x for x in self.value.split(':')+ if not x.startswith('com.gathin.tvhome/'))+ self.bound = set()+ self.ready = None+ elif args[0] == 'settings':+ if args[1:3] != ['--user', str(self.user)]:+ raise AssertionError('wrong Android user: ' + piece)+ op, key = args[3], args[5]+ if op == 'get':+ output += self.value if key == restart.SERVICES else self.flag+ elif key == restart.SERVICES:+ self.value = args[6]+ else:+ self.flag = args[6]+ if self.flag == '0':+ self.off_at = self.now+ self.ready = None+ self.bound = set()+ self.clear_count += 1+ elif self.off_at is not None and self.now - self.off_at >= self.minimum_off:+ self.ready = self.now + self.delay+ elif args[:3] == ['dumpsys', 'activity', 'services']:+ output += ''.join(service(x, user=self.user, connected=x in self.bound)+ for x in restart.components(self.value)+ if x.startswith('com.gathin.tvhome/'))+ return output + '\n__CYT_THEME_RC__0\n'+++class BindingProbe(unittest.TestCase):+ def test_short_and_full_component_names(self):+ for component in (HOME, 'com.gathin.tvhome/com.gathin.tvhome.HomeKeyService'):+ self.assertEqual(restart.bound_services(service(component), 0), set(restart.components(HOME)))++ def test_component_only_and_accessibility_action_bindings(self):+ explicit = service()+ with_action = explicit.replace('intent={cmp=', 'intent={act=' + restart.ACTION + ' cmp=')+ self.assertEqual(restart.bound_services(explicit, 0), restart.bound_services(with_action, 0))+ wrong_component = explicit.replace('cmp=' + HOME, 'cmp=' + INPUT)+ self.assertFalse(restart.bound_services(wrong_component, 0))++ def test_multiple_helpers_and_users(self):+ dump = service(HOME) + service(INPUT) + service(HOME, user=10, connected=False)+ self.assertEqual(restart.bound_services(dump, 0), set(restart.components(HOME + ':' + INPUT)))+ self.assertEqual(restart.bound_services(dump, 10), set())++ def test_running_or_requested_service_is_not_a_completed_binding(self):+ for before, after in [('binder=android.os.BinderProxy@d4', 'binder=null'),+ ('received=true', 'received=false'),+ ('hasBound=true', 'hasBound=false'),+ ('requested=true', 'requested=false'),+ (':system/1000', ':com.example/10123'),+ ('app=ProcessRecord{b2 1234:com.gathin.tvhome/u0a101}', 'app=null'),+ ('intent={cmp=', 'intent={act=com.example.Unrelated cmp=')]:+ with self.subTest(after=after):+ self.assertFalse(restart.bound_services(service().replace(before, after), 0))++ def test_does_not_borrow_binder_or_client_from_another_record(self):+ bad = service(connected=False)+ self.assertNotIn(next(iter(restart.components(HOME))),+ restart.bound_services(bad + service(INPUT), 0))+ missing_client = service().replace('Client AppBindRecord', 'Other AppBindRecord')+ self.assertFalse(restart.bound_services(missing_client + '\nAll Connections:\n'+ '* Client AppBindRecord{x ProcessRecord{f 222:system/1000}}', 0))++ def test_localized_accessibility_labels_are_not_used(self):+ self.assertFalse(restart.bound_services('Bound services:{Service[label=Bouton Accueil]}', 0))+ self.assertEqual(restart.bound_services(service(), 0), set(restart.components(HOME)))+++class Recovery(unittest.TestCase):+ def test_delayed_tcl_binding(self):+ tv = TV(delay=3)+ restart.restart(tv, tv.pause)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.clear_count, 1)+ self.assertGreaterEqual(tv.now, 9)++ def test_late_removal_uses_original_snapshot_and_rechecks(self):+ tv = TV(late=6)+ restart.restart(tv, tv.pause)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.clear_count, 2, 'first successful bind must not end the check')+ tv.pause(3)+ self.assertEqual(set(restart.components(tv.value)), set(restart.components(tv.saved)))++ def test_two_helpers_and_another_app_are_preserved(self):+ tv = TV(saved=HOME + ':' + OTHER + ':' + INPUT)+ restart.restart(tv, tv.pause)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.flag, '1')+ self.assertTrue(set(restart.components(HOME + ':' + INPUT)) <= tv.bound)++ def test_no_helper_has_no_settings_writes_or_waits(self):+ for saved in ('null', '', OTHER, 'com.gathin.tvhome.other/.Service'):+ with self.subTest(saved=saved):+ tv = TV(saved=saved)+ restart.restart(tv, tv.pause)+ self.assertFalse(any(' put secure ' in x for x in tv.calls))+ self.assertFalse(any('dumpsys' in x for x in tv.calls))+ self.assertEqual(tv.now, 0)++ def test_accessibility_was_off_and_stays_off(self):+ tv = TV(flag='0')+ restart.restart(tv, tv.pause)+ self.assertEqual(tv.flag, '0')+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.now, 0)++ def test_another_foreground_android_user(self):+ tv = TV(user=10)+ restart.restart(tv, tv.pause)+ self.assertTrue(any('am start --user 10' in x for x in tv.calls))+ self.assertEqual(tv.clear_count, 1)++ def test_stock_home_redirect_uses_explicit_start(self):+ tv = TV(home='com.google.android.apps.tv.launcherx/.HomeActivity')+ restart.restart(tv, tv.pause)+ start = next(x for x in tv.calls if x.startswith('am start '))+ self.assertIn('-n com.gathin.tvhome/.MainActivity', start)+ tv = TV()+ restart.restart(tv, tv.pause)+ start = next(x for x in tv.calls if x.startswith('am start '))+ self.assertIn('-c android.intent.category.HOME', start)+ self.assertNotIn(' -n ', start)++ def test_unbound_timeout_is_bounded_and_leaves_saved_list(self):+ tv = TV(never=True)+ with self.assertRaisesRegex(RuntimeError, 'did not stay bound'):+ restart.restart(tv, tv.pause)+ self.assertEqual(tv.clear_count, 3)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.flag, '1')+ self.assertLessEqual(tv.now, 33)++ def test_newly_enabled_other_service_is_preserved_on_retry(self):+ tv = TV(late=6)+ original = tv.pause+ def pause(duration):+ original(duration)+ if tv.now >= 6 and EXTRA not in tv.value:+ tv.value += ':' + EXTRA+ restart.restart(tv, pause)+ self.assertIn(EXTRA, tv.value)+ self.assertTrue(set(restart.components(tv.saved)) <= restart.components(tv.value).keys())++ def test_other_apps_late_removal_is_also_repaired(self):+ tv = TV()+ original = tv.pause+ removed = False+ def pause(duration):+ nonlocal removed+ original(duration)+ if tv.now >= 6 and not removed:+ tv.value = tv.value.replace(OTHER + ':', '')+ removed = True+ restart.restart(tv, pause)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.clear_count, 2)++ def test_start_failure_restores_the_snapshot_before_returning_error(self):+ tv = TV()+ tv.fail = 'am start'+ with self.assertRaises(OSError):+ restart.restart(tv, tv.pause)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.flag, '1')++ def test_host_interrupt_during_off_interval_restores_list(self):+ tv = TV()+ def pause(duration):+ if duration == 2:+ raise KeyboardInterrupt()+ tv.pause(duration)+ tv.remote_pause = pause+ with self.assertRaises(KeyboardInterrupt):+ restart.restart(tv, pause)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.flag, '1')++ def test_transport_failure_stops_without_repeated_toggles(self):+ tv = TV()+ tv.fail = 'dumpsys activity'+ with self.assertRaises(OSError):+ restart.restart(tv, tv.pause)+ self.assertEqual(tv.clear_count, 1)+ self.assertEqual(tv.value, tv.saved)+ self.assertEqual(tv.flag, '1')++ def test_bad_setting_is_refused_before_force_stop(self):+ for value in ('Error: permission denied', 'pkg/.Svc; echo unsafe', 'pkg/.Svc::other/.Svc'):+ tv = TV(saved='')+ tv.value = value+ with self.assertRaises(RuntimeError):+ restart.restart(tv, tv.pause)+ self.assertFalse(any('force-stop' in x for x in tv.calls))+++class RemoteCycle(unittest.TestCase):+ def test_restore_runs_on_normal_exit_settings_failure_and_remote_termination(self):+ # Run the actual device-side command in a POSIX shell. The settings stub+ # writes files; TERM simulates a remote shell being torn down mid-cycle.+ setup = r'''+settings() {+ shift 2+ printf '%s' "$4" > "$STATE/$3"+ if [ "$3" = accessibility_enabled ] && [ "$4" = 0 ]; then+ case "$MODE" in term) kill -TERM $$ ;; fail) return 1 ;; esac+ fi+}+sleep() { :; }+'''+ for mode in ('ok', 'fail', 'term'):+ with self.subTest(mode=mode), tempfile.TemporaryDirectory() as tmp:+ class Local:+ def shell(self, command, **kwargs):+ return subprocess.run(['/bin/sh', '-c', setup + command], text=True,+ capture_output=True, env=dict(os.environ, STATE=tmp, MODE=mode)).stdout+ if mode == 'ok':+ restart.cycle(Local(), 0, restart.components(OTHER + ':' + HOME))+ else:+ with self.assertRaises(RuntimeError):+ restart.cycle(Local(), 0, restart.components(OTHER + ':' + HOME))+ self.assertEqual((Path(tmp) / restart.SERVICES).read_text(), OTHER + ':' + HOME)+ self.assertEqual((Path(tmp) / restart.FLAG).read_text(), '1')+++class ExitStatus(unittest.TestCase):+ def test_real_posix_shell_marker_checks_nonzero_exit(self):+ class Local:+ def shell(self, command, **kwargs):+ return subprocess.run(['/bin/sh', '-c', command], text=True,+ capture_output=True, check=True).stdout+ self.assertEqual(restart.shell(Local(), 'printf hello'), 'hello')+ for command in ('false', "printf 'Permission Denial: denied\\n'"):+ with self.assertRaises(RuntimeError):+ restart.shell(Local(), command)++ def test_missing_exit_marker_is_an_error(self):+ class Broken:+ def shell(self, command, **kwargs):+ return 'partial response'+ with self.assertRaises(RuntimeError):+ restart.shell(Broken(), 'true')++ def test_cli_returns_failure_and_closes_transport(self):+ tv = TV()+ module = types.SimpleNamespace(connect=lambda: tv)+ stderr = io.StringIO()+ with patch.dict(sys.modules, tv=module), patch.object(restart, 'restart', side_effect=RuntimeError('unbound')):+ with contextlib.redirect_stderr(stderr):+ self.assertEqual(restart.main(), 1)+ self.assertTrue(tv.closed)+ self.assertIn('Theme restart failed', stderr.getvalue())+++if __name__ == '__main__':+ unittest.main()diff --git a/tools/theme.ps1 b/tools/theme.ps1index e32900567..5c6c1c957 100644--- a/tools/theme.ps1+++ b/tools/theme.ps1@@ -27,18 +27,7 @@ function Invoke-Tv {}$dir = "/sdcard/Android/data/$pkg/files"$revision = [guid]::NewGuid().ToString('N')-# Restart Home so it rereads the theme. Android drops a force-stopped app's accessibility services from the-# enabled list (asynchronously, so wait a second), which would switch off InputKeyService/HomeKeyService;-# put the list back if it had ours. Writing the same list back is not enough: the force-stop also turns-# accessibility_enabled off, and the service only binds again once the list changes. So restart first, then-# clear the list, switch accessibility off (some TVs keep the service "crashed" and unbound otherwise), write-# the list back and switch accessibility on again. On some TVs (Xiaomi MiTV-MOOR2, Android 11) Android has already-# emptied the list and switched accessibility off by then, so clearing it changes nothing and the services stay-# crashed: write the list back first, so the clear is a change (the same order as theme.sh). When the launcher is-# already Home it comes back through the Home-# intent, since `am start -n` from the shell leaves a second MainActivity behind the Home one; before the handover-# it is started by name as before.-$restart = "a=`$(settings get secure enabled_accessibility_services); am force-stop $pkg; case `"`$(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME | tail -n 1)`" in $pkg/*) am start -a android.intent.action.MAIN -c android.intent.category.HOME >/dev/null ;; *) am start -n $pkg/.MainActivity >/dev/null ;; esac; case `"`$a`" in *$pkg*) sleep 1; settings put secure enabled_accessibility_services `"`$a`"; settings put secure accessibility_enabled 1; sleep 1; settings put secure enabled_accessibility_services ''; settings put secure accessibility_enabled 0; sleep 1; settings put secure enabled_accessibility_services `"`$a`"; settings put secure accessibility_enabled 1 ;; esac"+# One shared recovery path verifies the helpers after Home restarts.# 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.@@ -63,7 +52,10 @@ function Drop($name) { "rm -f $dir/$name 2>/dev/null; content delete --uri $uri/$clearWallpapers = "mkdir -p $dir/wallpapers 2>/dev/null; rm -f $dir/wallpapers/*.jpg $dir/wallpapers/*.jpeg $dir/wallpapers/*.png $dir/wallpapers/*.webp $dir/wallpapers/*.JPG $dir/wallpapers/*.JPEG $dir/wallpapers/*.PNG $dir/wallpapers/*.WEBP 2>/dev/null; content delete --uri $uri/wallpapers 2>/dev/null"if ($Reset) {- Invoke-Tv tv.py "mkdir -p $dir 2>/dev/null; $(Drop 'config.json'); $(Drop 'wallpaper.jpg'); $(Drop 'wallpapers/captions.txt'); $clearWallpapers; printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision'); $restart; echo reset"+ Invoke-Tv tv.py "mkdir -p $dir 2>/dev/null; $(Drop 'config.json'); $(Drop 'wallpaper.jpg'); $(Drop 'wallpapers/captions.txt'); $clearWallpapers; printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision')" | Out-Null+ & $py -I theme_restart.py+ if ($LASTEXITCODE) { throw 'Home restart recovery failed' }+ Write-Host 'reset'exit 0}if (-not $Theme) { throw 'usage: theme.ps1 <theme folder> | -Reset' }@@ -95,5 +87,7 @@ if (Test-Path $captions -PathType Leaf) {Invoke-Tv tv.py (Drop 'wallpapers/captions.txt') | Out-Null}Invoke-Tv tv.py "printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision')" | Out-Null-Invoke-Tv tv.py "$restart; echo applied"+& $py -I theme_restart.py+if ($LASTEXITCODE) { throw 'Home restart recovery failed' }+Write-Host 'applied'Write-Host "Theme $(Split-Path $Theme -Leaf) is on the TV. Undo with: tools\theme.ps1 -TvHost $TvHost -Reset"diff --git a/tools/theme.sh b/tools/theme.shindex a62401003..6638275dc 100755--- a/tools/theme.sh+++ b/tools/theme.sh@@ -29,20 +29,8 @@ DIR=/sdcard/Android/data/$PKG/files# including a push of identical config.json bytes and --reset.REVISION="$("$PY" -I -c 'import uuid; print(uuid.uuid4().hex)')"tv() { "$PY" -I tv.py "$@"; }-# Restart Home so it rereads the theme. Android drops a force-stopped app's accessibility services from the-# enabled list, which would switch off InputKeyService/HomeKeyService, so put the list back if it had ours.-# Android removes them asynchronously while it handles the restart, so wait a second before writing the-# list back. Writing the same list back is not enough: the force-stop also turns accessibility_enabled off,-# and the service only binds again once the list changes. So restart first, then clear the list, write it-# back and switch accessibility on again as build-and-install does. Some TVs (TCL Smart TV Pro G03, Android 11)-# also keep the service in their "crashed" list after the force-stop and leave it unbound until accessibility-# itself goes off and on again, so switch it off with the list cleared and wait a second before writing back.-# By then Android has already emptied the list and switched accessibility off (Xiaomi MiTV-MOOR2, Android 11), so-# clearing it changed nothing and the services stayed crashed: write the list back first, so the clear is a change.-# When the launcher is already Home, it comes back through the Home intent: `am start -n` from the shell brings it-# back in an ordinary task, and the next Home press starts a second MainActivity next to it. Otherwise (a theme-# pushed before the handover) it is started by name as before, so the new look still shows.-RESTART="a=\$(settings get secure enabled_accessibility_services); am force-stop $PKG; case \"\$(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME | tail -n 1)\" in $PKG/*) am start -a android.intent.action.MAIN -c android.intent.category.HOME >/dev/null ;; *) am start -n $PKG/.MainActivity >/dev/null ;; esac; case \"\$a\" in *$PKG*) sleep 1; settings put secure enabled_accessibility_services \"\$a\"; settings put secure accessibility_enabled 1; sleep 1; settings put secure enabled_accessibility_services ''; settings put secure accessibility_enabled 0; sleep 1; settings put secure enabled_accessibility_services \"\$a\"; settings put secure accessibility_enabled 1 ;; esac"+# One shared recovery path verifies the helpers after Home restarts.+# 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.@@ -67,7 +55,9 @@ del() { echo "rm -f $DIR/$1 2>/dev/null; content delete --uri $URI/$1 2>/dev/nulCLEAR_WALLPAPERS="mkdir -p $DIR/wallpapers 2>/dev/null; rm -f $DIR/wallpapers/*.[jJ][pP][gG] $DIR/wallpapers/*.[jJ][pP][eE][gG] $DIR/wallpapers/*.[pP][nN][gG] $DIR/wallpapers/*.[wW][eE][bB][pP] 2>/dev/null; content delete --uri $URI/wallpapers 2>/dev/null"if [ "${1:-}" = --reset ]; then- tv "mkdir -p $DIR 2>/dev/null; $(del config.json); $(del wallpaper.jpg); $(del wallpapers/captions.txt); $CLEAR_WALLPAPERS; printf '%s' '$REVISION' > $TMP-theme_revision; $(put theme_revision); $RESTART; echo reset" | tail -n 1+ tv "mkdir -p $DIR 2>/dev/null; $(del config.json); $(del wallpaper.jpg); $(del wallpapers/captions.txt); $CLEAR_WALLPAPERS; printf '%s' '$REVISION' > $TMP-theme_revision; $(put theme_revision)" >/dev/null+ "$PY" -I theme_restart.py+ echo resetexit 0fiTHEME="${THEME_ARG:?usage: theme.sh <theme folder> | --reset}"@@ -105,5 +95,6 @@ elsetv "$(del wallpapers/captions.txt)" >/dev/nullfitv "printf '%s' '$REVISION' > $TMP-theme_revision; $(put theme_revision)" >/dev/null-tv "$RESTART; echo applied" | tail -n 1+"$PY" -I theme_restart.py+echo appliedecho "Theme $(basename "$THEME") is on the TV. Undo with: tools/theme.sh --reset"diff --git a/tools/theme_restart.py b/tools/theme_restart.pynew file mode 100644index 000000000..c9624161e--- /dev/null+++ b/tools/theme_restart.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""Restart Home after a theme push and verify its previously enabled key helpers (#994).++Used by theme.sh and theme.ps1. No theme files or app configuration are changed here.+"""+import os+import re+import shlex+import sys+import time++PACKAGE = "com.gathin.tvhome"+SERVICES = "enabled_accessibility_services"+FLAG = "accessibility_enabled"+ACTION = "android.accessibilityservice.AccessibilityService"+++def shell(dev, command):+ # adb_shell's shell transport does not return the remote exit code. Require a+ # final marker, so a failed settings/start command cannot look like success.+ output = dev.shell(command + "; rc=$?; printf '\\n__CYT_THEME_RC__%s\\n' \"$rc\"",+ read_timeout_s=15)+ result = re.search(r"\n__CYT_THEME_RC__(\d+)\s*$", output)+ if not result or result[1] != "0":+ raise RuntimeError("TV command failed or returned an incomplete response")+ text = output[:result.start()].strip()+ if re.search(r"(?mi)^\s*(Error:|Permission Denial:|Security exception:)", text):+ raise RuntimeError("TV refused the command")+ return text+++def components(value):+ if value in ("", "null"):+ return {}+ found = {}+ for item in value.split(":"):+ if not re.fullmatch(r"[A-Za-z0-9_.]+/[A-Za-z0-9_.$]+", item):+ raise RuntimeError("Could not read the accessibility service list")+ package, name = item.split("/", 1)+ full = package + "/" + (package + name if name.startswith(".") else name)+ found.setdefault(full, item)+ return found+++def bound_services(output, user):+ """Read completed system-server bindings, by component, without localized labels.++ Accessibility's own dump uses Service[label=...] on Android 8/11/14. Activity+ Manager instead identifies the component, current-user instance, received+ binder and system-server client. A started/running service alone is not bound.+ """+ found = set()+ for block in re.split(r"(?m)^\s*\* ServiceRecord\{", output)[1:]:+ header = re.match(r"[^\n]*?\bu(\d+) ([A-Za-z0-9_.$]+/[A-Za-z0-9_.$]+)\}", block)+ if not header or int(header[1]) != user:+ continue+ if not re.search(r"(?m)^\s*app=ProcessRecord\{", block):+ continue+ for binding in re.split(r"(?m)^\s*\* IntentBindRecord\{", block)[1:]:+ # All Connections is a different section; do not borrow a client from it.+ binding = binding.split("All Connections:", 1)[0]+ intent = re.search(r"(?m)^\s*intent=\{([^}\n]*)}", binding)+ component = re.search(r"\bcmp=([A-Za-z0-9_.$]+/[A-Za-z0-9_.$]+)", intent[1]) if intent else None+ action = re.search(r"\bact=(\S+)", intent[1]) if intent else None+ if (component and components(component[1]).keys() == components(header[2]).keys()+ and (not action or action[1] == ACTION)+ and re.search(r"(?m)^\s*binder=(?!null(?:\s|$))\S+", binding)+ and re.search(r"\brequested=true received=true hasBound=true\b", binding)+ and re.search(r"Client AppBindRecord\{[^\n]*ProcessRecord\{[^}\n]*:system/1000}", binding)):+ found.update(components(header[2]))+ break+ return found+++def settings_command(user, services, flag):+ value = shlex.quote(":".join(services.values()))+ return (f"settings --user {user} put secure {SERVICES} {value} && "+ f"settings --user {user} put secure {FLAG} {flag}")+++def cycle(dev, user, saved):+ # Keep the off interval and restoration on the TV. A host disconnect during+ # a host-side sleep must not strand every accessibility service switched off.+ restore = settings_command(user, saved, 1)+ off = settings_command(user, {}, 0)+ shell(dev, f"cyt_restore() {{ {restore}; }}; trap cyt_restore EXIT; "+ f"trap 'cyt_restore; exit 1' HUP INT TERM; {off} && sleep 2; "+ "cyt_rc=$?; cyt_restore; cyt_restore_rc=$?; trap - EXIT HUP INT TERM; "+ '[ "$cyt_rc" -eq 0 ] && [ "$cyt_restore_rc" -eq 0 ]')+++def restart(dev, pause=time.sleep):+ user_text = shell(dev, "am get-current-user")+ if not user_text.isdecimal():+ raise RuntimeError("Could not identify the current Android user")+ user = int(user_text)+ get = lambda key: shell(dev, f"settings --user {user} get secure {key}")+ saved = components(get(SERVICES))+ enabled = get(FLAG)+ if enabled not in ("0", "1", "null"):+ raise RuntimeError("Could not read the accessibility enabled flag")+ helpers = {component for component in saved if component.split("/", 1)[0] == PACKAGE}+ home = shell(dev, "cmd package resolve-activity --brief --user " + str(user)+ + " -a android.intent.action.MAIN -c android.intent.category.HOME")+ def write(services, flag):+ shell(dev, settings_command(user, services, flag))++ try:+ shell(dev, f"am force-stop --user {user} {PACKAGE}")+ if home.splitlines()[-1:] and home.splitlines()[-1].startswith(PACKAGE + "/"):+ start = "-a android.intent.action.MAIN -c android.intent.category.HOME"+ else:+ start = "-n " + PACKAGE + "/.MainActivity"+ shell(dev, f"am start --user {user} {start}")+ if not helpers:+ return++ if enabled != "1":+ # An intentionally disabled accessibility subsystem stays disabled.+ write(saved, 0)+ return++ pause(1) # Android removes force-stopped services asynchronously.+ for attempt in range(3):+ # Keep the original list even if Android has now dropped our helpers. Also+ # retain any newly observed service belonging to another app.+ saved.update(components(get(SERVICES)))+ write(saved, 1)+ pause(1) # Xiaomi needs a real list change before the clear (#726).+ cycle(dev, user, saved) # TCL G05 needs a two-second off interval (#994).+ stable = 0+ for _ in range(7):+ pause(1)+ current = components(get(SERVICES))+ saved.update(current)+ flag = get(FLAG)+ bound = bound_services(shell(dev, f"dumpsys activity services {PACKAGE}"), user)+ stable = stable + 1 if saved.keys() <= current.keys() and flag == "1" and helpers <= bound else 0+ # Three readings span two seconds; a first successful bind alone does+ # not catch the later removal reported on Chromecast (#994).+ if stable == 3:+ return+ # Leave the original list restored even when binding could not be verified.+ write(saved, 1)+ raise RuntimeError("Home restarted, but key helpers did not stay bound; check Accessibility settings")+ except BaseException:+ # A failed start/probe or Ctrl-C must not leave the force-stopped helpers+ # off the list. If the transport is gone this fails explicitly as well.+ if helpers:+ write(saved, 1 if enabled == "1" else 0)+ raise+++def main():+ # Both callers use Python -I, which excludes the script directory from sys.path.+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ dev = None+ try:+ from tv import connect+ dev = connect()+ restart(dev)+ except Exception as error:+ print(f"Theme restart failed: {error}", file=sys.stderr)+ return 1+ finally:+ if dev is not None:+ dev.close()+ return 0+++if __name__ == "__main__":+ sys.exit(main())