Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

disable: skip the launcher that owns Home while nothing else can take it (#239)

ppjsw0756fa809726
diff --git a/README.md b/README.md
index 8fb8d61c6..b25477eae 100644
--- a/README.md
+++ b/README.md
@@ -271,6 +271,12 @@ The install scripts ask the TV which launcher owns Home and only disable one the
(`tvlauncher` or `launcherx`); pass `STOCK_LAUNCHER=<package>` (`-StockLauncher`) to override, or
`none` to leave it alone.
+`tools/disable.sh` (`disable.ps1`) applies the same rule before it disables anything: if the list
+contains the app that owns Home and no other app on the TV answers HOME, it skips that entry, says
+why, and disables the rest of the list. So a list applied before the launcher handover cannot leave
+the TV with nothing to start. Run the same list again once `launcher/build-and-install.sh` has made
+the new launcher Home and the entry is applied; `FORCE_HOME=1` (`$env:FORCE_HOME`) disables it anyway.
+
## The launcher
A small native Android TV app (`com.gathin.tvhome`, about 370 KB installed) in plain Java with
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 6fd0137db..11a4ab80c 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -57,6 +57,10 @@ Things that bit us or contributors, so they don't bite you. Commands use `tools/
`Success` while HOME still resolves to the stock launcher (priority 2) until that one is disabled.
And check which packages actually handle HOME before disabling anything by name: on the Sony
above, `com.google.android.leanbacklauncher` has a boot receiver but no HOME activity.
+ `tools/disable.sh` now does that check itself: when the list holds the app that owns Home and
+ nothing else on the TV answers HOME, it skips that entry and says so (`FORCE_HOME=1` overrides),
+ so applying a list before the handover no longer leaves the TV without a launcher. Apply the list
+ again after the install script has made the new launcher Home to disable the old one.
- **The new launcher still doesn't own Home** after the stock one is disabled, seen on Google TV
(Xiaomi MiTV-MOOR2). Another system app answers HOME: `com.google.android.tungsten.setupwraith`,
with `.MainActivity` at intent-filter priority 4 and `.RecoveryActivity` at priority 1. You
diff --git a/tests/test_home_guard.py b/tests/test_home_guard.py
new file mode 100644
index 000000000..1d4c741eb
--- /dev/null
+++ b/tests/test_home_guard.py
@@ -0,0 +1,230 @@
+"""tools/disable.sh and tools/disable.ps1 must not disable the app that owns Home (#239).
+
+A list from `examples/` (the Xiaomi one, for instance) includes the stock launcher, and running it
+before the replacement launcher is Home leaves the TV with nothing to start. The property worth
+testing is the one no TV reproduces on demand, so tools/tv.py is replaced by a fake that answers the
+queries from a JSON file: the real disable script runs, only the ADB transport is simulated.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+The PowerShell cases need `pwsh` on PATH and skip without it; CI has no PowerShell.
+"""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+STOCK = "com.google.android.tvlauncher"
+CUSTOM = "com.gathin.tvhome"
+PWSH = shutil.which("pwsh")
+
+# Stands in for tools/tv.py: answers the queries the disable script makes and records what a batch
+# would send, without a TV.
+FAKE_TV = r'''
+import json
+import os
+import sys
+
+STATE_PATH = os.environ["FAKE_TV_STATE"]
+
+
+def load():
+ with open(STATE_PATH) as f:
+ return json.load(f)
+
+
+state = load()
+
+
+def save():
+ with open(STATE_PATH, "w") as f:
+ json.dump(state, f)
+
+
+def answer(command):
+ if command == "pm list packages":
+ return "".join(f"package:{name}\n" for name in state["installed"])
+ if command == "pm list packages -d":
+ return "".join(f"package:{name}\n" for name in state["disabled"])
+ if command.startswith("cmd package query-activities"):
+ if state["claims_fail"]:
+ sys.exit(1)
+ return "".join(f" {name}/.MainActivity\n" for name in state["claims"])
+ if command.startswith("cmd package resolve-activity"):
+ if state["home_fails"]:
+ sys.exit(1)
+ return (state["home"] or "") + "\n"
+ if command.startswith("settings get global "):
+ return "null\n"
+ return ""
+
+
+class Device:
+ def shell(self, command, read_timeout_s=None):
+ return answer(command)
+
+ def close(self):
+ pass
+
+
+def connect():
+ # recovery.py imports this module and calls connect() directly.
+ return Device()
+
+
+def main():
+ args = sys.argv[1:]
+ if "--batch" in args:
+ for line in sys.stdin:
+ line = line.strip()
+ if line and not line.startswith("#"):
+ state["commands"].append(line)
+ save()
+ return 0
+ print(answer(args[-1]), end="")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
+'''
+
+
+class HomeGuardTest(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.base = Path(tmp.name)
+ self.repo = self.base / "repo"
+ self.tools = self.repo / "tools"
+ self.tools.mkdir(parents=True)
+ for name in ("disable.sh", "disable.ps1", "recovery.py"):
+ shutil.copy2(ROOT / "tools" / name, self.tools / name)
+ (self.tools / "tv.py").write_text(FAKE_TV)
+ # The scripts call the tools venv's Python. Run the real interpreter, which imports the fake
+ # tv.py for the transport and the real recovery.py for the logic. disable.ps1 asks for the
+ # Windows path, which PowerShell resolves to tools/venv/Scripts/python.exe here too.
+ for client in (self.tools / "venv" / "bin" / "python",
+ self.tools / "venv" / "Scripts" / "python.exe"):
+ client.parent.mkdir(parents=True, exist_ok=True)
+ client.write_text(f'#!/bin/sh\nexec "{sys.executable}" "$@"\n')
+ client.chmod(0o755)
+
+ self.home = self.base / "home"
+ self.home.mkdir()
+ self.state_path = self.base / "tv-state.json"
+ self.list_path = self.base / "debloat.txt"
+ self.write_list(["com.example.before", STOCK, "com.example.after"])
+
+ def write_list(self, names):
+ self.list_path.write_text("# My TV\n" + "".join(f"{name}\n" for name in names))
+
+ def tv(self, **overrides):
+ state = {
+ "installed": ["com.example.before", "com.example.after", STOCK],
+ "disabled": [],
+ "home": f"{STOCK}/.MainActivity",
+ "claims": [STOCK],
+ "home_fails": False,
+ "claims_fail": False,
+ "commands": [],
+ }
+ state.update(overrides)
+ self.state_path.write_text(json.dumps(state))
+
+ def disable(self, entry, extra_env=None, list_path=None):
+ env = dict(os.environ, TV_HOST="192.168.1.50", HOME=str(self.home),
+ FAKE_TV_STATE=str(self.state_path), **(extra_env or {}))
+ if entry == "sh":
+ argv = ["bash", str(self.tools / "disable.sh"), str(list_path or self.list_path)]
+ else:
+ argv = [PWSH, "-NoProfile", "-File", str(self.tools / "disable.ps1"),
+ "-TvHost", "192.168.1.50", str(list_path or self.list_path)]
+ result = subprocess.run(argv, cwd=self.repo, env=env, capture_output=True, text=True,
+ timeout=180)
+ with open(self.state_path) as f:
+ return result, json.load(f)["commands"]
+
+ def entries(self):
+ return ("sh", "ps1") if PWSH else ("sh",)
+
+ def output(self, result):
+ return result.stdout + result.stderr
+
+ def test_the_owner_of_home_is_skipped_when_it_is_the_only_home(self):
+ for entry in self.entries():
+ with self.subTest(entry=entry):
+ self.tv()
+ result, sent = self.disable(entry)
+ self.assertEqual(result.returncode, 0, self.output(result))
+ self.assertNotIn(f"pm disable-user --user 0 {STOCK}", sent,
+ "the only Home the TV has must not be disabled")
+ self.assertEqual(sent[:2], ["pm disable-user --user 0 com.example.before",
+ "pm disable-user --user 0 com.example.after"])
+ self.assertIn(f"Skipping {STOCK}", self.output(result))
+
+ def test_a_second_home_lets_the_list_disable_the_owner(self):
+ # The usual end state: the new launcher is Home, and the stock one is still enabled.
+ for entry in self.entries():
+ with self.subTest(entry=entry):
+ self.tv(installed=["com.example.before", "com.example.after", STOCK, CUSTOM],
+ home=f"{CUSTOM}/.MainActivity", claims=[CUSTOM, STOCK])
+ result, sent = self.disable(entry)
+ self.assertEqual(result.returncode, 0, self.output(result))
+ self.assertIn(f"pm disable-user --user 0 {STOCK}", sent)
+
+ def test_a_list_that_disables_every_home_keeps_the_owner(self):
+ self.write_list(["com.example.before", STOCK, CUSTOM])
+ for entry in self.entries():
+ with self.subTest(entry=entry):
+ self.tv(installed=["com.example.before", STOCK, CUSTOM], claims=[STOCK, CUSTOM])
+ result, sent = self.disable(entry)
+ self.assertEqual(result.returncode, 0, self.output(result))
+ self.assertNotIn(f"pm disable-user --user 0 {STOCK}", sent,
+ "the app that owns Home stays enabled")
+ self.assertIn(f"pm disable-user --user 0 {CUSTOM}", sent,
+ "the other launcher listed is still disabled")
+
+ def test_a_tv_that_cannot_list_its_homes_is_left_with_one(self):
+ # tv.py fails or the TV answers nothing: the owner is the only Home this run knows about.
+ for entry in self.entries():
+ with self.subTest(entry=entry):
+ self.tv(claims_fail=True)
+ result, sent = self.disable(entry)
+ self.assertEqual(result.returncode, 0, self.output(result))
+ self.assertNotIn(f"pm disable-user --user 0 {STOCK}", sent)
+
+ def test_force_disables_the_owner(self):
+ for entry in self.entries():
+ with self.subTest(entry=entry):
+ self.tv()
+ result, sent = self.disable(entry, {"FORCE_HOME": "1"})
+ self.assertEqual(result.returncode, 0, self.output(result))
+ self.assertIn(f"pm disable-user --user 0 {STOCK}", sent)
+
+ def test_the_guard_does_not_touch_a_list_without_the_owner(self):
+ # Home belongs to the new launcher: the stock one in the list is fair game.
+ for entry in self.entries():
+ with self.subTest(entry=entry):
+ self.tv(installed=["com.example.before", "com.example.after", STOCK, CUSTOM],
+ home=f"{CUSTOM}/.MainActivity", claims=[CUSTOM, STOCK])
+ result, sent = self.disable(entry)
+ self.assertEqual(result.returncode, 0, self.output(result))
+ self.assertIn(f"pm disable-user --user 0 {STOCK}", sent)
+ self.assertNotIn("Skipping", self.output(result))
+
+ def test_the_skipped_launcher_stays_in_the_recovery_record(self):
+ self.tv()
+ result, sent = self.disable("sh")
+ self.assertEqual(result.returncode, 0, self.output(result))
+ record = next((self.home / ".cleanyourtv").glob("recovery-*.json"))
+ self.assertEqual(json.loads(record.read_text())["packages"][STOCK], "enabled")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_setupwraith_guard.py b/tests/test_setupwraith_guard.py
index ee84b788c..74dc81cbf 100644
--- a/tests/test_setupwraith_guard.py
+++ b/tests/test_setupwraith_guard.py
@@ -30,6 +30,9 @@ class SetupwraithGuardTest(unittest.TestCase):
'#!/bin/sh\n'
'case "$*" in\n'
f' *dumpsys*) {answer} ;;\n'
+ # The Home guard asks which app owns Home and which ones answer it.
+ ' *resolve-activity*) echo "com.google.android.tvlauncher/.MainActivity" ;;\n'
+ ' *query-activities*) echo " com.google.android.tvlauncher/.MainActivity" ;;\n'
' *) cat > "$CAPTURE" ;;\n'
'esac\n')
client.chmod(0o755)
diff --git a/tools/disable.ps1 b/tools/disable.ps1
index 50b8b3a81..d39ecfeb8 100644
--- a/tools/disable.ps1
+++ b/tools/disable.ps1
@@ -38,6 +38,27 @@ if ($pkgs -contains $setup -and -not $env:FORCE_SETUPWRAITH) {
$pkgs = @($pkgs | Where-Object { $_ -ne $setup })
}
}
+# Home guard (#239), the same check as disable.sh: a list that disables the app owning Home leaves the
+# TV with nothing to start Home with. Skip the owner while nothing else on the TV can answer HOME;
+# `$env:FORCE_HOME=1` disables it anyway, for a TV reachable another way.
+if (-not $env:FORCE_HOME) {
+ $homeQuery = 'cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME'
+ $homeLine = @(& $py -I (Join-Path $repo 'tools\tv.py') $homeQuery) |
+ Where-Object { $_ -match '\S' } | Select-Object -Last 1
+ $homePkg = "$homeLine".Trim() -split '/' | Select-Object -First 1
+ if ($homePkg -and ($pkgs -contains $homePkg)) {
+ # Every package with a HOME activity the TV can start now; a disabled one does not answer.
+ $claimQuery = 'cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME'
+ $claims = @(& $py -I (Join-Path $repo 'tools\tv.py') $claimQuery | ForEach-Object {
+ if ($_ -match '^\s*([A-Za-z0-9_.]+)/') { $Matches[1] }
+ } | Sort-Object -Unique)
+ $others = @($claims | Where-Object { $_ -ne $homePkg -and $pkgs -notcontains $_ })
+ if ($others.Count -eq 0) {
+ Write-Warning "Skipping ${homePkg}: it owns Home, and no other app that can answer Home is installed and staying enabled. Make the new launcher Home first (launcher\build-and-install.ps1), then run this list again to disable the old one; or set `$env:FORCE_HOME=1 if you can still reach the TV."
+ $pkgs = @($pkgs | Where-Object { $_ -ne $homePkg })
+ }
+ }
+}
# Same as disable.sh: the state undo needs is recorded before the first command reaches the TV, and
# a failed save leaves the TV untouched (#239).
& $py -I (Join-Path $repo 'tools\recovery.py') --save $List
diff --git a/tools/disable.sh b/tools/disable.sh
index 054295e23..cb0f993aa 100755
--- a/tools/disable.sh
+++ b/tools/disable.sh
@@ -49,6 +49,30 @@ if printf '%s\n' "$PKGS" | grep -x "$SETUP" >/dev/null && [ -z "${FORCE_SETUPWRA
fi
fi
+# Home guard (#239): a list that disables the app owning Home leaves the TV with nothing to start the
+# next time Home is pressed, and on Google TV the setup wizard can take the category instead and
+# crash-loop system_server (docs/TROUBLESHOOTING.md). Skip the owner while nothing else on the TV can
+# answer HOME; FORCE_HOME=1 disables it anyway, for a TV reachable another way.
+# The extra query is worth it only when the list holds Home's own package, which is how a list that
+# leaves the TV without a launcher looks before anything is disabled.
+HOME_QUERY='cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME'
+HOME_PKG=$("$PY" -I tools/tv.py "$HOME_QUERY" 2>/dev/null | tail -n 1 | tr -d '\r' | cut -d/ -f1 || true)
+if [ -n "$HOME_PKG" ] && printf '%s\n' "$PKGS" | grep -qxF "$HOME_PKG" && [ -z "${FORCE_HOME:-}" ]; then
+ # Every package with a HOME activity the TV can start now: disabled packages do not answer, so this
+ # is "what could take Home if the list went through".
+ CLAIMS=$("$PY" -I tools/tv.py 'cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.HOME' 2>/dev/null \
+ | tr -d '\r' | grep -o '^ *[A-Za-z0-9_.]*/' | tr -d ' /' | sort -u || true)
+ # Nothing left to answer Home once the list is applied, or the TV could not say who does: either
+ # way the owner is the only Home this run knows about, so it stays enabled.
+ OTHERS=$(printf '%s\n' "$CLAIMS" | grep -vxF "$HOME_PKG" | grep -vxF "$PKGS" || true)
+ if [ -z "$OTHERS" ]; then
+ echo "Skipping $HOME_PKG: it owns Home, and no other app that can answer Home is installed and" >&2
+ echo "staying enabled. Make the new launcher Home first (launcher/build-and-install.sh), then run" >&2
+ echo "this list again to disable the old one; or set FORCE_HOME=1 if you can still reach the TV." >&2
+ PKGS="$(printf '%s\n' "$PKGS" | grep -vxF "$HOME_PKG" || true)"
+ fi
+fi
+
# The state undo needs goes to disk before the first command reaches the TV, and a failed save stops
# here with the TV untouched: a record written afterwards would describe a TV that is already broken,
# and a retry must not overwrite the one taken before the first change (#239).