Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218"""Draw a screen's ANSI text as a PNG, so a person or a model can look at it.
TUI tests write what a view draws to $ALBEDO_SHOT_DIR/<name>.ans (see shot incli/internal/tui/shot_test.go). This turns every .ans in a directory, or thefiles named, into a .svg and a .png beside it. Needs rsvg-convert.
ALBEDO_SHOT_DIR=/tmp/shots go -C cli test ./internal/tui -run TestShotGallery python3 test/manual/tui_shot.py /tmp/shots
For a directory it also makes contact sheets per screen, sheet-<screen>-<page>.png,six states to a sheet so a model can read them (images over 2000px a side arerefused). The screen is the file name up to the first "-". Screens registertheir states with registerShots in the tests.
--blockout draws text as flat bars, the way the Flow Block wireframe font does,so a screen's layout can be judged without reading it. Box drawing, bars,arrows and separators stay as glyphs. It writes <name>.blockout.png andsheet-<screen>-blockout-<page>.png beside the plain ones."""
import htmlimport reimport subprocessimport sysimport unicodedatafrom pathlib import Path
BG, FG = "#1e1e2e", "#cdd6f4"SHEET_TILES = 6 # two columns of three: a sheet stays under a model's 2000px edge limitFONTS = ["/System/Library/Fonts/Menlo.ttc", "/System/Library/Fonts/Monaco.ttf"]BASIC = { 30: "#45475a", 31: "#f38ba8", 32: "#a6e3a1", 33: "#f9e2af", 34: "#89b4fa", 35: "#cba6f7", 36: "#94e2d5", 37: "#bac2de", 90: "#585b70", 91: "#f38ba8", 92: "#a6e3a1", 93: "#f9e2af", 94: "#89b4fa", 95: "#cba6f7", 96: "#94e2d5", 97: "#a6adc8",} # fmt: skipTOKEN = re.compile( r"\x1b\[([0-9;:]*)m|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b_.*?\x1b\\|(.)", re.S)
Style = dict[str, str | bool | None]
def xterm(n: int) -> str: if n < 8: return BASIC[30 + n] if n < 16: return BASIC[82 + n] if n < 232: n -= 16 level = lambda v: 0 if v == 0 else 55 + 40 * v # noqa: E731 return "#%02x%02x%02x" % (level(n // 36), level(n // 6 % 6), level(n % 6)) v = 8 + 10 * (n - 232) return "#%02x%02x%02x" % (v, v, v)
def fresh() -> Style: return { "fg": None, "bg": None, "bold": False, "faint": False, "under": False, "reverse": False, }
def apply(style: Style, params: list[int]) -> None: i = 0 while i < len(params): p = params[i] if p == 0: style.update(fresh()) elif p in (1, 2, 4, 7): style[{1: "bold", 2: "faint", 4: "under", 7: "reverse"}[p]] = True elif p == 22: style.update(bold=False, faint=False) elif p == 24: style["under"] = False elif p == 27: style["reverse"] = False elif p == 39: style["fg"] = None elif p == 49: style["bg"] = None elif p in (38, 48): key = "fg" if p == 38 else "bg" if params[i + 1] == 2: style[key] = "#%02x%02x%02x" % tuple(params[i + 2 : i + 5]) i += 4 elif params[i + 1] == 5: style[key] = xterm(params[i + 2]) i += 2 elif 30 <= p <= 37 or 90 <= p <= 97: style["fg"] = BASIC[p] elif 40 <= p <= 47 or 100 <= p <= 107: style["bg"] = BASIC[p - 10] i += 1
def width_of(char: str) -> int: if unicodedata.combining(char): return 0 return 2 if unicodedata.east_asian_width(char) in "WF" else 1
def is_text(char: str) -> bool: kind = unicodedata.category(char)[0] return kind in "LN" or (char.isascii() and kind in "PS")
def to_svg( text: str, cw: int = 9, ch: int = 19, pad: int = 18, size: int = 15, blockout: bool = False,) -> str: cells: list[tuple[int, int, str, Style, int]] = [] lines = text.rstrip("\n").split("\n") columns = 0 for y, line in enumerate(lines): style, x = fresh(), 0 for match in TOKEN.finditer(line): if match.group(2) is not None: w = width_of(match.group(2)) cells.append((x, y, match.group(2), dict(style), w)) x += w elif match.group(1) is not None: apply( style, [ int(p) if p else 0 for p in re.split("[;:]", match.group(1) or "0") ], ) columns = max(columns, x) out = [ f'<svg xmlns="http://www.w3.org/2000/svg" width="{pad * 2 + columns * cw}" height="{pad * 2 + len(lines) * ch}">', f'<rect width="100%" height="100%" rx="10" fill="{BG}"/>', f'<g font-family="Menlo" font-size="{size}" xml:space="preserve">', ] for x, y, char, style, w in cells: fg, bg = style["fg"] or FG, style["bg"] if style["reverse"]: fg, bg = bg or BG, fg if bg: out.append( f'<rect x="{pad + x * cw}" y="{pad + y * ch}" width="{cw * w + 0.5}" height="{ch + 0.5}" fill="{bg}"/>' ) if char == " ": continue faint = ' opacity="0.6"' if style["faint"] else "" if blockout and is_text(char): top, bottom = (0.42, 0.70) if style["bold"] else (0.45, 0.68) out.append( f'<rect x="{pad + x * cw}" y="{pad + y * ch + ch * top:.1f}" width="{cw * w + 0.3}" height="{ch * (bottom - top):.1f}" fill="{fg}"{faint}/>' ) continue extra = (' font-weight="bold"' if style["bold"] else "") + faint extra += ' text-decoration="underline"' if style["under"] else "" out.append( f'<text x="{pad + x * cw + cw * w / 2}" y="{pad + y * ch + ch * 0.75}" text-anchor="middle" fill="{fg}"{extra}>{html.escape(char)}</text>' ) out.append("</g></svg>") return "\n".join(out)
def main(args: list[str]) -> int: blockout = "--blockout" in args args = [a for a in args if a != "--blockout"] suffix = ".blockout" if blockout else "" sources = [ p for a in args for p in (sorted(Path(a).glob("*.ans")) if Path(a).is_dir() else [Path(a)]) ] if not sources: print(__doc__, file=sys.stderr) return 2 sheets: dict[tuple[Path, str], list[Path]] = {} for source in sources: svg = source.with_suffix(suffix + ".svg") png = source.with_suffix(suffix + ".png") if not png.exists() or png.stat().st_mtime < source.stat().st_mtime: drawn = to_svg(source.read_text(encoding="utf-8"), blockout=blockout) svg.write_text(drawn, encoding="utf-8") subprocess.run(["rsvg-convert", str(svg), "-o", str(png)], check=True) screen = re.split("-", source.stem, maxsplit=1)[0] + suffix.replace(".", "-") sheets.setdefault((source.parent, screen), []).append(png) for (folder, screen), pngs in sheets.items(): font = next((f for f in FONTS if Path(f).exists()), None) montage = ["magick", "montage", "-pointsize", "16", "-fill", "#cdd6f4"] montage += ["-font", font, "-label", "%t"] if font else ["-label", ""] montage += [ "-background", "#11111b", "-tile", "2x3", "-geometry", "970x>+12+12", "-depth", "8", ] for page, start in enumerate(range(0, len(pngs), SHEET_TILES), 1): sheet = folder / f"sheet-{screen}-{page}.png" subprocess.run( [*montage, *map(str, pngs[start : start + SHEET_TILES]), str(sheet)], check=True, ) print(sheet) return 0
if __name__ == "__main__": sys.exit(main(sys.argv[1:]))