diff options
| -rw-r--r-- | AGENTS.md | 11 | ||||
| -rw-r--r-- | config.toml | 5 | ||||
| -rw-r--r-- | deckit/modules/tablet.py | 3 | ||||
| -rw-r--r-- | deckit/server.py | 13 | ||||
| -rw-r--r-- | deckit/theme.py | 66 | ||||
| -rw-r--r-- | static/app.js | 3 | ||||
| -rw-r--r-- | static/deck.css | 5 | ||||
| -rw-r--r-- | tests/test_server.py | 10 | ||||
| -rw-r--r-- | tests/test_theme.py | 16 |
9 files changed, 97 insertions, 35 deletions
@@ -87,10 +87,13 @@ Keep the server dependency-free apart from that one package. covers the page with `#dimmer` and `tablet`'s `dim` action sets the backlight to `dim_brightness` over adb (auto brightness off meanwhile); the touch on the cover calls `undim`, which puts both back, as does the - module's `stop`. The cover's clock (and, with `clock_font_date`, its - date) uses `[tablet] clock_font`, a family installed on the PC that the - server finds with `fc-match` and serves at `/fonts/clock`; the font file - never enters the repo, so a personal-use font is fine. + module's `stop`. The cover's time and date fonts are keystone's Fonts + page: `family` `deckit-clock` and `deckit-date` in its `fonts.json`, each a + family installed on the PC that the server finds with `fc-match` and + serves at `/fonts/<key>`; their px sizes are its `deckit:clock` and + `deckit:date` overrides (else deck.css's 8rem and 1.6rem); theme.css + carries the rules, so a change reaches an open page. The font file never + enters the repo, so a personal-use font is fine. Before a suspend, poweroff or reboot `deckit/sleep.py` (an elogind delay inhibitor plus `dbus-monitor` on PrepareForSleep/PrepareForShutdown) marks answers with `X-Deckit-Sleep: asleep|shutting down` for 2s, and `app.js` diff --git a/config.toml b/config.toml index d268031..cbaf6ee 100644 --- a/config.toml +++ b/config.toml @@ -100,11 +100,6 @@ peek = 8 # dim_brightness (0-255); a touch puts it back. 0 turns dimming off. dim_after = 120 dim_brightness = 8 -# A font family installed on the PC (fc-list) for the clock on the dim -# cover, served to the tablet at /fonts/clock; empty keeps the page font. -# clock_font_date sets the date in it too. -clock_font = "" -clock_font_date = true [icons] # Launcher icons follow the icon theme Keystone sets (gsettings diff --git a/deckit/modules/tablet.py b/deckit/modules/tablet.py index 08f12fa..71f7a95 100644 --- a/deckit/modules/tablet.py +++ b/deckit/modules/tablet.py @@ -112,7 +112,6 @@ def make(cfg: dict) -> Module: tcfg = cfg.get("tablet", {}) dim_after = max(0, int(tcfg.get("dim_after", 120))) level = min(255, max(0, int(tcfg.get("dim_brightness", 8)))) - clock = {"clock_font": bool(tcfg.get("clock_font")), "clock_font_date": bool(tcfg.get("clock_font_date", True))} saved = {} # mode and brightness from before a dim; empty while bright try: saved["mode"], saved["level"] = DIM_FILE.read_text().split() @@ -155,5 +154,5 @@ def make(cfg: dict) -> Module: pass return Module(name="tablet", title="Tablet", - state=lambda: {**state(), "dim_after": dim_after, **clock}, + state=lambda: {**state(), "dim_after": dim_after}, actions={"dim": dim, "undim": undim}, stop=stop) diff --git a/deckit/server.py b/deckit/server.py index 2ced8dd..bd46446 100644 --- a/deckit/server.py +++ b/deckit/server.py @@ -142,10 +142,11 @@ def nerd_font(): return _font["p"] -def clock_font(): - """[tablet] clock_font's file, for the dim cover's clock; None when unset - or not installed (fc-match falls back to any font, so the family must match).""" - family = CFG.get("tablet", {}).get("clock_font", "") +def clock_font(key): + """The file of a clock font keystone's fonts.json names (theme.CLOCK_FONTS); + None when unset or not installed (fc-match falls back to any font, so the + family must match).""" + family = theme.families().get(key, "") if not family: return None out = _run(["fc-match", "-f", "%{family}\n%{file}", family]) @@ -219,8 +220,8 @@ class Handler(BaseHTTPRequestHandler): if path == "/fonts/nerd.ttf": f = nerd_font() return self._send(200, f.read_bytes(), "font/ttf", cache=True) if f else self._send(404) - if path == "/fonts/clock": - f = clock_font() + if path.startswith("/fonts/") and path[len("/fonts/"):] in theme.CLOCK_FONTS: + f = clock_font(path[len("/fonts/"):]) return self._send(200, f.read_bytes(), mimetypes.guess_type(f)[0] or "font/ttf") if f else self._send(404) if path.startswith("/api/"): if not self._authed(): diff --git a/deckit/theme.py b/deckit/theme.py index 142a79f..343e084 100644 --- a/deckit/theme.py +++ b/deckit/theme.py @@ -24,6 +24,7 @@ than restating the colours, so a scheme or wallpaper change reaches the tablet. import json import re from pathlib import Path +from urllib.parse import quote PALETTE_LINE = re.compile(r"^\s*([a-z0-9]+)\s*:\s*(#[0-9a-fA-F]{6,8});", re.M) ACCENT = re.compile(r"accent:\s*(#[0-9a-fA-F]{6,8})") @@ -32,7 +33,8 @@ BORDER = re.compile(r"rgb\(\s*([0-9a-fA-F]{6})\s*\)") PALETTE_PATH = Path.home() / ".config" / "rofi" / "udt" / "palette.rasi" ACCENT_PATH = Path.home() / ".cache" / "udt" / "udt-accent.rasi" BORDER_PATH = Path.home() / ".cache" / "udt" / "udt-border.lua" -# Keystone's fonts page owns text sizes: deck-it's own override, else the base. +# Keystone's fonts page owns text sizes (deck-it's own override, else the base) +# and the clock's font families. FONTS_PATH = Path.home() / ".config" / "keystone" / "fonts.json" FONT_SIZE = 14 # px, the size deck.css was designed at @@ -74,8 +76,59 @@ def parse_font_size(text: str) -> int | None: return None +# fonts.json's "family" keys for the dim cover's clock, and the selector each sets. +CLOCK_FONTS = {"deckit-clock": ".dim-time", "deckit-date": ".dim-date"} +# Its "override" keys for the clock's px sizes; unset keeps deck.css's rem. +CLOCK_SIZES = {"deckit:clock": ".dim-time", "deckit:date": ".dim-date"} + + +def parse_clock_sizes(text: str) -> dict[str, int]: + """The clock's own px sizes from keystone's fonts.json, by selector, range-checked.""" + try: + override = json.loads(text).get("override") or {} + except (ValueError, AttributeError): + return {} + if not isinstance(override, dict): + return {} + return {sel: round(px) for key, sel in CLOCK_SIZES.items() + if isinstance(px := override.get(key), (int, float)) and not isinstance(px, bool) and 8 <= px <= 400} + + +def parse_families(text: str) -> dict[str, str]: + """The clock font families from keystone's fonts.json, by key; empty ones left out.""" + try: + family = json.loads(text).get("family") or {} + except (ValueError, AttributeError): + return {} + if not isinstance(family, dict): + return {} + return {k: v.strip() for k, v in family.items() + if k in CLOCK_FONTS and isinstance(v, str) and v.strip()} + + +def families() -> dict[str, str]: + try: + return parse_families(FONTS_PATH.read_text()) + except OSError: + return {} + + +def font_rules(fams: dict[str, str], sizes: dict[str, int] | None = None) -> str: + """@font-face and selector rules for each set clock font. The family is in + the URL only, quoted, so a change reloads the file and no name reaches the CSS.""" + out = [] + for key, sel in CLOCK_FONTS.items(): + if key in fams: + out.append(f'@font-face {{ font-family: "{key}"; src: url("/fonts/{key}?f={quote(fams[key])}"); }}') + out.append(f'#dimmer {sel} {{ font-family: "{key}", "Inconsolata Nerd Font Mono", ' + 'ui-monospace, monospace; font-weight: normal; }') + out += [f"#dimmer {sel} {{ font-size: {px}px; }}" for sel, px in (sizes or {}).items()] + return "".join(line + "\n" for line in out) + + def css(colors: dict, accent: str | None, border: list[str] | None = None, - font_size: int | None = None) -> str: + font_size: int | None = None, fams: dict[str, str] | None = None, + clock_sizes: dict[str, int] | None = None) -> str: lines = [":root {"] lines.append(f" --udt-font-size: {font_size or FONT_SIZE}px;") lines += [f" --udt-{name}: {value};" for name, value in colors.items()] @@ -85,7 +138,7 @@ def css(colors: dict, accent: str | None, border: list[str] | None = None, for index, value in enumerate(stops[:3], 1): lines.append(f" --udt-border-{index}: {value};") lines.append("}") - return "\n".join(lines) + "\n" + return "\n".join(lines) + "\n" + font_rules(fams or {}, clock_sizes) def load() -> str: @@ -105,7 +158,8 @@ def load() -> str: except OSError: border = None try: - font_size = parse_font_size(FONTS_PATH.read_text()) + fonts = FONTS_PATH.read_text() except OSError: - font_size = None - return css(colors, accent, border, font_size) + fonts = "" + return css(colors, accent, border, parse_font_size(fonts), parse_families(fonts), + parse_clock_sizes(fonts)) diff --git a/static/app.js b/static/app.js index 1296805..0466372 100644 --- a/static/app.js +++ b/static/app.js @@ -295,9 +295,6 @@ document.addEventListener("pointerdown", touched, true); // A fresh page is not dimmed, so a dim left by an earlier server goes too. fetch("/api/tablet").then((r) => r.json()).then((t) => { dimAfter = t.dim_after ?? 0; - // [tablet] clock_font, served at /fonts/clock (deck.css). - dimmer.classList.toggle("font-time", !!t.clock_font); - dimmer.classList.toggle("font-date", !!t.clock_font && !!t.clock_font_date); tablet("undim"); touched(); }).catch(() => {}); diff --git a/static/deck.css b/static/deck.css index fd0b813..b6da4c6 100644 --- a/static/deck.css +++ b/static/deck.css @@ -611,10 +611,7 @@ select { #dimmer[hidden] { display: none; } .dim-time { font-size: 8rem; font-weight: 300; line-height: 1; color: var(--udt-text); font-variant-numeric: tabular-nums; } .dim-date { font-size: 1.6rem; color: var(--udt-subtext0); } -/* [tablet] clock_font; a missing font falls back to the page font. */ -@font-face { font-family: "deckit-clock"; src: url("/fonts/clock"); } -#dimmer.font-time .dim-time { font-family: "deckit-clock", "Inconsolata Nerd Font Mono", ui-monospace, monospace; font-weight: normal; } -#dimmer.font-date .dim-date { font-family: "deckit-clock", "Inconsolata Nerd Font Mono", ui-monospace, monospace; letter-spacing: .08em; } +/* The clock's fonts come from keystone's fonts.json, as rules in theme.css. */ /* The PC asleep: over everything, and the wake lock is dropped (app.js). */ #asleep { diff --git a/tests/test_server.py b/tests/test_server.py index 8f82e9f..4d734b4 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -143,14 +143,14 @@ class Server(unittest.TestCase): from pathlib import Path f = Path(tempfile.mkdtemp()) / "Graffiti.ttf" f.write_bytes(b"\x00\x01\x00\x00clock") - with mock.patch.dict(srv.CFG, {"tablet": {"clock_font": "a Graffiti"}}): + with mock.patch.object(srv.theme, "families", return_value={"deckit-date": "a Graffiti"}): with mock.patch.object(srv, "_run", return_value=f"a Graffiti\n{f}"): - self.assertEqual(self.req("GET", "/fonts/clock", HOST)[0:2], (200, b"\x00\x01\x00\x00clock")) + self.assertEqual(self.req("GET", "/fonts/deckit-date?f=a%20Graffiti", HOST)[0:2], + (200, b"\x00\x01\x00\x00clock")) + self.assertEqual(self.req("GET", "/fonts/deckit-clock", HOST)[0], 404) # unset # fc-match's fallback for a font that is not installed with mock.patch.object(srv, "_run", return_value="DejaVu Sans\n/usr/share/fonts/DejaVuSans.ttf"): - self.assertEqual(self.req("GET", "/fonts/clock", HOST)[0], 404) - with mock.patch.dict(srv.CFG, {"tablet": {}}): - self.assertEqual(self.req("GET", "/fonts/clock", HOST)[0], 404) + self.assertEqual(self.req("GET", "/fonts/deckit-date", HOST)[0], 404) def test_assets_and_api(self): self.assertEqual(self.req("GET", "/", HOST)[0], 200) diff --git a/tests/test_theme.py b/tests/test_theme.py index f14b0f1..1c79370 100644 --- a/tests/test_theme.py +++ b/tests/test_theme.py @@ -61,6 +61,22 @@ class Theme(unittest.TestCase): for bad in ('{"base": 99}', '{"base": "16"}', "not json", "[]"): self.assertIsNone(theme.parse_font_size(bad)) + def test_clock_fonts_from_fonts_json(self): + fams = theme.parse_families('{"base": 16, "family": {"deckit-date": " a Tag ", "deckit-clock": "", "qt": "x"}}') + self.assertEqual(fams, {"deckit-date": "a Tag"}) + for bad in ("", "nope", '{"family": "x"}', "[]"): + self.assertEqual(theme.parse_families(bad), {}) + out = theme.css({}, None, fams=fams) + self.assertIn('src: url("/fonts/deckit-date?f=a%20Tag")', out) + self.assertIn("#dimmer .dim-date", out) + self.assertNotIn("dim-time", out) + + def test_clock_sizes_from_fonts_json(self): + sizes = theme.parse_clock_sizes('{"override": {"deckit:clock": 180.4, "deckit:date": 2, "deckit": 18}}') + self.assertEqual(sizes, {".dim-time": 180}) # 2px is out of range + self.assertEqual(theme.parse_clock_sizes("nope"), {}) + self.assertIn("#dimmer .dim-time { font-size: 180px; }", theme.css({}, None, clock_sizes=sizes)) + def test_css_exposes_font_size(self): self.assertIn("--udt-font-size: 17px", theme.css({}, None, font_size=17)) self.assertIn(f"--udt-font-size: {theme.FONT_SIZE}px", theme.css({}, None)) |
