utils/kuhy_credit/generator/emit.py
Krzysztof kuhy Rudnicki 96fedf6442 kuhy_credit: LaTeX stack for PDF documents
Generated latex/kuhy-credit.sty draws the M1 logo as TikZ polygons and
links it to the site; compile E2E in pytest. Version 0.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 22:27:55 +01:00

231 lines
8.4 KiB
Python

"""Render the shared credit data as source text for each stack.
Every emitter returns the full file. Long data (the SVG, the polygon points)
is wrapped into short lines so each stack's linter accepts the file as is.
"""
from __future__ import annotations
import json
import shlex
import textwrap
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from generator.svg import Logo
from generator.tokens import Palette, Tokens
MARK = "generated by kuhy_credit/generator/generate.py; DO NOT EDIT"
@dataclass(frozen=True)
class Credit:
"""Everything a stack needs: the words, the link, the art, the tokens."""
url: str
text: str
svg: str
logo: Logo
tokens: Tokens
def _num(v: float) -> str:
return f"{v:g}" if v != int(v) else f"{int(v)}.0"
def _wrap(items: list[str], indent: str, width: int = 76) -> str:
joined = ", ".join(items) + ","
return textwrap.fill(joined, width, initial_indent=indent, subsequent_indent=indent)
def _points(points: tuple[float, ...], indent: int) -> str:
return _wrap([_num(p) for p in points], " " * indent)
def _chunks(text: str, size: int = 60) -> list[str]:
return [json.dumps(text[i : i + size]) for i in range(0, len(text), size)]
def _gd_str(chunk: str) -> str:
"""GDScript literal the way gdformat writes it: single quotes around '"'."""
text = json.dumps(chunk)
if '"' in chunk and "'" not in chunk:
return "'" + text[1:-1].replace('\\"', '"') + "'"
return text
def _argb(hex_colour: str) -> str:
return f"0xFF{hex_colour.lstrip('#').upper()}"
def python(c: Credit) -> str:
"""kuhy_credit/_data.py."""
shapes = "".join(
f' (\n "{s.fill}",\n (\n{_points(s.points, 12)}\n ),\n ),\n'
for s in c.logo.shapes
)
def pal(p: Palette) -> str:
return (
f'{{"bg": "{p.bg}", "surface": "{p.surface}", "border": "{p.border}", '
f'"text": "{p.text}"}}'
)
t = c.tokens
return (
f'"""The shared credit data ({MARK})."""\n\n'
f"URL = {json.dumps(c.url)}\nTEXT = {json.dumps(c.text)}\n"
f"LOGO_SIZE = {c.logo.size}\nLOGO_FIELD = {json.dumps(c.logo.field)}\n"
f"LOGO_SHAPES: tuple[tuple[str, tuple[float, ...]], ...] = (\n{shapes})\n"
f"DARK = {pal(t.dark)}\nLIGHT = {pal(t.light)}\n"
f'FOCUS = "{t.focus}"\nRADIUS = {t.radius}\nSPACE_SM = {t.space_sm}\n'
f"SPACE_MD = {t.space_md}\nTEXT_BODY = {t.text_body}\n"
)
def web(c: Credit) -> str:
"""web/src/credit-data.js."""
svg = "\n + ".join(_chunks(c.svg))
t = c.tokens
def pal(p: Palette) -> str:
return f'{{ bg: "{p.bg}", surface: "{p.surface}", border: "{p.border}", text: "{p.text}" }}'
return (
f"// The shared credit data ({MARK}).\n"
f"export const CREDIT_URL = {json.dumps(c.url)};\n"
f"export const CREDIT_TEXT = {json.dumps(c.text)};\n"
f"export const LOGO_SVG =\n {svg};\n"
f"export const TOKENS = {{\n dark: {pal(t.dark)},\n light: {pal(t.light)},\n"
f' focus: "{t.focus}",\n radius: {t.radius},\n spaceSm: {t.space_sm},\n'
f" spaceMd: {t.space_md},\n textBody: {t.text_body},\n}};\n"
)
def flutter(c: Credit) -> str:
"""flutter/lib/src/credit_data.g.dart."""
shapes = "".join(
f" (\n {_argb(s.fill)},\n <double>[\n{_points(s.points, 6)}\n ],\n ),\n"
for s in c.logo.shapes
)
t = c.tokens
return (
f"// GENERATED CODE - DO NOT MODIFY BY HAND ({MARK}).\n"
"// ignore_for_file: public_member_api_docs\n\n"
f"const String kCreditUrl = {json.dumps(c.url)};\n"
f"const String kCreditText = {json.dumps(c.text)};\n"
f"const double kLogoSize = {c.logo.size};\n"
f"const int kLogoField = {_argb(c.logo.field)};\n"
f"const List<(int, List<double>)> kLogoShapes = [\n{shapes}];\n"
f"const int kDarkBg = {_argb(t.dark.bg)};\n"
f"const int kLightBg = {_argb(t.light.bg)};\n"
f"const int kDarkSurface = {_argb(t.dark.surface)};\n"
f"const int kDarkBorder = {_argb(t.dark.border)};\n"
f"const int kDarkText = {_argb(t.dark.text)};\n"
f"const int kLightSurface = {_argb(t.light.surface)};\n"
f"const int kLightBorder = {_argb(t.light.border)};\n"
f"const int kLightText = {_argb(t.light.text)};\n"
f"const int kFocus = {_argb(t.focus)};\n"
f"const double kRadius = {t.radius};\n"
f"const double kSpaceSm = {t.space_sm};\n"
f"const double kSpaceMd = {t.space_md};\n"
f"const double kTextBody = {t.text_body};\n"
)
def godot(c: Credit) -> str:
"""godot/addons/kuhy_credit/credit_data.gd."""
svg = "\n\t+ ".join(_gd_str(c.svg[i : i + 60]) for i in range(0, len(c.svg), 60))
t = c.tokens
def pal(p: Palette) -> str:
return (
f'{{\n\t"bg": Color("{p.bg}"),\n\t"surface": Color("{p.surface}"),'
f'\n\t"border": Color("{p.border}"),\n\t"text": Color("{p.text}"),\n}}'
)
return (
f"## The shared credit data ({MARK}).\n"
"extends RefCounted\n\n"
f"const URL := {json.dumps(c.url)}\n"
f"const TEXT := {json.dumps(c.text)}\n"
f"const LOGO_SIZE := {c.logo.size}\n"
f"const LOGO_SVG := (\n\t{svg}\n)\n"
f"const DARK := {pal(t.dark)}\n"
f"const LIGHT := {pal(t.light)}\n"
f'const FOCUS := Color("{t.focus}")\n'
f"const RADIUS := {t.radius}\nconst SPACE_SM := {t.space_sm}\n"
f"const SPACE_MD := {t.space_md}\nconst TEXT_BODY := {t.text_body}\n"
)
def terminal(c: Credit) -> str:
"""terminal/kuhy-credit.sh."""
return (
"#!/bin/bash\n"
f"# Prints the one-line kuhy credit and opens nothing ({MARK}).\n"
"set -euo pipefail\n"
f"printf '%s %s\\n' {shlex.quote(c.text)} {shlex.quote(c.url)}\n"
)
_TEX_SPECIAL = set("\\{}%#$&^_~")
def _tex_safe(value: str) -> str:
"""Refuse a value that would need TeX escaping; the macros keep it verbatim."""
bad = sorted(set(value) & _TEX_SPECIAL)
if bad:
msg = f"TeX-special characters {bad} in {value!r}: the LaTeX stack cannot carry them"
raise ValueError(msg)
return value
def latex(c: Credit) -> str:
"""latex/kuhy-credit.sty."""
names = {c.logo.field: "kuhycreditfield"}
for s in c.logo.shapes:
names.setdefault(s.fill, f"kuhycreditfill{len(names)}")
colours = "".join(
f"\\definecolor{{{name}}}{{HTML}}{{{fill.lstrip('#').upper()}}}\n"
for fill, name in names.items()
)
def poly(points: tuple[float, ...]) -> str:
pairs = [f"({_num(points[i])},{_num(points[i + 1])})" for i in range(0, len(points), 2)]
return textwrap.fill(" ".join(pairs), 76, initial_indent=" ", subsequent_indent=" ")
shapes = "".join(
f" \\fill[{names[s.fill]}] plot coordinates {{\n{poly(s.points)}\n }} -- cycle;\n"
for s in c.logo.shapes
)
n = c.logo.size
return (
f"% The kuhy credit for LaTeX ({MARK}).\n"
"% \\kuhycredit[<size>] draws the logo linked to the site (needs hyperref);\n"
"% \\kuhycreditlogo[<size>] draws it without a link. Size defaults to\n"
"% \\kuhycreditsize (12mm, about the web stack's 48px).\n"
"\\NeedsTeXFormat{LaTeX2e}\n"
"\\ProvidesPackage{kuhy-credit}[kuhy credit]\n"
"\\RequirePackage{tikz}\n"
f"{colours}"
f"\\newcommand*\\kuhycreditURL{{{_tex_safe(c.url)}}}\n"
f"\\newcommand*\\kuhycreditText{{{_tex_safe(c.text)}}}\n"
"\\newlength\\kuhycreditsize\n\\setlength\\kuhycreditsize{12mm}\n"
"\\newcommand\\kuhycreditlogo[1][\\kuhycreditsize]{%\n"
f" \\pgfmathsetmacro\\kuhycredit@unit{{(#1)/{n}}}%\n"
" \\begin{tikzpicture}[x=\\kuhycredit@unit pt,y=-\\kuhycredit@unit pt,\n"
" baseline=(current bounding box.south)]\n"
f" \\fill[kuhycreditfield] (0,0) rectangle ({n},{n});\n"
f"{shapes}"
" \\end{tikzpicture}}\n"
"\\newcommand\\kuhycredit[1][\\kuhycreditsize]{%\n"
" \\ifdefined\\href{\\hypersetup{pdfborder={0 0 0}}%\n"
" \\href{\\kuhycreditURL}{\\kuhycreditlogo[#1]}}%\n"
" \\else\\kuhycreditlogo[#1]\\fi}\n"
"\\AtBeginDocument{\\ifdefined\\href\\else\\PackageWarningNoLine{kuhy-credit}%\n"
" {hyperref is not loaded: \\string\\kuhycredit\\space draws no link}\\fi}\n"
"\\endinput\n"
)