#!/usr/bin/env python3 """ZimiGames' Red theme for the colours a game writes into its rules (not its tokens). Red is deep red on black (games.css, :root.gs.night-red). A game's tokens (custom properties) get their Red values from games.css and from a block each stylesheet carries; this script covers the rest: every declaration in a stylesheet that holds a colour literal (hex, rgb, rgba) gets a twin under :root.gs.night-red with each colour mapped by its luminance onto black-to-red (the shell's own red ramp: white is full red, black stays black). The twins are appended to the stylesheet between two marker lines, in source order, so what a later rule overrode it still overrides. Rules that exist only for the light scheme are skipped; rules inside a prefers-color-scheme media query are unwrapped, because Red is dark. python3 scripts/games_red.py rewrite the blocks python3 scripts/games_red.py --check exit 1 if a block is stale (tests/test_games_red_generated.py runs this) """ import os import re import sys GAMES = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "zimi", "builtin", "games") BEGIN = "/* Red, generated by scripts/games_red.py from the rules above: do not edit. */" END = "/* end Red */" RED = ":root.gs.night-red" HEX = re.compile(r"#([0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b") RGB = re.compile(r"rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)") SKIP_AT = ("@keyframes", "@-webkit-keyframes", "@font-face", "@page", "@property", "@import", "@charset") def red(r, g, b, a=None): t = max(0.0, min(1.0, (0.299 * r + 0.587 * g + 0.114 * b) / 255)) r, g, b = round(255 * t), round(32 * t), round(16 * t) return "rgba(%d, %d, %d, %s)" % (r, g, b, a) if a is not None else "#%02x%02x%02x" % (r, g, b) def convert(value): def h(m): s = m.group(1) if len(s) == 3: s = "".join(c * 2 for c in s) a = round(int(s[6:8], 16) / 255, 2) if len(s) == 8 else None return red(int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16), a) def f(m): return red(int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4)) return RGB.sub(f, HEX.sub(h, value)) def has_colour(value): return bool(HEX.search(value) or RGB.search(value)) def blocks(text): """Top-level (prelude, body) pairs of a stylesheet; braces inside strings and parentheses do not count.""" out, i, n, start = [], 0, len(text), 0 while i < n: c = text[i] if c in "\"'": j = i + 1 while j < n and text[j] != c: j += 2 if text[j] == "\\" else 1 i = j + 1 elif c == "(": depth = 1 i += 1 while i < n and depth: if text[i] in "\"'": q = text[i] i += 1 while i < n and text[i] != q: i += 2 if text[i] == "\\" else 1 elif text[i] == "(": depth += 1 elif text[i] == ")": depth -= 1 i += 1 elif c == ";": start = i + 1 i += 1 elif c == "{": depth, j = 1, i + 1 while j < n and depth: if text[j] in "\"'": q = text[j] j += 1 while j < n and text[j] != q: j += 2 if text[j] == "\\" else 1 elif text[j] == "(": k = 1 j += 1 while j < n and k: k += (text[j] == "(") - (text[j] == ")") j += 1 continue elif text[j] == "{": depth += 1 elif text[j] == "}": depth -= 1 j += 1 out.append((text[start:i].strip(), text[i + 1 : j - 1])) i = start = j else: i += 1 return out def split_top(s, sep): parts, depth, cur, q = [], 0, "", None for ch in s: if q: cur += ch if ch == q: q = None elif ch in "\"'": q = ch cur += ch elif ch == "(": depth += 1 cur += ch elif ch == ")": depth -= 1 cur += ch elif ch == sep and depth == 0: parts.append(cur) cur = "" else: cur += ch if cur.strip(): parts.append(cur) return parts def red_selector(sel): sel = sel.strip() if sel.startswith(RED) or '[data-theme="light"]' in sel or ":not([data-theme=" in sel and "light" in sel: return None m = re.match(r"(:root|html)(?![\w-])", sel) if m: rest = sel[m.end() :] rest = re.sub(r'^\[data-theme="dark"\]', "", rest) return RED + rest return RED + " " + sel def rule_twin(prelude, body): sels = [red_selector(s) for s in split_top(prelude, ",")] sels = [s for s in sels if s] if not sels: return "" decls = [] for d in split_top(body, ";"): if ":" not in d: continue prop, value = d.split(":", 1) prop = prop.strip() if not has_colour(value) or (prop.startswith("--") and RED in sels and len(sels) == 1 and sels[0] == RED): continue # the page's own tokens (:root) have their Red values by hand in games.css and a block in each file decls.append("%s: %s;" % (prop, convert(value.strip()))) return "%s { %s }" % (", ".join(sels), " ".join(decls)) if decls else "" def twins(text, dark_media=False): out = [] for prelude, body in blocks(text): if prelude.startswith("@"): if prelude.startswith(SKIP_AT): continue inner = twins(body, dark_media="prefers-color-scheme: dark" in prelude) if not inner: continue if "prefers-color-scheme" in prelude: if "dark" in prelude: out.extend(inner) # Red is dark: the dark scheme's rules, unwrapped else: out.append("%s {\n%s\n}" % (prelude, "\n".join(" " + x for x in inner))) else: t = rule_twin(prelude, body) if t: out.append(t) return out def split_generated(text): i = text.find(BEGIN) return (text if i < 0 else text[:i]).rstrip("\n") + "\n" def generated(path): with open(path, encoding="utf-8") as f: source = split_generated(f.read()) clean = re.sub(r"/\*.*?\*/", "", source, flags=re.S) rules = twins(clean) return source + ("\n%s\n%s\n%s\n" % (BEGIN, "\n".join(rules), END) if rules else "") def main(argv): stale = [] for fn in sorted(os.listdir(GAMES)): if not fn.endswith(".css"): continue path = os.path.join(GAMES, fn) want = generated(path) with open(path, encoding="utf-8") as f: have = f.read() if want != have: stale.append(fn) if "--check" not in argv: with open(path, "w", encoding="utf-8") as f: f.write(want) if stale: print(("stale: " if "--check" in argv else "rewrote: ") + " ".join(stale)) return 1 if stale and "--check" in argv else 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))