Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

5.0 KB
Raw Blame
#!/usr/bin/env python3
"""Regenerate `src/terminal_themes.rs` from a terminal's bundled theme files.

A terminal ships ~460 theme config files: a 16-colour palette plus background/foreground.
This script reads them from a directory and writes them into the TUI as a static Rust
array, so `hn theme` can preview every one without needing the source terminal installed.

Usage:
    python3 tui/scripts/gen_terminal_themes.py [THEMES_DIR]

The themes directory defaults to Ghostty's on macOS (the 463 themes hn ships with).
On other platforms pass the path to any directory of `theme`-style config files.
"""

import os
import re
import sys

DEFAULTS = [
    "/Applications/Ghostty.app/Contents/Resources/ghostty/themes",
    "/usr/share/ghostty/themes",
]


def hex_to_rgb(h: str) -> tuple[int, int, int]:
    h = h.lstrip("#")
    return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))


def esc(s: str) -> str:
    return s.replace("\\", "\\\\").replace('"', '\\"')


def read_theme(path: str) -> tuple[str, str, str, dict[int, str]]:
    """Return (name, background, foreground, palette)."""
    name = os.path.basename(path)
    bg = fg = None
    pal: dict[int, str] = {}
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            m = re.match(r"^background\s*=\s*(\S+)$", line)
            if m:
                bg = m.group(1)
                continue
            m = re.match(r"^foreground\s*=\s*(\S+)$", line)
            if m:
                fg = m.group(1)
                continue
            m = re.match(r"^palette\s*=\s*(\d+)\s*=\s*(\S+)$", line)
            if m:
                pal[int(m.group(1))] = m.group(2)
    return name, bg, fg, pal


def main() -> int:
    theme_dir = None
    for arg in sys.argv[1:]:
        if os.path.isdir(arg):
            theme_dir = arg
            break
    if theme_dir is None:
        for d in DEFAULTS:
            if os.path.isdir(d):
                theme_dir = d
                break
    if theme_dir is None:
        print("error: could not find a themes directory", file=sys.stderr)
        return 1

    themes = []
    for fn in sorted(os.listdir(theme_dir)):
        path = os.path.join(theme_dir, fn)
        if not os.path.isfile(path):
            continue
        name, bg, fg, pal = read_theme(path)
        if bg is None or fg is None:
            continue
        themes.append((name, bg, fg, pal))

    lines = []
    lines.append("//! hn's bundled terminal colour themes. Each theme is a terminal's 16-colour")
    lines.append("//! palette plus its background and foreground, used by the `hn theme` picker.")
    lines.append("//!")
    lines.append("//! Generated by scripts/gen_terminal_themes.py — do not hand-edit.")
    lines.append("")
    lines.append("/// One bundled terminal theme.")
    lines.append("#[derive(Clone, Copy, Debug)]")
    lines.append("pub struct TerminalTheme {")
    lines.append("    pub name: &'static str,")
    lines.append("    pub background: [u8; 3],")
    lines.append("    pub foreground: [u8; 3],")
    lines.append("    /// ANSI 0-15, in palette order.")
    lines.append("    pub palette: [[u8; 3]; 16],")
    lines.append("}")
    lines.append("")
    lines.append("/// Every bundled theme, sorted by name.")
    lines.append("pub static TERMINAL_THEMES: &[TerminalTheme] = &[")
    for name, bg, fg, pal in themes:
        bgc = hex_to_rgb(bg)
        fgc = hex_to_rgb(fg)
        palc = [hex_to_rgb(pal.get(i, "#000000")) for i in range(16)]
        lines.append("    TerminalTheme {")
        lines.append(f'        name: "{esc(name)}",')
        lines.append(f"        background: [{bgc[0]}, {bgc[1]}, {bgc[2]}],")
        lines.append(f"        foreground: [{fgc[0]}, {fgc[1]}, {fgc[2]}],")
        lines.append("        palette: [")
        for p in palc:
            lines.append(f"            [{p[0]}, {p[1]}, {p[2]}],")
        lines.append("        ],")
        lines.append("    },")
    lines.append("];")
    lines.append("")
    lines.append("#[cfg(test)]")
    lines.append("mod tests {")
    lines.append("    use super::*;")
    lines.append("    #[test]")
    lines.append("    fn terminal_themes_are_parseable_and_nonempty() {")
    lines.append("        assert!(TERMINAL_THEMES.len() > 400);")
    lines.append("        for t in TERMINAL_THEMES {")
    lines.append("            assert!(!t.name.is_empty());")
    lines.append("        }")
    lines.append("    }")
    lines.append("    #[test]")
    lines.append("    fn palette_has_16_entries() {")
    lines.append("        for t in TERMINAL_THEMES {")
    lines.append("            assert_eq!(t.palette.len(), 16);")
    lines.append("        }")
    lines.append("    }")
    lines.append("}")
    lines.append("")

    here = os.path.dirname(os.path.abspath(__file__))
    out = os.path.join(here, "..", "src", "terminal_themes.rs")
    with open(out, "w", encoding="utf-8") as f:
        f.write("\n".join(lines))

    print(f"wrote {len(themes)} themes to {os.path.normpath(out)}")
    return 0


if __name__ == "__main__":
    sys.exit(main())