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
launcher: read the grant back and test the PowerShell steps
Rasmus Kjær Damgaard5623b8c81302
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex ffe0b5d71..2f45f5b61 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -927,8 +927,9 @@ tools/tv.py 'dumpsys accessibility'A force stop of the launcher (Settings > Apps, a cleaner app, `am force-stop`) takes both helpers offthat list. With `restore_key_services` on (`config.xml` or a theme) and `WRITE_SECURE_SETTINGS` granted-(`RESTORE_KEY_SERVICES=1` at install, `-RestoreKeyServices` on Windows), Home puts the helpers that were-running back on the list the next time it starts; a helper turned off in Settings stays off.+(`RESTORE_KEY_SERVICES=1` on every install, `-RestoreKeyServices` on Windows; an install without it takes+the grant back), Home puts the helpers that were running back on the list the next time it starts; a helper+turned off in Settings stays off.- **Home puts the helper back on the list after a force stop, and it still is not bound.** `dumpsysaccessibility` then shows `Bound services:{}`, `accessibility_enabled` falls back to `0`, and the helper@@ -1264,9 +1265,10 @@ first two writes are what make the opt-in survive, so read why:- `WRITE_SECURE_SETTINGS` is what lets the launcher write the helper back onto the list at screen-on.Without it `GuardKeep` gives up silently and the helper stays off after the first standby, which looks- like the helper having died. `RESTORE_KEY_SERVICES=1` at install already grants it- ([the force-stop section](#accessibility-helper-enabled-but-the-remote-button-does-nothing)), and an install- without it takes the grant back, so once the opt-in is on, pass it on every reinstall.+ like the helper having died. `RESTORE_KEY_SERVICES=1` at install (`-RestoreKeyServices` on Windows)+ already grants it ([the force-stop section](#accessibility-helper-enabled-but-the-remote-button-does-nothing)),+ and an install without it takes the grant back, the one made by hand above included, so once the opt-in is+ on, pass it on every reinstall.- `GuardRevival` is the listener the system re-binds once the process is gone, and firmware that killsthird-party apps in standby takes the screen-on watch with it. The rebind is what re-arms it.diff --git a/launcher/app/src/main/res/values/config.xml b/launcher/app/src/main/res/values/config.xmlindex e626a4207..7571886c7 100644--- a/launcher/app/src/main/res/values/config.xml+++ b/launcher/app/src/main/res/values/config.xml@@ -166,7 +166,7 @@<!-- A force stop of the launcher (Settings, a cleaner app, am force-stop) takes HomeKeyService and InputKeyServiceoff the enabled list. true: Home puts the helpers that were running back when it starts; one turned off inSettings stays off. Needs WRITE_SECURE_SETTINGS, which build-and-install grants with RESTORE_KEY_SERVICES=1- (-RestoreKeyServices on Windows). Can also be set with "restore_key_services": true in a theme's config.json. -->+ (-RestoreKeyServices on Windows) and takes back on an install without it. Can also be set with "restore_key_services": true in a theme's config.json. --><bool name="restore_key_services">false</bool><!-- More remote buttons that open the input switcher, by Android keycode (INPUT_KEY_SERVICE=1diff --git a/launcher/build-and-install.ps1 b/launcher/build-and-install.ps1index 051a58216..1a3ce849e 100644--- a/launcher/build-and-install.ps1+++ b/launcher/build-and-install.ps1@@ -158,16 +158,20 @@ if ($HomeKeyService) { Enable-Service 'HomeKeyService' }# The grant follows the switch on every install: pm install -r keeps a grant, so a run without the switch takes it# back. WRITE_SECURE_SETTINGS opens every secure and global setting, not only the accessibility list.# tv.py does not hand back the TV shell's exit status, so each side prints its marker only once the TV shows the-# state it wants, and the install stops when the marker is missing (see build-and-install.sh).+# state it wants, and the install stops when the marker is missing (see build-and-install.sh). The steps are the+# same text as there, which tests/test_launcher_secure_ack.py checks.$secure = 'android.permission.WRITE_SECURE_SETTINGS'+$read = 's=$(dumpsys package com.gathin.tvhome) && case "$s" in *"DUMP TIMEOUT"*) ;; *"' + $secure + ': granted=true"*)'if ($RestoreKeyServices) {- $step = "pm grant com.gathin.tvhome $secure && echo restore-granted"; $mark = 'restore-granted'+ $step = 'pm grant com.gathin.tvhome ' + $secure + ' && ' + $read + ' echo restore-granted ;; esac'; $mark = 'restore-granted'+ $hint = 'the launcher does not hold it, so restore_key_services cannot put the helpers back'} else {- $step = "pm revoke com.gathin.tvhome $secure; s=`$(dumpsys package com.gathin.tvhome) && case `"`$s`" in *`"${secure}: granted=true`"*) ;; *`"$secure`"*) echo secure-settings-revoked ;; esac"+ $step = 'pm revoke com.gathin.tvhome ' + $secure + '; ' + $read + ' ;; *"' + $secure + '"*) echo secure-settings-revoked ;; esac'$mark = 'secure-settings-revoked'+ $hint = 'the launcher may still hold it; run again with -RestoreKeyServices to keep it on purpose'}$out = ($step | & $py -I ..\tools\tv.py --batch) -join "`n"Write-Host $out# Only a line that is the marker and nothing else counts: tv.py --batch echoes the step, which contains it too.-if (($out -split '\r?\n') -notcontains $mark) { throw "WRITE_SECURE_SETTINGS is not in the state this install asked for ($mark missing)" }+if (($out -split '\r?\n') -cnotcontains $mark) { throw "WRITE_SECURE_SETTINGS is not in the state this install asked for ($mark missing): $hint. The launcher is installed and is Home. Check by hand: tools\tv.py 'dumpsys package com.gathin.tvhome'" }Write-Host 'Installed. Press Home on the remote to see it.'diff --git a/launcher/build-and-install.sh b/launcher/build-and-install.shindex 4601d149d..58a7acf7a 100755--- a/launcher/build-and-install.sh+++ b/launcher/build-and-install.sh@@ -225,18 +225,24 @@ if [ "${INPUT_KEY_SERVICE:-0}" = 1 ]; then enable_service InputKeyService; fiif [ "${HOME_KEY_SERVICE:-0}" = 1 ]; then enable_service HomeKeyService; fi# The grant follows the switch on every install: pm install -r keeps a grant, so a run without the switch takes it# back. WRITE_SECURE_SETTINGS opens every secure and global setting, not only the accessibility list.-# tv.py does not hand back the TV shell's exit status, so each side prints its marker only once the TV shows the+# tv.py does not hand back the TV shell's exit status, so each side prints its marker only once dumpsys shows the# state it wants, and the install stops when the marker is missing. The revoke is judged by the package's-# permission state rather than pm's exit status, so a permission that was never granted counts as revoked, and a-# dumpsys that does not list the permission at all prints nothing.+# permission state rather than pm's exit status, so a permission that was never granted counts as revoked; on+# Android 8 to 11 a revoked install permission leaves only the requested-permissions entry. A dumpsys that does+# not list the permission at all, fails, or ran out of time (it says DUMP TIMEOUT and still exits 0, cut off+# before the granted line) prints nothing.SECURE=android.permission.WRITE_SECURE_SETTINGS+READ="s=\$(dumpsys package com.gathin.tvhome) && case \"\$s\" in *\"DUMP TIMEOUT\"*) ;; *\"$SECURE: granted=true\"*)"if [ "${RESTORE_KEY_SERVICES:-0}" = 1 ]; then- STEP="pm grant com.gathin.tvhome $SECURE && echo restore-granted"; MARK=restore-granted+ STEP="pm grant com.gathin.tvhome $SECURE && $READ echo restore-granted ;; esac"; MARK=restore-granted+ HINT="the launcher does not hold it, so restore_key_services cannot put the helpers back"else- STEP="pm revoke com.gathin.tvhome $SECURE; s=\$(dumpsys package com.gathin.tvhome) && case \"\$s\" in *\"$SECURE: granted=true\"*) ;; *\"$SECURE\"*) echo secure-settings-revoked ;; esac"+ STEP="pm revoke com.gathin.tvhome $SECURE; $READ ;; *\"$SECURE\"*) echo secure-settings-revoked ;; esac"MARK=secure-settings-revoked+ HINT="the launcher may still hold it; run again with RESTORE_KEY_SERVICES=1 to keep it on purpose"fi-OUT=$("$PY" -I ../tools/tv.py "$STEP")+# A tv.py that cannot reach the TV fails here too, and gets the same message instead of stopping the script bare.+OUT=$("$PY" -I ../tools/tv.py "$STEP") || OUT=""echo "$OUT"# Only a line that is the marker and nothing else counts: the step's own text contains it too.ACK_FOUND=0@@ -244,6 +250,8 @@ while IFS= read -r line; doif [ "${line%$'\r'}" = "$MARK" ]; then ACK_FOUND=1; break; fidone <<< "$OUT"if [ "$ACK_FOUND" != 1 ]; then- echo "ERROR: WRITE_SECURE_SETTINGS is not in the state this install asked for ($MARK missing)" >&2; exit 1+ echo "ERROR: WRITE_SECURE_SETTINGS is not in the state this install asked for ($MARK missing): $HINT." >&2+ echo "The launcher is installed and is Home. Check by hand: tools/tv.py 'dumpsys package com.gathin.tvhome' | grep $SECURE" >&2+ exit 1fiecho "Installed. Press Home on the remote to see it."diff --git a/tests/test_launcher_handover.py b/tests/test_launcher_handover.pyindex af1bcafd1..abb3c87bc 100644--- a/tests/test_launcher_handover.py+++ b/tests/test_launcher_handover.py@@ -50,7 +50,8 @@ state = load()def run(command):if "pm install" in command:return "Success\n"- # A TV that never held WRITE_SECURE_SETTINGS: the revoke step finds it denied.+ # A TV that never held WRITE_SECURE_SETTINGS: the revoke step finds it denied. The step itself is run+ # against fake pm and dumpsys in test_launcher_min_sdk; here only the handover is under test.if "pm revoke" in command and "WRITE_SECURE_SETTINGS" in command:return "secure-settings-revoked\n"if "am start" in command:@@ -156,7 +157,7 @@ class HandoverTest(unittest.TestCase):state.update(overrides)self.state_path.write_text(json.dumps(state))env = {k: v for k, v in os.environ.items()- if k not in ("STOCK_LAUNCHER", "INPUT_KEY_SERVICE", "HOME_KEY_SERVICE")}+ if k not in ("STOCK_LAUNCHER", "INPUT_KEY_SERVICE", "HOME_KEY_SERVICE", "RESTORE_KEY_SERVICES")}env.update(TV_HOST="192.168.1.50", FAKE_TV_STATE=str(self.state_path),HOME=str(self.home), JAVA_HOME=str(self.base / "java"),ANDROID_HOME=str(self.base / "android-sdk"))diff --git a/tests/test_launcher_min_sdk.py b/tests/test_launcher_min_sdk.pyindex efac9d7a5..c53dff510 100644--- a/tests/test_launcher_min_sdk.py+++ b/tests/test_launcher_min_sdk.py@@ -71,23 +71,34 @@ def run(command):# The WRITE_SECURE_SETTINGS step decides its own marker on the TV, so it runs here as written,# in sh, against a pm and a dumpsys that keep the grant in the state file.+# A refused grant prints pm's exception and exits non-zero; a revoke the TV ignores says nothing.PM = """#!/bin/shcase "$1" in- grant) echo granted > "$FAKE_SECURE" ;;- revoke) [ "$(cat "$FAKE_SECURE.works")" = 1 ] && echo denied > "$FAKE_SECURE" ;;+ grant)+ if [ "$(cat "$FAKE_SECURE.grant")" != 1 ]; then+ echo "Exception occurred while executing 'grant':" >&2; exit 255+ fi+ echo granted > "$FAKE_SECURE" ;;+ revoke) [ "$(cat "$FAKE_SECURE.revoke")" = 1 ] && echo denied > "$FAKE_SECURE" ;;esacexit 0"""-# A readback that fails part way has printed the requested-permissions list, which names the-# permission without its state.+# Laid out as Android 8 to 11 print it: the requested list always names the permission, and the+# install-permissions line is there only while it is granted. A failed readback stops after the requested+# list with a non-zero exit; a timed-out one stops there too, says so, and exits 0 as dumpsys does.DUMPSYS = """#!/bin/sh-if [ "$(cat "$FAKE_SECURE.readback")" = fail ]; then- echo " requested permissions:"- echo " android.permission.WRITE_SECURE_SETTINGS"- exit 1+echo " Package [com.gathin.tvhome] (1a2b3c):"+echo " requested permissions:"+echo " android.permission.WRITE_SECURE_SETTINGS"+case "$(cat "$FAKE_SECURE.readback")" in+ fail) exit 1 ;;+ timeout) echo "*** SERVICE 'package' DUMP TIMEOUT (10000ms) EXPIRED ***"; exit 0 ;;+esac+if [ "$(cat "$FAKE_SECURE")" = granted ]; then+ echo " install permissions:"+ echo " android.permission.WRITE_SECURE_SETTINGS: granted=true"fi-g=false; [ "$(cat "$FAKE_SECURE")" = granted ] && g=true-echo " android.permission.WRITE_SECURE_SETTINGS: granted=$g"+echo " User 0: ceDataInode=4242 installed=true hidden=false suspended=false stopped=false""""@@ -102,10 +113,11 @@ def secure_step(command):secure = shims + "/secure"with open(secure, "w") as f:f.write(state["secure"] + "\n")- with open(secure + ".works", "w") as f:- f.write("1\n" if state["revoke_works"] else "0\n")- with open(secure + ".readback", "w") as f:- f.write("fail\n" if state["readback_fails"] else "ok\n")+ for suffix, value in ((".grant", "1" if state["grant_works"] else "0"),+ (".revoke", "1" if state["revoke_works"] else "0"),+ (".readback", state["readback"])):+ with open(secure + suffix, "w") as f:+ f.write(value + "\n")env = dict(os.environ, PATH=shims + ":" + os.environ["PATH"], FAKE_SECURE=secure)out = subprocess.run(["sh", "-c", command], env=env, capture_output=True, text=True).stdoutwith open(secure) as f:@@ -127,6 +139,10 @@ def main():commands = []for command in commands:state["commands"].append(command)+ if state["link_fails"] and "WRITE_SECURE_SETTINGS" in command:+ save()+ sys.stderr.write("Error: could not reach the TV\n")+ return 2if "--batch" in args:# As tools/tv.py does: a batch echoes each command before its output.sys.stdout.write(f"$ {command}\n")@@ -176,7 +192,9 @@ class MinSdkGuardTest(unittest.TestCase):"install_output": "Success\n","secure": "denied","revoke_works": True,- "readback_fails": False,+ "grant_works": True,+ "readback": "ok",+ "link_fails": False,"commands": [],}state.update(overrides)@@ -223,11 +241,32 @@ class MinSdkGuardTest(unittest.TestCase):self.assertIn("secure-settings-revoked missing", result.stderr)self.assertEqual(state["secure"], "granted")- def test_a_failed_readback_stops_the_install(self):- result, state = self.install(secure="granted", revoke_works=False, readback_fails=True)+ def test_a_failed_or_timed_out_readback_stops_the_revoke(self):+ for readback in ("fail", "timeout"):+ with self.subTest(readback=readback):+ result, state = self.install(secure="granted", revoke_works=False, readback=readback)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("secure-settings-revoked missing", result.stderr)+ self.assertEqual(state["secure"], "granted")++ def test_a_refused_grant_stops_the_install(self):+ result, state = self.install(restore=True, grant_works=False)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("restore-granted missing", result.stderr)+ self.assertEqual(state["secure"], "denied")++ def test_a_grant_whose_readback_fails_or_times_out_stops_the_install(self):+ for readback in ("fail", "timeout"):+ with self.subTest(readback=readback):+ result, _ = self.install(restore=True, readback=readback)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("restore-granted missing", result.stderr)++ def test_a_tv_that_cannot_be_reached_gets_the_message(self):+ # tv.py exits non-zero for this step only; set -e must not stop the script before the error.+ result, _ = self.install(link_fails=True)self.assertNotEqual(result.returncode, 0)self.assertIn("secure-settings-revoked missing", result.stderr)- self.assertEqual(state["secure"], "granted")def test_a_granted_tv_is_revoked(self):result, state = self.install(secure="granted")diff --git a/tests/test_launcher_secure_ack.py b/tests/test_launcher_secure_ack.pyindex f7a4a02f4..01d7a14e5 100644--- a/tests/test_launcher_secure_ack.py+++ b/tests/test_launcher_secure_ack.py@@ -33,6 +33,7 @@ CASES = [(f"not-{REVOKE}\n", REVOKE, False),(f"{REVOKE}-later\n", REVOKE, False),(f"{GRANT}\n", REVOKE, False),+ (f"{REVOKE.upper()}\n", REVOKE, False),("", GRANT, False),]@@ -51,7 +52,40 @@ def ps_check():if "$mark missing" in line and line.lstrip().startswith("if"))+def block(path, first, last):+ """The lines of `path` from the one starting with `first` to the next one equal to `last`."""+ lines = path.read_text(encoding="utf-8").splitlines()+ start = next(i for i, line in enumerate(lines) if line.startswith(first))+ end = next(i for i in range(start, len(lines)) if lines[i] == last)+ return "\n".join(lines[start:end + 1])+++def sh_step(restore):+ script = block(SH, "SECURE=", "fi") + '\nprintf %s "$STEP"'+ env = dict(os.environ, RESTORE_KEY_SERVICES="1" if restore else "0")+ return subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30,+ env=env, check=True).stdout+++def ps_step(restore):+ script = (f"$RestoreKeyServices = ${'true' if restore else 'false'}\n"+ + block(PS1, "$secure = ", "}") + "\n[Console]::Out.Write($step)")+ return subprocess.run([PWSH, "-NoProfile", "-Command", script], capture_output=True, text=True,+ timeout=60, check=True).stdout++class SecureAckTest(unittest.TestCase):+ def test_the_powershell_steps_are_the_bash_steps(self):+ # The end-to-end cases in test_launcher_min_sdk run the .sh steps on fake pm and dumpsys; the+ # .ps1 sends the same text, so they cover it too.+ if not PWSH or not shutil.which("bash"):+ raise unittest.SkipTest("needs bash and pwsh")+ for restore in (False, True):+ with self.subTest(restore=restore):+ step = sh_step(restore)+ self.assertIn("dumpsys package", step)+ self.assertEqual(ps_step(restore), step)+def test_bash_accepts_only_a_whole_returned_line(self):if not shutil.which("bash"):raise unittest.SkipTest("needs bash")diff --git a/themes/README.md b/themes/README.mdindex bd7ca299d..25da33eb0 100644--- a/themes/README.md+++ b/themes/README.md@@ -123,7 +123,7 @@ A new key needs one there in the same pull request.| `settings_key_keycodes` | list of keycodes | Remote buttons that open Settings, for `HomeKeyService` (TCL Google TV gear: `[83]`) || `settings_key_panel` | bool | Those buttons open a small quick settings panel (TV settings, Display, Network, Apps, Launcher settings) instead of the TV's Settings || `settings_fallback_components` | list, `config.xml` only | Vendor screens tried in order when nothing usable answers the standard Settings action (Xiaomi China, TCL/FFALCON, and Fire OS, where the real menu lives in its launcher), each as `package/activity`; the first one whose package is installed wins, and when none is, the standard intent is sent anyway and may open nothing. Fire OS answers that intent with a `CTSDummy` stub, which counts as missing so the fallback runs. A package named here also has to be listed in the launcher's `<queries>` (Android 11 package visibility), so a set whose settings app is neither of these needs a build, not a theme push. Not read from a theme |-| `restore_key_services` | bool | After a force stop of the launcher, Home puts the remote's accessibility helpers (`HomeKeyService`, `InputKeyService`) back on the enabled list; needs `RESTORE_KEY_SERVICES=1` at install. Off by default |+| `restore_key_services` | bool | After a force stop of the launcher, Home puts the remote's accessibility helpers (`HomeKeyService`, `InputKeyService`) back on the enabled list; needs `RESTORE_KEY_SERVICES=1` (`-RestoreKeyServices` on Windows) on every install, since an install without it takes the grant back. Off by default || `input_key_keycodes` | list of keycodes | More remote buttons that open the input switcher, for `InputKeyService` (`KEYCODE_TV` and `KEYCODE_TV_INPUT` always do) || `app_keys` | list of strings | Remote buttons that open an app, as `"190:com.google.android.youtube.tv"` or `"KEYCODE_BUTTON_3:com.google.android.youtube.tv"`, or by scancode as `"scan:490:com.wbd.hbomax"` for remotes that share one keycode between app buttons (Sony BRAVIA), for `InputKeyService` or `HomeKeyService`. `"input:<input id>"` in place of the package switches to a TV input instead, e.g. `"scan:227:input:com.tcl.tvinput/.passthroughinput.TvPassThroughService/HW1413744640"` for an HDMI port (ids from `dumpsys tv_input`). `"inputs"` in place of the package opens the Inputs menu, for a remote whose source button sends a key Android does not map, e.g. `"scan:365:inputs"` (TCL 65C745). An action word in place of the package runs that action: `back`, `home`, `recents`, `mute`, `sleep` (standby, Android 9 and later), `screensaver`, `settings`, `wifi` or `ignore` (swallows the button so it does nothing, for a shortcut pressed by accident), e.g. `"KEYCODE_PROG_YELLOW:mute"` or `"scan:586:ignore"`. Prefix an entry with `hold:` to make it the long-press action, e.g. `"hold:190:com.netflix.ninja"`, while the unprefixed entry still opens on a tap. Prefix it with `front:` for what a tap does while the button's own app is already in front (`HomeKeyService` only), and use `"guide:<package>"` as a target to open that Live TV app's program guide: `"172:com.vt.tv.tvcenter"` with `"front:172:guide:com.vt.tv.tvcenter"` opens Live TV, then its guide, on a Hisense hengshan set whose firmware sends the Live TV button (`KEYCODE_GUIDE`) only to the stock launcher || `key_filter` | bool | `false` makes the key helpers stop filtering keys while staying enabled. Use it on firmware where any key-filtering accessibility service breaks long-press repeat (TCL Google TV on Android 12): the remote buttons above stop working, and volume repeat comes back |