Files
LLeMbas-Android/scripts/fetch-tokens.py
T
HomerandClaude Opus 5.5 77e1539e8f
CI / check (push) Canceled after 0s
Assistant entry points: share sheet (new or last chat), widget, shortcuts, headset button
- Share: a sheet over the sharing app shows what came in, takes an optional request, and sends
  to a new chat or the last assistant chat; files uploaded first; a new chat becomes the last.
- Home-screen widget (RemoteViews, nothing from the account): Ask, Speak, last chat.
- Launcher shortcuts published from code (the debug build's package differs): Ask, Speak, Last.
- ACTION_VOICE_COMMAND / VOICE_SEARCH_HANDS_FREE open the sheet listening; locked: unlock first.
- Quick Settings tile: STATE_INACTIVE (never greyed out), TOGGLEABLE_TILE false.
- fetch-tokens.py also writes values{,-night}/tokens.xml for what Compose cannot draw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:05:11 +00:00

172 lines
6.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""The server's colours, as the app's Compose theme.
scripts/fetch-tokens.py <server-ref> read tokens.css at that ref (a tag such as v1.7.0),
write Tokens.kt, the colour resources and tokens.lock.json
scripts/fetch-tokens.py verify: they match tokens.lock.json
The server is a git checkout, LLeMbas beside this repository by default (LEMBAS_SERVER names
another). Only the colour tokens of the two themes are read -- `moria` (declared on `:root`) and
`shire` -- and each becomes a `Palette` in Kotlin. The lock records the ref, the commit and the
SHA-256 of the generated file, as LLeMbas Desktop's `tokens.lock.json` does: the file in the tree
says which server version the look comes from, and CI refuses a copy that drifted.
What Compose cannot draw -- the home-screen widget, the shortcuts' icons -- takes the same colours
as Android resources: `values/tokens.xml` from `shire` and `values-night/tokens.xml` from `moria`,
a few of the tokens as `@color/token_<name>`, so a widget follows the phone's dark mode in the
app's own colours.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
SOURCE = "src/lembas/web/static/css/tokens.css"
OUT = ROOT / "app/src/main/java/eu/llembas/android/ui/theme/Tokens.kt"
LOCK = ROOT / "tokens.lock.json"
RES = ROOT / "app/src/main/res"
# The tokens a resource reads, and which theme each folder takes.
RES_NAMES = ("bg", "surface", "surface-raised", "border", "ink", "ink-muted", "accent", "accent-ink", "accent-soft")
RES_THEMES = {"values": "shire", "values-night": "moria"}
# The tokens the app uses, in the order they are written. A token missing from a theme is an
# error rather than a default: a palette that silently fell back would look right and be wrong.
NAMES = (
"bg", "bg-sunken", "surface", "surface-raised", "surface-hover", "surface-active",
"border", "border-strong", "ink", "ink-muted", "ink-faint", "ink-inverse",
"accent", "accent-hover", "accent-ink", "accent-soft", "selection", "leaf", "danger", "danger-soft",
"success", "success-soft", "warning", "warning-soft", "bubble-user", "code-bg", "code-border",
)
THEMES = {
"moria": r':root,\s*:root\[data-theme="moria"\]\s*\{',
"shire": r':root\[data-theme="shire"\],\s*:root\[data-base="shire"\]\s*\{',
}
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def block(css: str, opener: str) -> str:
match = re.search(opener, css)
if not match:
sys.exit(f"fetch-tokens: no block {opener!r} in {SOURCE}")
depth, start = 1, match.end()
for i in range(start, len(css)):
depth += {"{": 1, "}": -1}.get(css[i], 0)
if depth == 0:
return css[start:i]
sys.exit("fetch-tokens: unbalanced braces")
def argb(value: str) -> str:
value = value.strip()
if m := re.fullmatch(r"#([0-9a-fA-F]{6})", value):
return f"0xFF{m.group(1).upper()}"
if m := re.fullmatch(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)", value):
r, g, b = (int(m.group(i)) for i in (1, 2, 3))
a = round(float(m.group(4)) * 255)
return f"0x{a:02X}{r:02X}{g:02X}{b:02X}"
sys.exit(f"fetch-tokens: not a colour this script reads: {value!r}")
def camel(name: str) -> str:
head, *rest = name.split("-")
return head + "".join(p.capitalize() for p in rest)
def android_colour(value: str) -> str:
"""#AARRGGBB, as a resource writes it."""
return "#" + argb(value)[2:]
def theme_values(css: str, theme: str) -> dict[str, str]:
return dict(re.findall(r"--([a-z0-9-]+)\s*:\s*([^;]+);", block(css, THEMES[theme])))
def generate_res(css: str, ref: str, theme: str) -> str:
values = theme_values(css, theme)
lines = [
'<?xml version="1.0" encoding="utf-8"?>',
f"<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at {ref} ({theme}). Do not edit. -->",
"<resources>",
*[f' <color name="token_{n.replace("-", "_")}">{android_colour(values[n])}</color>' for n in RES_NAMES],
"</resources>",
"",
]
return "\n".join(lines)
def res_files() -> dict[str, Path]:
return {folder: RES / folder / "tokens.xml" for folder in RES_THEMES}
def generate(css: str, ref: str) -> str:
lines = [
"// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at "
f"{ref}. Do not edit.",
"package eu.llembas.android.ui.theme",
"",
"import androidx.compose.ui.graphics.Color",
"",
"data class Palette(",
*[f" val {camel(n)}: Color," for n in NAMES],
")",
"",
]
for theme, opener in THEMES.items():
body = block(css, opener)
values = dict(re.findall(r"--([a-z0-9-]+)\s*:\s*([^;]+);", body))
missing = [n for n in NAMES if n not in values]
if missing:
sys.exit(f"fetch-tokens: {theme} has no {', '.join(missing)}")
lines.append(f"val {theme.capitalize()} = Palette(")
lines += [f" {camel(n)} = Color({argb(values[n])}L)," for n in NAMES]
lines += [")", ""]
return "\n".join(lines)
def main() -> None:
if len(sys.argv) == 1:
lock = json.loads(LOCK.read_text())
if sha(OUT) != lock["sha256"]:
sys.exit(f"fetch-tokens: {OUT.name} does not match {LOCK.name} (server {lock['tag']})")
for folder, path in res_files().items():
if not path.exists() or sha(path) != lock.get("res", {}).get(folder):
sys.exit(f"fetch-tokens: {folder}/tokens.xml does not match {LOCK.name} (server {lock['tag']})")
print(f"fetch-tokens: {OUT.name} matches {LOCK.name} (server {lock['tag']})")
return
ref = sys.argv[1]
commit = subprocess.run(
["git", "-C", str(SERVER), "rev-parse", "--verify", f"{ref}^{{commit}}"],
capture_output=True, text=True, check=True,
).stdout.strip()
css = subprocess.run(
["git", "-C", str(SERVER), "show", f"{commit}:{SOURCE}"],
capture_output=True, text=True, check=True,
).stdout
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(generate(css, ref), encoding="utf-8")
res = {}
for folder, path in res_files().items():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(generate_res(css, ref, RES_THEMES[folder]), encoding="utf-8")
res[folder] = sha(path)
LOCK.write_text(
json.dumps({"tag": ref, "commit": commit, "sha256": sha(OUT), "res": res}, indent=2) + "\n"
)
print(f"fetch-tokens: wrote {OUT.relative_to(ROOT)} from {ref} ({commit[:12]})")
if __name__ == "__main__":
main()