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: trace.py and flamechart.py refuse an --out they cannot write
xbsheng3a05af6169a2
diff --git a/tests/test_flamechart.py b/tests/test_flamechart.pyindex d9c0b15ee..3d2f5c221 100644--- a/tests/test_flamechart.py+++ b/tests/test_flamechart.py@@ -8,7 +8,9 @@ neither Perfetto's query engine nor a TV. Drawing needs Pillow, so that test skiRun from the repository root: python3 -m unittest discover -s tests -v"""+import contextlibimport importlib.util+import ioimport osfrom pathlib import Pathimport re@@ -128,6 +130,34 @@ class ArgumentTest(unittest.TestCase):with open(os.devnull, "w") as null, mock.patch("sys.stderr", null):flamechart.parse(argv)+ def parse_error(self, argv):+ with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as caught:+ flamechart.parse(argv)+ self.assertEqual(caught.exception.code, 2)+ return err.getvalue()++ def test_an_out_that_cannot_be_written_is_refused_before_the_traces_are_opened(self):+ # im.save() threw from draw(), after Perfetto's query engine had started and every trace had been+ # read, so a typo in --out read as a chart that failed.+ with tempfile.TemporaryDirectory() as tmp:+ folder = Path(tmp) / "charts"+ folder.mkdir()+ for out, expected in ((str(folder), "is a folder"),+ (str(folder / "chart"), "has no extension"),+ (str(Path(tmp) / "nothere" / "chart.png"), "there is no folder")):+ with self.subTest(out=out):+ self.assertIn(expected, self.parse_error(["a", "--out", out]))+ through = Path(tmp) / "file.png"+ through.write_text("not a folder")+ self.assertIn("is a file, not a folder", self.parse_error(["a", "--out", str(through / "chart.png")]))+ self.assertIn("--out is empty", self.parse_error(["a", "--out", ""]))++ def test_a_png_in_a_folder_that_is_there_is_still_accepted(self):+ with tempfile.TemporaryDirectory() as tmp:+ out = os.path.join(tmp, "chart.png")+ self.assertEqual(flamechart.parse(["a", "b", "--out", out]).out, out)+ self.assertEqual(flamechart.parse(["a", "--out", "chart.png"]).out, "chart.png") # the checkout+@unittest.skipUnless(importlib.util.find_spec("PIL"), "drawing needs Pillow (tools/requirements-perf.txt)")class DrawTest(unittest.TestCase):diff --git a/tests/test_trace.py b/tests/test_trace.pyindex 5fe5f72c1..b01af143b 100644--- a/tests/test_trace.py+++ b/tests/test_trace.py@@ -19,6 +19,7 @@ from pathlib import Pathimport reimport sysimport tempfile+import typesimport unittestfrom unittest import mock@@ -127,6 +128,47 @@ class ArgumentTest(unittest.TestCase):args = trace.parse(["nav"])self.assertEqual((args.runs, args.out, args.package), (5, "traces", "com.gathin.tvhome"))+ def test_a_file_where_the_traces_go_is_refused_before_connecting(self):+ # os.makedirs() threw FileExistsError from main() after the TV had answered the Home query, so a+ # --out typo read as a recording that failed.+ with tempfile.TemporaryDirectory() as tmp:+ target = Path(tmp) / "traces"+ target.write_text("not a folder")+ err = self.parse_error(["home", "--out", str(target)])+ self.assertIn(str(target), err)+ self.assertIn("is a file", err)+ err = self.parse_error(["home", "--out", str(target / "before")])+ self.assertIn(str(target), err)+ self.assertIn("passes through the file", err)+ self.assertIn("--out is empty", self.parse_error(["home", "--out", ""]))++ def test_a_folder_or_a_new_folder_is_still_accepted(self):+ with tempfile.TemporaryDirectory() as tmp:+ existing = Path(tmp) / "before"+ existing.mkdir()+ self.assertEqual(trace.parse(["home", "--out", str(existing)]).out, str(existing))+ new = Path(tmp) / "after"+ self.assertEqual(trace.parse(["home", "--out", str(new)]).out, str(new)) # makedirs() creates it++ def test_nothing_is_asked_of_the_tv_when_the_folder_is_a_file(self):+ with tempfile.TemporaryDirectory() as tmp:+ target = Path(tmp) / "traces"+ target.write_text("not a folder")+ connects = []+ fake_tv = types.ModuleType("tv")+ fake_tv.HOST, fake_tv.PORT = "192.0.2.7", "5555"+ fake_tv.connect = lambda: connects.append(1)+ fake_bench = types.ModuleType("bench")+ fake_bench.accessibility_services = lambda *a: []+ fake_bench.restore_accessibility = lambda *a: None+ with mock.patch.dict(sys.modules, {"tv": fake_tv, "bench": fake_bench}), \+ contextlib.redirect_stderr(io.StringIO()) as err:+ with self.assertRaises(SystemExit) as caught:+ trace.main(["coldsys", "--out", str(target)])+ self.assertEqual(caught.exception.code, 2)+ self.assertEqual(connects, [], "the TV was never opened")+ self.assertIn("is a file", err.getvalue())+class RecordTest(unittest.TestCase):def record(self, device, setup, steps):diff --git a/tools/flamechart.md b/tools/flamechart.mdindex 9a281ff16..19287f884 100644--- a/tools/flamechart.md+++ b/tools/flamechart.md@@ -13,6 +13,9 @@ tools/venv/bin/python tools/flamechart.py traces/before traces/after \--out chart.png```+`--out` is the PNG to write; a folder, a name with no extension and a folder that is not there are refused+before the traces are opened, so a typo cannot read as a chart that failed.+| Option | Default | Notes ||---|---|---|| `TRACE ...` | | Before, then after (up to 4). A folder draws its median run, by the first of time to first frame, median frame time and median RenderThread draw that every run has; the panel names the run and the measure. A folder with none of them in every run is refused. |diff --git a/tools/flamechart.py b/tools/flamechart.pyindex c324dffe3..8aca8308a 100644--- a/tools/flamechart.py+++ b/tools/flamechart.py@@ -11,6 +11,10 @@ visibly shorter. Slices whose name matches --highlight are drawn in magenta, andBEFORE and AFTER are .pftrace files or folders; for a folder the median run is drawn, by the first oftime to first frame, median frame time and median RenderThread draw that every run has. Needs the optional packages intools/requirements-perf.txt. Read tools/flamechart.md first.++--out is the PNG to write, and it is checked before the traces are opened: a folder, a name with no+extension, and a folder that is not there are argument errors (exit 2) rather than a traceback after the+traces have been read."""import argparseimport colorsys@@ -186,10 +190,35 @@ def draw(panels, rx, title, subtitle, out, width=1600):return im.size+def output_path(value):+ """The PNG --out names, judged before the traces are opened and before Pillow is imported.++ im.save() answers a folder with IsADirectoryError (or ValueError: unknown file extension, when the+ folder's name has no suffix), a name with no extension with that ValueError, and a folder that is not+ there with FileNotFoundError - each a traceback with exit 1, thrown after Perfetto's query engine has+ been started and every trace read. 1 is also what a run that drew no chart returns, so the reader+ cannot tell a typo from a chart that failed. Refused here it is an argument error, before anything is+ read; a suffixless file cannot be saved at all, so it is refused rather than guessed at.+ """+ if not value:+ raise argparse.ArgumentTypeError("--out is empty: name the PNG to write, e.g. --out chart.png")+ if os.path.isdir(value):+ raise argparse.ArgumentTypeError(f"{value} is a folder, so no PNG could be written there: name the "+ f"file, e.g. --out {os.path.join(value, 'chart.png')}")+ if not os.path.splitext(value)[1]:+ raise argparse.ArgumentTypeError(f"{value} has no extension, so the format is unknown: name it {value}.png")+ folder = os.path.dirname(value) or "."+ if os.path.exists(folder) and not os.path.isdir(folder):+ raise argparse.ArgumentTypeError(f"{value}: {folder} is a file, not a folder")+ if not os.path.isdir(folder):+ raise argparse.ArgumentTypeError(f"{value}: there is no folder {folder} - create it first")+ return value++def parse(argv):p = argparse.ArgumentParser(description="Before/after flame chart PNG from tools/trace.py traces. See tools/flamechart.md.")p.add_argument("traces", nargs="+", metavar="TRACE", help="before, then after: .pftrace files or folders (median run)")- p.add_argument("--out", required=True, help="the PNG to write")+ p.add_argument("--out", required=True, type=output_path, help="the PNG to write")p.add_argument("--highlight", default="^(activityResume|RV OnBindView)$",help="regex of slice names to draw in magenta and total (default: onResume and tile binding)")p.add_argument("--window", default="first-frame",diff --git a/tools/trace.md b/tools/trace.mdindex b057f56c9..41eb6883c 100644--- a/tools/trace.md+++ b/tools/trace.md@@ -25,6 +25,9 @@ It sends a binary trace config, which Android 9 accepts without the `--txt` optiTV_HOST=<tv ip> tools/venv/bin/python -I tools/trace.py home --runs 5 --out traces/before```+`--out` is the folder the traces are written into, and it is created if it is not there. A file where the+folder goes, a path through a file and an empty `--out` are refused before the TV is asked anything.+| Scenario | Recorded | Use for ||---|---|---|| `home` | HOME pressed while another app is in front | Most Home changes |diff --git a/tools/trace.py b/tools/trace.pyindex 1ec9fcc33..38843edab 100644--- a/tools/trace.py+++ b/tools/trace.py@@ -15,6 +15,10 @@ and later. Set TV_HOST to the TV's IP (and TV_PORT if it is not 5555). Usage:tools/trace.py custom --setup 'input keyevent KEYCODE_HOME' --setup 'sleep 2' \\--step 'input keyevent KEYCODE_DPAD_RIGHT' --step 'sleep 1' --out DIR+--out DIR is the folder the traces go into; it is created if it is not there. A file where the folder+goes, a path through a file, and an empty --out are refused as argument errors (exit 2) before the TV is+asked anything, so a typo cannot read as a recording that failed.+Scenarios (setup runs before the recording starts, so it stays out of the trace):cold another app in front, the launcher force-stopped, then started with `am start -W`coldsys Home in front, the launcher force-stopped: Android starts it again by itself@@ -26,6 +30,7 @@ import argparseimport base64import jsonimport os+from pathlib import Pathimport reimport sysimport time@@ -110,12 +115,35 @@ def scenario(name, launcher_component, other_component, setup=(), steps=()):return list(setup), list(steps)+def traces_folder(value):+ """--out as the folder the traces go into, judged before anything is asked of the TV.++ os.makedirs() answers a file where the folder goes with FileExistsError, a path through a file with+ NotADirectoryError and an empty argument with FileNotFoundError: three tracebacks with exit 1, each+ thrown from main() after the TV has answered the Home query and the model was read, so the reader+ cannot tell their argument from a recording that failed. Refusing here makes it an argument error+ like --runs or --app, with the run never reaching the TV. A folder that does not exist yet is fine:+ makedirs() creates it, as the default traces/ always has.+ """+ if not value:+ raise argparse.ArgumentTypeError("--out is empty: name the folder for the traces, e.g. --out traces/before")+ path = Path(value)+ if path.exists() and not path.is_dir():+ raise argparse.ArgumentTypeError(f"{value} is a file, and --out is the folder the traces go into: "+ f"nothing could be recorded into it")+ for parent in path.parents:+ if parent.exists() and not parent.is_dir():+ raise argparse.ArgumentTypeError(f"{value} passes through the file {parent}, so the folder the "+ f"traces go into cannot be made")+ return value++def parse(argv):p = argparse.ArgumentParser(description="Record Perfetto traces on the TV around a launcher scenario. ""See tools/trace.md.")p.add_argument("scenario", choices=["cold", "coldsys", "home", "nav", "custom"])p.add_argument("--runs", type=int, default=5, help="how many traces to record (default 5)")- p.add_argument("--out", default="traces", help="folder for the traces (default traces/)")+ p.add_argument("--out", type=traces_folder, default="traces", help="folder for the traces (default traces/)")p.add_argument("--package", default="com.gathin.tvhome", help="the launcher's package (default com.gathin.tvhome)")p.add_argument("--app", metavar="COMPONENT",help="the other app for cold and home, as package/activity (default: found on the TV)")