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: manage.py set refuses a string the launcher answers with a default
xbshengf646cb564fae
diff --git a/tests/test_manage_set_enums.py b/tests/test_manage_set_enums.pynew file mode 100644index 000000000..422121753--- /dev/null+++ b/tests/test_manage_set_enums.py@@ -0,0 +1,195 @@+"""tools/manage.py set refuses a value the launcher's closed-set string readers answer with a default.++Four keys in the Keys table name the values they take - `glow_style` (radial or horizon), `glass_style` (glass,+rim or halo), `wallpaper_order` (shuffle or sequential) and `clock_format` (12, 24 or system) - and the readers in+the launcher keep those and nothing else: Config.glowStyle() is `GLOW_HORIZON.equalsIgnoreCase(value.trim()) ?+GLOW_HORIZON : GLOW_RADIAL`, glassStyle() answers glass for anything else, WallpaperRotation.validOrder() is+`ORDER_SEQUENTIAL.equals(order) || ORDER_SHUFFLE.equals(order)` and ClockFormat applies "12" or "24" and lets+every other mode follow the TV. A string key of another type is refused by value_as since #3398, but these four+were read as free text: `set glow_style off` printed `glow_style = "off"`, wrote the theme and pushed it, and the+launcher answered radial - the same dead value #3429 removed from themes/cinematic and themes/red-rain.++The values come from the launcher, not from a second copy in the tool: the tests below read the GLOW_/GLASS_/+ORDER_ constants and the comparison each reader makes out of the Java, so a new value in the launcher fails here+instead of leaving set refusing a value the TV would have kept.+"""+import json+import re+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "tools"))+import manage # noqa: E402++JAVA = ROOT / "launcher" / "app" / "src" / "main" / "java" / "com" / "gathin" / "tvhome"+CONFIG_JAVA = JAVA / "Config.java"+ROTATION = JAVA / "WallpaperRotation.java"+CLOCK = JAVA / "ClockFormat.java"+README = ROOT / "themes" / "README.md"++# The four keys this rule is about, with a value none of them takes and the one the launcher answers instead.+REFUSED = {+ "glow_style": ("off", "radial"),+ "glass_style": ("frosted", "glass"),+ "wallpaper_order": ("random", "shuffle"),+ "clock_format": ("13", "system"),+}+++def constants(source, prefix):+ """The string values of the NAME = "value" constants that start with prefix, as a set."""+ return set(re.findall(prefix + r'[A-Z_]+ = "([^"]+)"', source))+++def keys_row(key):+ """The Keys-table row of a key in themes/README.md, as (type cell, meaning cell)."""+ text = README.read_text(encoding="utf-8")+ for row in manage.table_rows(text[text.index("## Keys"):], "| Key |"):+ if key in re.findall(r"`([a-z_]+)`", row[0]):+ return (manage.plain(row[1]), manage.plain(row[2]))+ return None+++class SetEnumTest(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.theme = Path(self.tmp.name) / "my-theme"+ self.theme.mkdir()+ self.config = self.theme / "config.json"+ # cmd_set ends by pushing the theme with tools/theme.sh; the tests stop before the TV.+ patcher = mock.patch.object(manage, "run")+ self.push = patcher.start()+ self.push.return_value = 0+ self.addCleanup(patcher.stop)++ def set_key(self, key, value):+ """Runs set the way main() does; returns the refusal text, or None when the value was written."""+ try:+ with mock.patch("sys.stdout"):+ manage.cmd_set(key, value, str(self.theme))+ except SystemExit as stop:+ return str(stop.code)+ return None++ def written(self):+ return json.loads(self.config.read_text(encoding="utf-8")) if self.config.is_file() else None++ def test_every_closed_set_key_refuses_a_value_it_does_not_take(self):+ for key, (value, fallback) in REFUSED.items():+ with self.subTest(key=key):+ self.config.unlink(missing_ok=True)+ self.push.reset_mock()+ refusal = self.set_key(key, value)+ self.assertIsNotNone(refusal, f"{key} took {value!r}, which the launcher answers with {fallback}")+ self.assertIn(key, refusal)+ self.assertIn(repr(value), refusal, "the refusal should quote what was passed")+ for allowed in manage.ENUMS[key][0]:+ self.assertIn(allowed, refusal, f"the refusal should name {allowed}, another value it takes")+ self.assertIn("Nothing was written or pushed", refusal)+ self.assertIsNone(self.written(), f"a refused value must not touch the theme ({key})")+ self.push.assert_not_called()++ def test_the_refusal_says_what_the_launcher_answers_instead(self):+ refusal = self.set_key("glow_style", "off")+ self.assertIn("radial", refusal)+ refusal = self.set_key("glass_style", "frosted")+ self.assertIn("glass", refusal)+ refusal = self.set_key("wallpaper_order", "random")+ self.assertIn("shuffle", refusal)+ refusal = self.set_key("clock_format", "13")+ self.assertIn("system", refusal)++ def test_the_style_keys_are_read_trimming_and_ignoring_case(self):+ # Config.glowStyle()/glassStyle() trim the string and compare with equalsIgnoreCase, so these are kept.+ for key, value, kept in (("glow_style", " HORIZON ", "HORIZON"), ("glass_style", " Rim ", "Rim"),+ ("glow_style", "radial", "radial"), ("glass_style", "halo", "halo")):+ with self.subTest(key=key, value=value):+ self.assertIsNone(self.set_key(key, value), f"{value!r} is a value {key} takes")+ self.assertEqual(self.written()[key], kept)++ def test_wallpaper_order_is_read_exactly(self):+ # validOrder() compares the string with equals, so a capital is not the value it looks like.+ refusal = self.set_key("wallpaper_order", "Sequential")+ self.assertIn("shuffle", refusal)+ self.assertIsNone(self.written())+ self.assertIsNone(self.set_key("wallpaper_order", " sequential "))+ self.assertEqual(self.written()["wallpaper_order"], "sequential")++ def test_clock_format_takes_12_24_and_system(self):+ for value in ("12", "24", "system", "System"):+ with self.subTest(value=value):+ self.assertIsNone(self.set_key("clock_format", value), f"{value!r} is a mode the clock keeps")+ self.assertEqual(self.written()["clock_format"], value.strip())+ self.assertIsNotNone(self.set_key("clock_format", "12-hour"))++ def test_a_value_written_is_still_the_text_the_author_typed(self):+ # The launcher trims every string it reads, so set writes the trimmed one and nothing else is changed.+ self.assertIsNone(self.set_key("glow_style", "horizon"))+ self.assertEqual(self.written(), {"glow_style": "horizon"})++ def test_a_string_key_with_no_closed_set_still_takes_any_text(self):+ for key, value in (("greeting_name", "off"), ("festival", "random"), ("locale", "vi")):+ with self.subTest(key=key):+ self.assertIsNone(self.set_key(key, value), f"{key} is free text, so {value!r} is fine")+ self.assertEqual(self.written()[key], value)++ def test_a_number_key_is_unaffected(self):+ self.assertIsNone(self.set_key("columns", "4"))+ self.assertEqual(self.written()["columns"], 4)++ def test_the_values_are_the_ones_the_launcher_keeps(self):+ config = CONFIG_JAVA.read_text(encoding="utf-8")+ rotation = ROTATION.read_text(encoding="utf-8")+ self.assertEqual(set(manage.ENUMS["glow_style"][0]), constants(config, "GLOW_"))+ self.assertEqual(set(manage.ENUMS["glass_style"][0]), constants(config, "GLASS_"))+ self.assertEqual(set(manage.ENUMS["wallpaper_order"][0]), constants(rotation, "ORDER_"))+ # ClockFormat has no constant for "system": it is the mode the clock keeps for anything that is not 12+ # or 24, so the third value is named here and the two the Java compares are read out of it.+ self.assertEqual(set(manage.ENUMS["clock_format"][0]), {"12", "24", "system"})+ clock = CLOCK.read_text(encoding="utf-8")+ for mode in ("12", "24"):+ self.assertIn(f'"{mode}".equals(mode)', clock,+ f"ClockFormat no longer compares {mode} the way this rule assumes")++ def test_the_comparison_is_the_one_each_reader_makes(self):+ config = CONFIG_JAVA.read_text(encoding="utf-8")+ # Both style readers trim and ignore case; the map says so with True, and the fallback it names is the+ # constant each method answers with.+ self.assertIn("GLOW_HORIZON.equalsIgnoreCase(value.trim())", config)+ self.assertIn(".equalsIgnoreCase(v)", config)+ self.assertTrue(manage.ENUMS["glow_style"][2])+ self.assertTrue(manage.ENUMS["glass_style"][2])+ self.assertEqual(manage.ENUMS["glow_style"][1], "radial")+ self.assertEqual(manage.ENUMS["glass_style"][1], "glass")+ # validOrder() compares the string with equals, so a capital there is not kept: False in the map.+ rotation = ROTATION.read_text(encoding="utf-8")+ self.assertIn("ORDER_SEQUENTIAL.equals(order)", rotation)+ self.assertFalse(manage.ENUMS["wallpaper_order"][2])+ self.assertEqual(manage.ENUMS["wallpaper_order"][1], "shuffle")+ # clock_format is the one reader that answers a default for every mode it has not got, so a capital in+ # SYSTEM is the same mode; the map says so, and names the mode.+ self.assertTrue(manage.ENUMS["clock_format"][2])+ self.assertEqual(manage.ENUMS["clock_format"][1], "system")++ def test_every_closed_set_key_has_a_row_that_names_its_values(self):+ for key, (values, fallback, _) in manage.ENUMS.items():+ with self.subTest(key=key):+ row = keys_row(key)+ self.assertIsNotNone(row, f"{key} is read as a closed set but themes/README.md has no row for it")+ cell = " ".join(row)+ for value in values:+ self.assertIn(value, cell, f"the {key} row should name {value}, a value the launcher keeps")+ self.assertIn(fallback, cell, f"the {key} row should say what it answers otherwise")++ def test_enum_value_leaves_a_key_with_no_closed_set_alone(self):+ self.assertEqual(manage.enum_value("greeting_name", " off "), " off ")+ self.assertEqual(manage.enum_value("not_a_key", "off"), "off")+++if __name__ == "__main__":+ unittest.main()diff --git a/themes/README.md b/themes/README.mdindex e3736d7f7..99192a8a2 100644--- a/themes/README.md+++ b/themes/README.md@@ -181,7 +181,7 @@ A new key needs one there in the same pull request.| `power_on_home_always` | bool | Home at every power-on, whatever the TV put in front: the last HDMI input, Live TV or an app, for TVs that come back to the last source (Philips). Unlike `power_on_home`, it does not wait for a window to show: the Home screen comes up about a second after the screen turns on (`HOME_KEY_SERVICE=1`). A key pressed before that wins. Ignored with `boot_to_live_tv`, or with an Open on start app. Off by default || `inputs_connected_only` | bool | The Inputs list shows only HDMI ports and CEC devices that report connected; empty ports, the AV jacks and devices asleep in standby fold behind a "More inputs" row that expands them. Some TVs (TCL) report an empty HDMI port as connected-standby, the same state a sleeping device has, so a device in standby is folded too. An HDMI row whose state the TV cannot be trusted with stays (`false` by default) || `inputs_cec_state_only` | bool | Only CEC device rows in the Inputs list show a connection state ("Steam Deck · HDMI 1", Connected); bare HDMI ports show none. For TVs that put port states on the wrong port: TCL UnionTV (Android 9) reports its empty HDMI 1 as connected and a device on HDMI 2 nowhere, while its CEC device list stays right. A device without CEC shows no state (`false` by default) |-| `clock_format` | `12`, `24` or `system` | The launcher's clocks (Home and the clock screensaver) in 12- or 24-hour time whatever the TV is set to; `system` (the default) follows the TV. Launcher settings' Clock row sets it too |+| `clock_format` | `12`, `24` or `system` | The launcher's clocks (Home and the clock screensaver) in 12- or 24-hour time whatever the TV is set to; `system` (the default) follows the TV, and so does any other value, which is why tools/manage.py's `set` refuses one. Launcher settings' Clock row sets it too || `race_calendar` | list of races | F1 race-weekend mode: from 12 hours before a weekend's first session until 4 hours after the race starts, a panel under the clock shows the next session with a countdown (or the live one) and the weekend's session times in the TV's time zone. Write it with `tools/venv/bin/python -I tools/race_calendar.py <theme folder>`, which fetches the season from the free Jolpica API; the launcher itself never goes online || `home_idle_clock_minutes` | 0 to 1440 | Minutes Home may sit untouched before it shows the clock screensaver (a thin clock and date drifting over a slow glow, as the system "Clock" screensaver does). Any key returns to Home. It starts only from Home, never over Live TV or an app; 0 is off (default) || `back_opens_clock` | bool | Back on the Home screen opens the clock screensaver (the same screen as `home_idle_clock_minutes`) instead of doing nothing. Back inside apps, Settings and the App library is unchanged; any key leaves the clock for Home. `false` by default |diff --git a/tools/manage.py b/tools/manage.pyindex 90dd0b11c..729ddd8f0 100644--- a/tools/manage.py+++ b/tools/manage.py@@ -16,8 +16,10 @@ pushes it with the platform's theme script, as themes/README.md describes; it ne--theme at the project's themes/ or examples/ is refused before anything is written. set reads the value the waythe key's own type in the Keys table needs - true or false for a bool, a JSON list, object or number where thetable says so, the text itself for a string - and refuses one the launcher would ignore or a number outside the-range the table states. A theme's config.json is hand-edited, so one that cannot be read, is not JSON, or is not a-JSON object is named before the key is written, and a write it cannot make says so instead of ending in a traceback.+range the table states. A string whose row names the values it takes (glow_style, glass_style, wallpaper_order,+clock_format) is held to them, since the launcher answers any other value with its own default. A theme's+config.json is hand-edited, so one that cannot be read, is not JSON, or is not a JSON object is named before the+key is written, and a write it cannot make says so instead of ending in a traceback.set's own arguments are read first: a switch without a value, a --theme without the folder behind it, and a wordleft over are answered with the usage line and exit 2 before a theme folder is read or written. list, status,show, install and remove read their own words the same way, before anything is read from this checkout or asked@@ -218,6 +220,41 @@ def number_in_range(key, item, parsed, text):return value+# The string keys a Keys-table row names the values of, with the one the launcher answers instead and whether its+# reader ignores case. Config.glowStyle() is `GLOW_HORIZON.equalsIgnoreCase(value.trim()) ? GLOW_HORIZON :+# GLOW_RADIAL` and glassStyle() answers glass to anything else; WallpaperRotation.validOrder() is+# `ORDER_SEQUENTIAL.equals(order) || ORDER_SHUFFLE.equals(order)`, so `Sequential` is shuffle; ClockFormat applies+# "12" or "24" and lets every other mode follow the TV, which is what `system` means, so a capital in SYSTEM is the+# same mode. A value outside these sets is not an error on the TV - the default comes back - so set would report a+# switch it left where it was, the dead `"glow_style": "off"` #3429 removed from two themes.+ENUMS = {+ "glow_style": (("radial", "horizon"), "radial", True),+ "glass_style": (("glass", "rim", "halo"), "glass", True),+ "clock_format": (("12", "24", "system"), "system", True),+ "wallpaper_order": (("shuffle", "sequential"), "shuffle", False),+}+++def enum_value(key, value):+ """The string as the key's own reader keeps it, or a refusal naming the values it takes.++ The launcher trims every string it reads (`string()`, `v instanceof String ? ((String) v).trim() : fallback`),+ so the value written is the trimmed one. A key with no closed set - a name, a festival, a locale - is handed+ back untouched, and so is a number written for a string key (`set greeting_name 42` is the text 42).+ """+ rule = ENUMS.get(key)+ if rule is None:+ return value+ values, fallback, ignores_case = rule+ trimmed = value.strip()+ kept = trimmed.lower() if ignores_case else trimmed+ if kept not in values:+ allowed = ", ".join(values[:-1]) + " or " + values[-1]+ sys.exit(f"{key} takes {allowed}, so {value!r} is not one the launcher keeps: it answers "+ f"{fallback} instead, and the theme would change nothing. Nothing was written or pushed.")+ return trimmed++def value_as(key, item, text):"""The argument read the way the key's type needs, or a refusal naming what the key takes."""kind = declared_kind(item)@@ -231,9 +268,9 @@ def value_as(key, item, text):try:parsed = json.loads(text)except ValueError:- return text+ return enum_value(key, text)# A string key is read as a String only, so `set greeting_name 42` means the text 42, not a number.- return parsed if isinstance(parsed, str) else text+ return enum_value(key, parsed if isinstance(parsed, str) else text)try:parsed = json.loads(text)except ValueError: