From 070cdf298aebbc70f2fbaddf3e2590deb247bdab Mon Sep 17 00:00:00 2001 From: adamXbot <111877622+adamXbot@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:50:16 +1100 Subject: [PATCH] Show this machine under the welcome tagline, with an OS symbol Bare fxcss now prints one line under the tagline: the OS, the Firefox build, the default profile and what is themed in it. The line is read from files only, so Firefox is never started, and anything unreadable drops the line rather than the welcome screen. Each OS name gets the symbol for its special key in the brand colour: Command on macOS, the Windows key on Windows and Meta on Linux. doctor's firefox row uses the same label. A terminal that cannot show the symbols gets the name alone. Co-Authored-By: Claude Opus 5.5 --- fxcss/cli.py | 52 +++++++- fxcss/core.py | 22 ++++ fxcss/style.py | 31 ++++- fxcss/support.py | 14 +- tests/test_welcome_context.py | 240 ++++++++++++++++++++++++++++++++++ 5 files changed, 346 insertions(+), 13 deletions(-) create mode 100644 tests/test_welcome_context.py diff --git a/fxcss/cli.py b/fxcss/cli.py index 023beac..3119561 100644 --- a/fxcss/cli.py +++ b/fxcss/cli.py @@ -105,12 +105,62 @@ def _command_row(name, summary, width): return [f" {shown}{' ' * (width - len(name))}{lines[0].lstrip()}"] + lines[1:] +def _installed_theme_name(manifest): + """A short name for an installed theme: the repository or folder, not its ref.""" + source = manifest.get("source") or {} + if source.get("name"): + return source["name"] + if source.get("path"): + return Path(source["path"]).name or source["path"] + return manifest.get("theme") or "a theme" + + +def _machine_context(): + """This machine at a glance: the OS, its Firefox and what is themed. + + Read from files only, so bare `fxcss` stays instant and never starts + Firefox. The profile and theme are left out when no single profile can be + named, the same case `install` would stop and ask about. + """ + from . import install, style + parts = [style.platform_label(sys.platform)] + try: + binary = core.find_firefox(None) + except SystemExit: + binary = None + if not binary or not Path(binary).exists(): + return parts + [f"{style.muted('Firefox')} {style.bad('not found')}", + f"{style.muted('set')} {style.cmd('FIREFOX_BIN')} " + f"{style.muted('to its path')}"] + name, version = core.build_identity(binary) + parts.append(f"{style.muted(name)} {version}" if version else style.muted(name)) + + profiles = install.discover_profiles() + picks = profiles if len(profiles) == 1 else [p for p in profiles if p["default"]] + if len(picks) != 1: + return parts + parts.append(style.clip(picks[0]["name"], 32)) + manifest = install.read_manifest(picks[0]["path"]) + if manifest: + theme = style.clip(_installed_theme_name(manifest), 32) + parts.append(f"{style.strong(theme)} {style.muted('installed')}") + elif profile_state(picks[0]) == "unmanaged": + parts.append(style.muted("has its own chrome/")) + else: + parts.append(style.muted("no theme yet")) + return parts + + def landing_text(): """What bare `fxcss` prints: where to start, by what someone came to do.""" from . import style examples = [(name, args) for _, q, _, subset in GROUPS if q for name, args in subset] width = max(len(f"fxcss {n} {a}".rstrip()) for n, a in examples) + 2 out = [f" {style.brand('fxcss')} {TAGLINE}"] + try: + out += style.dotted(_machine_context(), indent=9) + except Exception: # a courtesy line must never stop the welcome screen + pass for title, question, _, subset in GROUPS: if not question: continue @@ -2744,7 +2794,7 @@ def cmd_doctor(args): listed = any(b["path"] == firefox for b in builds) for line in style.rows([ ("fxcss", __version__), - ("firefox", f"{info['version']} on {style.platform_name(info['os'])}" + ("firefox", f"{info['version']} on {style.platform_label(info['os'])}" f" {style.muted('build ' + str(info['buildID']))}"), # The builds table below names the binary in use; say it here # only when that table will not. diff --git a/fxcss/core.py b/fxcss/core.py index bf02453..e9bf304 100644 --- a/fxcss/core.py +++ b/fxcss/core.py @@ -16,6 +16,7 @@ """ import base64 +import configparser import hashlib import json import os @@ -2618,6 +2619,27 @@ def record(label, binary): for label in CHANNEL_ORDER if label in found] +def application_ini(binary): + """The [App] section of a build's application.ini, or None if unreadable.""" + binary = Path(binary) + for ini in (binary.parent / "application.ini", + binary.parent.parent / "Resources" / "application.ini"): + if ini.is_file(): + config = configparser.ConfigParser(interpolation=None) + try: + config.read(ini, encoding="utf-8") + except configparser.Error: + return None + return dict(config["App"]) if config.has_section("App") else {} + return None + + +def build_identity(binary): + """A build's (product name, version), never by running it: name may be a fork's.""" + app = application_ini(binary) or {} + return app.get("name") or "Firefox", app.get("version") + + def firefox_version(binary): """The build's version string, or None if it will not say.""" try: diff --git a/fxcss/style.py b/fxcss/style.py index ef19cca..d932d18 100644 --- a/fxcss/style.py +++ b/fxcss/style.py @@ -55,6 +55,10 @@ def _utf8(): "ok", "!", "x", "->", "-", "*", "...", "-") POINTER, UPDOWN, ARROWS = ">", "up/down", "arrows" +# Beside an operating system's name, never instead of it. Each is the symbol +# for that system's special key: Command, the Windows key and Meta. +OS_MARKS = {"macOS": "⌘", "Windows": "⊞", "Linux": "◆"} if _utf8() else {} + def set_colour(on): """Force colour on or off for the rest of the run (None: detect again).""" @@ -349,6 +353,22 @@ def _visible(text): return re.sub(r"\033\[[0-9;]*m", "", text) +def dotted(items, indent=2, width=None, on=None): + """Styled items joined by a dim dot, breaking between items at the edge.""" + width = width or term_width() + separator = f" {muted(DOT, on=on)} " + lines = [[]] + used = indent + for item in items: + cells = len(_visible(item)) + if lines[-1] and used + 3 + cells >= width: + lines.append([]) + used = indent + used += cells + (3 if lines[-1] else 0) + lines[-1].append(item) + return [" " * indent + separator.join(line) for line in lines if line] + + def title(command_name, context=None, on=None): """The first line of a long-running command: the mark, the verb, where.""" line = f" {brand('fxcss', on=on)} {heading(command_name, on=on)}" @@ -358,8 +378,17 @@ def title(command_name, context=None, on=None): def platform_name(os_name): + """A reader's name for an OS, from what Firefox or sys.platform calls it.""" return {"Darwin": "macOS", "Linux": "Linux", "WINNT": "Windows", - "Windows_NT": "Windows"}.get(os_name, os_name) + "Windows_NT": "Windows", "darwin": "macOS", "linux": "Linux", + "win32": "Windows"}.get(os_name, os_name) + + +def platform_label(os_name, on=None): + """`⌘ macOS`: the name, after its symbol in the brand colour when it has one.""" + name = platform_name(os_name) + mark = OS_MARKS.get(name) + return f"{brand(mark, on=on)} {name}" if mark else name def agree(count, many, one): diff --git a/fxcss/support.py b/fxcss/support.py index dd4524c..ea90cde 100644 --- a/fxcss/support.py +++ b/fxcss/support.py @@ -27,7 +27,6 @@ """ import bisect -import configparser import gzip import json import os @@ -186,17 +185,10 @@ def get(self, version): def build_version(binary): """The version string of a Firefox build, read without running it.""" - binary = Path(binary) - for ini in (binary.parent / "application.ini", - binary.parent.parent / "Resources" / "application.ini"): - if ini.is_file(): - config = configparser.ConfigParser() - try: - config.read(ini, encoding="utf-8") - return config.get("App", "Version", fallback=None) - except configparser.Error: - break from . import core + app = core.application_ini(binary) + if app is not None: + return app.get("version") return core.firefox_version(binary) diff --git a/tests/test_welcome_context.py b/tests/test_welcome_context.py new file mode 100644 index 0000000..ad7cd0a --- /dev/null +++ b/tests/test_welcome_context.py @@ -0,0 +1,240 @@ +"""The line under the welcome tagline, and the OS symbol it shares with doctor.""" + +import argparse +import contextlib +import io +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from fxcss import cli, core, install, style, support + + +def plain(parts): + return " · ".join(style._visible(part) for part in parts) + + +class PlatformLabelTests(unittest.TestCase): + @unittest.skipUnless(style.OS_MARKS, "this console cannot show the symbols") + def test_each_system_uses_its_special_key_symbol(self): + self.assertEqual(style.OS_MARKS, {"macOS": "⌘", "Windows": "⊞", "Linux": "◆"}) + + def test_each_os_has_its_symbol_under_every_name_it_goes_by(self): + with mock.patch.dict(style.OS_MARKS, {"macOS": "⌘", "Windows": "⊞", "Linux": "◆"}): + for names, label in ((("Darwin", "darwin"), "⌘ macOS"), + (("WINNT", "Windows_NT", "win32"), "⊞ Windows"), + (("Linux", "linux"), "◆ Linux")): + for name in names: + with self.subTest(name=name): + self.assertEqual(style.platform_label(name, on=False), label) + + def test_only_the_symbol_takes_the_brand_colour(self): + with mock.patch.dict(style.OS_MARKS, {"macOS": "⌘"}): + self.assertEqual(style.platform_label("Darwin", on=True), + f"{style.brand('⌘', on=True)} macOS") + + def test_an_os_without_a_symbol_is_just_its_name(self): + self.assertEqual(style.platform_label("FreeBSD", on=True), "FreeBSD") + + def test_a_terminal_without_the_glyphs_gets_the_name_alone(self): + with mock.patch.dict(style.OS_MARKS, clear=True): + self.assertEqual(style.platform_label("Darwin", on=True), "macOS") + + +class DottedTests(unittest.TestCase): + def test_items_share_a_line_when_they_fit(self): + self.assertEqual(style.dotted(["a", "b"], indent=2, width=60, on=False), + [f" a {style.DOT} b"]) + + def test_breaks_between_items_at_the_edge(self): + lines = style.dotted(["a" * 30, "b" * 30, "c" * 30], indent=9, width=60, on=False) + self.assertEqual(lines, [" " * 9 + "a" * 30, " " * 9 + "b" * 30, " " * 9 + "c" * 30]) + + def test_colour_codes_take_no_room(self): + # Fits in 60 columns on screen; counting the codes would break the line. + items = [style.brand("a" * 30, on=True), style.brand("b" * 20, on=True)] + self.assertEqual(len(style.dotted(items, indent=2, width=60, on=True)), 1) + + +class ContextTests(unittest.TestCase): + """What the line says, for each state of the machine.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.binary = self.root / "firefox" + self.binary.write_text("") + self.write_ini("Firefox", "155.0.1") + self.profile = self.root / "abc.default-release" + self.profile.mkdir() + self.profiles = [{"name": "default-release", "path": self.profile, "default": True}] + for target, value in (("fxcss.cli.core.find_firefox", lambda _: str(self.binary)), + ("fxcss.install.discover_profiles", lambda: self.profiles)): + patcher = mock.patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + patcher = mock.patch("fxcss.cli.sys.platform", "darwin") + patcher.start() + self.addCleanup(patcher.stop) + style.set_colour(False) + self.addCleanup(style.set_colour, None) + + def write_ini(self, name, version): + (self.root / "application.ini").write_text( + f"; Generated\n[App]\nName={name}\nVersion={version}\n", encoding="utf-8") + + def manifest(self, **fields): + with mock.patch.object(install, "read_manifest", return_value=fields): + return plain(cli._machine_context()) + + def test_a_theme_from_github_goes_by_its_repository_name(self): + text = self.manifest(theme="AdamXweb/WhiteSur@v1", source={"name": "WhiteSur"}) + self.assertTrue(text.endswith( + "macOS · Firefox 155.0.1 · default-release · WhiteSur installed"), text) + + def test_a_local_theme_goes_by_its_folder(self): + self.assertIn(" · mine installed", self.manifest(source={"path": "/themes/mine"})) + + def test_a_theme_with_only_a_raw_id_shows_it(self): + self.assertIn(" · whitesur installed", self.manifest(theme="whitesur", source={})) + + def test_a_long_theme_name_is_cut(self): + text = self.manifest(source={"name": "x" * 80}) + self.assertNotIn("x" * 33, text) + self.assertIn(f"{style.ELLIPSIS} installed", text) + + def test_an_empty_profile_says_no_theme_yet(self): + self.assertIn(" · default-release · no theme yet", plain(cli._machine_context())) + + def test_a_hand_installed_theme_is_not_called_no_theme(self): + chrome = self.profile / "chrome" + chrome.mkdir() + (chrome / "userChrome.css").write_text("") + text = plain(cli._machine_context()) + self.assertIn(" · has its own chrome/", text) + self.assertNotIn("no theme", text) + + def test_a_fork_goes_by_its_own_name(self): + self.write_ini("LibreWolf", "140.0") + self.assertIn(" · LibreWolf 140.0 · ", plain(cli._machine_context())) + + def test_a_build_with_no_readable_version_still_says_firefox(self): + (self.root / "application.ini").unlink() + self.assertEqual(plain(cli._machine_context()).split(" · ")[1], "Firefox") + + def test_no_firefox_names_the_setting_that_finds_it(self): + with mock.patch("fxcss.cli.core.find_firefox", side_effect=SystemExit("none")): + self.assertTrue(plain(cli._machine_context()).endswith( + "macOS · Firefox not found · set FIREFOX_BIN to its path")) + + def test_a_firefox_path_that_does_not_exist_is_not_found(self): + self.binary.unlink() + self.assertIn("Firefox not found", plain(cli._machine_context())) + + def test_no_clear_default_names_no_profile(self): + self.profiles[:] = [dict(self.profiles[0], default=True), + dict(self.profiles[0], name="other", default=True)] + self.assertTrue(plain(cli._machine_context()).endswith("Firefox 155.0.1")) + + def test_no_profiles_stops_at_firefox(self): + self.profiles[:] = [] + self.assertTrue(plain(cli._machine_context()).endswith("Firefox 155.0.1")) + + def test_a_single_profile_needs_no_default_flag(self): + self.profiles[0]["default"] = False + self.assertIn(" · default-release · ", plain(cli._machine_context())) + + def test_firefox_is_never_started(self): + (self.root / "application.ini").unlink() + with mock.patch("fxcss.core.subprocess.run", side_effect=AssertionError("ran")) as run, \ + mock.patch("fxcss.core.subprocess.Popen", side_effect=AssertionError("ran")): + cli._machine_context() + run.assert_not_called() + + def test_the_line_sits_under_the_tagline_lined_up_with_it(self): + lines = cli.landing_text().splitlines() + self.assertEqual(lines[0].index("live-reload"), 9) + self.assertEqual(len(lines[1]) - len(lines[1].lstrip()), 9) + self.assertIn("macOS", lines[1]) + + def test_anything_unreadable_drops_the_line_not_the_welcome(self): + with mock.patch("fxcss.install.discover_profiles", side_effect=PermissionError("no")): + lines = cli.landing_text().splitlines() + self.assertIn(cli.TAGLINE, lines[0]) + self.assertEqual(lines[1], "") + self.assertIn("Try or install a theme", "\n".join(lines)) + + def test_bare_fxcss_prints_it(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(cli.main([]), 0) + self.assertIn("Firefox 155.0.1", out.getvalue()) + + +class DoctorRowTests(unittest.TestCase): + def test_the_firefox_row_carries_the_symbol(self): + info = {"version": "155.0.1", "os": "Darwin", "buildID": "20260903", + "outer": [1200, 800], "dpr": 2, "legacyStylesheets": True, + "nativeContextMenus": {}} + session = mock.MagicMock() + session.__enter__.return_value.info.return_value = info + out = io.StringIO() + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch("fxcss.cli.choose_firefox", return_value="/x/firefox"), \ + mock.patch("fxcss.cli.core.Session", return_value=session), \ + mock.patch("fxcss.cli.core.discover_firefoxes", return_value=[]), \ + mock.patch.dict(style.OS_MARKS, {"macOS": "⌘"}), \ + contextlib.redirect_stdout(out): + cli.cmd_doctor(argparse.Namespace(theme=Path(tmp), firefox=None)) + self.assertIn("155.0.1 on ⌘ macOS", style._visible(out.getvalue())) + + +class BuildIdentityTests(unittest.TestCase): + def build(self, *folders, body="[App]\nName=Firefox\nVersion=155.0.1\n"): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + ini = root.joinpath(*folders, "application.ini") + ini.parent.mkdir(parents=True, exist_ok=True) + ini.write_text(body, encoding="utf-8") + binary = root / "app" / "MacOS" / "firefox" + binary.parent.mkdir(parents=True, exist_ok=True) + return binary + + def test_read_beside_the_binary(self): + self.assertEqual(core.build_identity(self.build("app", "MacOS")), ("Firefox", "155.0.1")) + + def test_read_from_a_mac_bundles_resources(self): + self.assertEqual(core.build_identity(self.build("app", "Resources")), + ("Firefox", "155.0.1")) + + def test_a_missing_file_gives_a_generic_name_and_no_version(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(core.build_identity(Path(tmp) / "firefox"), ("Firefox", None)) + + def test_a_percent_sign_is_not_an_error(self): + binary = self.build("app", "MacOS", body="[App]\nName=Firefox\nVersion=1\nX=100%\n") + self.assertEqual(core.build_identity(binary), ("Firefox", "1")) + + def test_build_version_still_asks_the_binary_when_there_is_no_file(self): + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch.object(core, "firefox_version", return_value="9.9") as asked: + self.assertEqual(support.build_version(Path(tmp) / "firefox"), "9.9") + asked.assert_called_once() + + def test_build_version_still_asks_the_binary_when_the_file_is_broken(self): + binary = self.build("app", "MacOS", body="not an ini file\n") + with mock.patch.object(core, "firefox_version", return_value="9.9"): + self.assertEqual(support.build_version(binary), "9.9") + + def test_build_version_does_not_run_a_build_with_a_file(self): + binary = self.build("app", "MacOS") + with mock.patch.object(core, "firefox_version", side_effect=AssertionError("ran")): + self.assertEqual(support.build_version(binary), "155.0.1") + + +if __name__ == "__main__": + unittest.main()