Files
ghosttyconf/tools/termsvg/main.go
T

649 lines
17 KiB
Go
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Command termsvg renders a terminal screen captured with
// "tmux capture-pane -e -p" as an SVG image in a window frame. Colors come
// from a Ghostty theme file. It is used to make the screenshots in docs/.
//
// termsvg -theme "Catppuccin Mocha" -title ghosttyconf -o out.svg < screen.ans
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/charmbracelet/x/ansi"
)
// Cell metrics in SVG units.
const (
cellW = 8.0
cellH = 17.0
fontSize = 13.4
baseline = 12.9
padding = 14.0
titleH = 34.0
margin = 18.0
)
const fontFamily = `ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, Consolas, 'DejaVu Sans Mono', monospace`
type color struct {
set bool
r, g, b uint8
}
func (c color) hex() string { return fmt.Sprintf("#%02x%02x%02x", c.r, c.g, c.b) }
func mix(a, b color, t float64) color {
f := func(x, y uint8) uint8 { return uint8(float64(x)*(1-t) + float64(y)*t + 0.5) }
return color{true, f(a.r, b.r), f(a.g, b.g), f(a.b, b.b)}
}
type theme struct {
fg, bg color
palette [256]color
}
// colorRef is a cell color before the theme is applied: -1 is the default,
// 0..255 a palette index, and rgb a direct color.
type colorRef struct {
index int
rgb color
}
var defaultColor = colorRef{index: -1}
type style struct {
fg, bg colorRef
bold, faint, italic, under, strike, rev bool
}
type cell struct {
r rune
st style
wide bool // first half of a double-width character
cont bool // second half of a double-width character
blank bool
}
func main() {
themeName := flag.String("theme", "Catppuccin Mocha", "Ghostty theme name or path to a theme file")
title := flag.String("title", "", "window title")
out := flag.String("o", "", "output file (default: stdout)")
cols := flag.Int("cols", 0, "screen width in cells (default: widest line)")
flag.Parse()
th, err := loadTheme(*themeName)
if err != nil {
fatal(err)
}
var in io.Reader = os.Stdin
if flag.NArg() == 1 {
f, err := os.Open(flag.Arg(0))
if err != nil {
fatal(err)
}
defer f.Close()
in = f
}
data, err := io.ReadAll(in)
if err != nil {
fatal(err)
}
rows := parse(string(data))
for len(rows) > 0 && blankRow(rows[len(rows)-1]) {
rows = rows[:len(rows)-1]
}
w := *cols
for _, r := range rows {
w = max(w, len(r))
}
svg := render(rows, w, th, *title)
if *out == "" {
os.Stdout.WriteString(svg)
return
}
if err := os.WriteFile(*out, []byte(svg), 0o644); err != nil {
fatal(err)
}
}
func fatal(err error) {
fmt.Fprintln(os.Stderr, "termsvg:", err)
os.Exit(1)
}
func blankRow(r []cell) bool {
for _, c := range r {
if !c.blank || c.st.bg != defaultColor {
return false
}
}
return true
}
// loadTheme reads a Ghostty theme (palette, background, foreground) and fills
// the rest of the 256 colors like xterm.
func loadTheme(name string) (*theme, error) {
path := name
if !strings.ContainsRune(name, '/') {
for _, dir := range []string{
"/Applications/Ghostty.app/Contents/Resources/ghostty/themes",
"/usr/share/ghostty/themes",
"/usr/local/share/ghostty/themes",
} {
if p := filepath.Join(dir, name); fileExists(p) {
path = p
break
}
}
}
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("theme %q: %w", name, err)
}
defer f.Close()
th := &theme{}
xterm(&th.palette)
sc := bufio.NewScanner(f)
for sc.Scan() {
key, val, ok := strings.Cut(sc.Text(), "=")
if !ok {
continue
}
key, val = strings.TrimSpace(key), strings.TrimSpace(val)
switch key {
case "background":
th.bg = parseHex(val)
case "foreground":
th.fg = parseHex(val)
case "palette":
i, hex, ok := strings.Cut(val, "=")
if n, err := strconv.Atoi(strings.TrimSpace(i)); ok && err == nil && n >= 0 && n < 256 {
th.palette[n] = parseHex(strings.TrimSpace(hex))
}
}
}
if !th.bg.set {
th.bg = th.palette[0]
}
if !th.fg.set {
th.fg = th.palette[7]
}
return th, sc.Err()
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && !st.IsDir()
}
func parseHex(s string) color {
s = strings.TrimPrefix(s, "#")
if len(s) != 6 {
return color{}
}
v, err := strconv.ParseUint(s, 16, 32)
if err != nil {
return color{}
}
return color{true, uint8(v >> 16), uint8(v >> 8), uint8(v)}
}
func xterm(p *[256]color) {
base := []string{"000000", "cd0000", "00cd00", "cdcd00", "0000ee", "cd00cd", "00cdcd", "e5e5e5",
"7f7f7f", "ff0000", "00ff00", "ffff00", "5c5cff", "ff00ff", "00ffff", "ffffff"}
for i, h := range base {
p[i] = parseHex(h)
}
steps := []uint8{0, 95, 135, 175, 215, 255}
for i := 0; i < 216; i++ {
p[16+i] = color{true, steps[i/36], steps[i/6%6], steps[i%6]}
}
for i := 0; i < 24; i++ {
v := uint8(8 + 10*i)
p[232+i] = color{true, v, v, v}
}
}
// parse turns the captured text into rows of cells.
func parse(s string) [][]cell {
// tmux only writes attribute changes, so the style carries over from one
// line to the next.
var rows [][]cell
st := style{fg: defaultColor, bg: defaultColor}
for _, line := range strings.Split(strings.TrimRight(s, "\n"), "\n") {
var row []cell
for i := 0; i < len(line); {
if line[i] == 0x1b && i+1 < len(line) {
switch line[i+1] {
case '[':
j := i + 2
for j < len(line) && (line[j] < 0x40 || line[j] > 0x7e) {
j++
}
if j < len(line) && line[j] == 'm' {
sgr(&st, line[i+2:j])
}
i = j + 1
continue
case ']': // OSC, e.g. hyperlinks: skip up to BEL or ST
j := i + 2
for j < len(line) && line[j] != 0x07 && !(line[j] == 0x1b && j+1 < len(line) && line[j+1] == '\\') {
j++
}
if j < len(line) && line[j] == 0x1b {
j++
}
i = j + 1
continue
}
}
r, size := decodeRune(line[i:])
i += size
if r == '\t' {
for len(row)%8 != 0 || r == '\t' {
row = append(row, cell{r: ' ', st: st, blank: true})
r = 0
}
continue
}
if r < 0x20 {
continue
}
w := ansi.StringWidth(string(r))
if w == 0 {
continue
}
row = append(row, cell{r: r, st: st, wide: w == 2, blank: r == ' '})
if w == 2 {
row = append(row, cell{st: st, cont: true})
}
}
rows = append(rows, row)
}
return rows
}
func decodeRune(s string) (rune, int) {
for _, r := range s {
return r, len(string(r))
}
return 0, 1
}
func sgr(st *style, params string) {
if params == "" {
*st = style{fg: defaultColor, bg: defaultColor}
return
}
ps := strings.FieldsFunc(params, func(r rune) bool { return r == ';' || r == ':' })
num := func(i int) int {
if i >= len(ps) {
return 0
}
n, _ := strconv.Atoi(ps[i])
return n
}
for i := 0; i < len(ps); i++ {
switch n := num(i); {
case n == 0:
*st = style{fg: defaultColor, bg: defaultColor}
case n == 1:
st.bold = true
case n == 2:
st.faint = true
case n == 3:
st.italic = true
case n == 4:
st.under = true
case n == 7:
st.rev = true
case n == 9:
st.strike = true
case n == 22:
st.bold, st.faint = false, false
case n == 23:
st.italic = false
case n == 24:
st.under = false
case n == 27:
st.rev = false
case n == 29:
st.strike = false
case n >= 30 && n <= 37:
st.fg = colorRef{index: n - 30}
case n >= 40 && n <= 47:
st.bg = colorRef{index: n - 40}
case n >= 90 && n <= 97:
st.fg = colorRef{index: n - 90 + 8}
case n >= 100 && n <= 107:
st.bg = colorRef{index: n - 100 + 8}
case n == 39:
st.fg = defaultColor
case n == 49:
st.bg = defaultColor
case n == 38 || n == 48:
var c colorRef
switch num(i + 1) {
case 5:
c = colorRef{index: num(i+2) & 0xff}
i += 2
case 2:
c = colorRef{index: 256, rgb: color{true, uint8(num(i + 2)), uint8(num(i + 3)), uint8(num(i + 4))}}
i += 4
default:
continue
}
if n == 38 {
st.fg = c
} else {
st.bg = c
}
}
}
}
func (th *theme) resolve(c colorRef, def color) color {
switch {
case c.index < 0:
return def
case c.index < 256:
return th.palette[c.index]
default:
return c.rgb
}
}
// colors returns the effective foreground and background of a cell and
// whether the background differs from the screen's.
func (th *theme) colors(st style) (fg, bg color, ownBg bool) {
fg = th.resolve(st.fg, th.fg)
bg = th.resolve(st.bg, th.bg)
ownBg = st.bg != defaultColor
if st.rev {
fg, bg, ownBg = bg, fg, true
}
if st.faint {
fg = mix(fg, bg, 0.45)
}
return fg, bg, ownBg
}
// Box drawing characters drawn as lines so that borders connect.
type arms struct{ l, r, u, d, round, heavy bool }
var boxChars = map[rune]arms{
'─': {l: true, r: true}, '━': {l: true, r: true, heavy: true},
'│': {u: true, d: true}, '┃': {u: true, d: true, heavy: true},
'╭': {r: true, d: true, round: true}, '╮': {l: true, d: true, round: true},
'╰': {r: true, u: true, round: true}, '╯': {l: true, u: true, round: true},
'┌': {r: true, d: true}, '┐': {l: true, d: true},
'└': {r: true, u: true}, '┘': {l: true, u: true},
'├': {u: true, d: true, r: true}, '┤': {u: true, d: true, l: true},
'┬': {l: true, r: true, d: true}, '┴': {l: true, r: true, u: true},
'┼': {l: true, r: true, u: true, d: true},
}
// Block elements drawn as rectangles: x, y, w, h as fractions of the cell.
var blockChars = map[rune][4]float64{
'█': {0, 0, 1, 1}, '▀': {0, 0, 1, 0.5}, '▄': {0, 0.5, 1, 0.5},
'▌': {0, 0, 0.5, 1}, '▐': {0.5, 0, 0.5, 1},
}
func render(rows [][]cell, cols int, th *theme, title string) string {
termW := float64(cols)*cellW + 2*padding
termH := float64(len(rows))*cellH + 2*padding
winW, winH := termW, termH+titleH
totalW, totalH := winW+2*margin, winH+2*margin
var b strings.Builder
fmt.Fprintf(&b, `<svg xmlns="http://www.w3.org/2000/svg" width="%s" height="%s" viewBox="0 0 %s %s">`+"\n",
f(totalW), f(totalH), f(totalW), f(totalH))
b.WriteString(`<defs><filter id="shadow" x="-10%" y="-10%" width="120%" height="130%">` +
`<feDropShadow dx="0" dy="6" stdDeviation="7" flood-color="#000" flood-opacity="0.35"/></filter>` +
`<clipPath id="win"><rect x="0" y="0" width="` + f(winW) + `" height="` + f(winH) + `" rx="10"/></clipPath></defs>` + "\n")
fmt.Fprintf(&b, `<g transform="translate(%s %s)">`+"\n", f(margin), f(margin))
// Window frame and title bar, slightly lighter than the background.
bar := mix(th.bg, th.fg, 0.08)
fmt.Fprintf(&b, `<rect width="%s" height="%s" rx="10" fill="%s" filter="url(#shadow)"/>`+"\n", f(winW), f(winH), th.bg.hex())
fmt.Fprintf(&b, `<g clip-path="url(#win)"><rect width="%s" height="%s" fill="%s"/>`, f(winW), f(titleH), bar.hex())
fmt.Fprintf(&b, `<rect y="%s" width="%s" height="1" fill="%s"/></g>`+"\n", f(titleH-1), f(winW), mix(th.bg, th.fg, 0.14).hex())
for i, c := range []string{"#ff5f57", "#febc2e", "#28c840"} {
fmt.Fprintf(&b, `<circle cx="%s" cy="%s" r="6" fill="%s"/>`, f(20+float64(i)*20), f(titleH/2), c)
}
b.WriteString("\n")
if title != "" {
fmt.Fprintf(&b, `<text x="%s" y="%s" text-anchor="middle" fill="%s" font-family="-apple-system, 'Segoe UI', Helvetica, Arial, sans-serif" font-size="13" font-weight="600">%s</text>`+"\n",
f(winW/2), f(titleH/2+4.5), mix(th.fg, bar, 0.3).hex(), esc(title))
}
fmt.Fprintf(&b, `<g transform="translate(%s %s)">`+"\n", f(padding), f(titleH+padding))
backgrounds(&b, rows, th)
shapes(&b, rows, th)
text(&b, rows, th)
b.WriteString("</g>\n</g>\n</svg>\n")
return b.String()
}
func backgrounds(b *strings.Builder, rows [][]cell, th *theme) {
for y, row := range rows {
for x := 0; x < len(row); {
_, bg, own := th.colors(row[x].st)
n := 1
for x+n < len(row) {
_, bg2, own2 := th.colors(row[x+n].st)
if own2 != own || bg2 != bg {
break
}
n++
}
if own && bg != th.bg {
fmt.Fprintf(b, `<rect x="%s" y="%s" width="%s" height="%s" fill="%s"/>`+"\n",
f(float64(x)*cellW), f(float64(y)*cellH), f(float64(n)*cellW+0.6), f(cellH+0.6), bg.hex())
}
x += n
}
}
}
// shapes draws box drawing and block characters, one path per color.
func shapes(b *strings.Builder, rows [][]cell, th *theme) {
lines := map[string]*strings.Builder{}
heavy := map[string]*strings.Builder{}
var order []string
path := func(m map[string]*strings.Builder, c string) *strings.Builder {
p, ok := m[c]
if !ok {
p = &strings.Builder{}
m[c] = p
order = append(order, c)
}
return p
}
for y, row := range rows {
for x, c := range row {
fg, _, _ := th.colors(c.st)
x0, y0 := float64(x)*cellW, float64(y)*cellH
if r, ok := blockChars[c.r]; ok {
fmt.Fprintf(b, `<rect x="%s" y="%s" width="%s" height="%s" fill="%s"/>`+"\n",
f(x0+r[0]*cellW), f(y0+r[1]*cellH), f(r[2]*cellW+0.6), f(r[3]*cellH+0.6), fg.hex())
continue
}
a, ok := boxChars[c.r]
if !ok {
continue
}
m := lines
if a.heavy {
m = heavy
}
p := path(m, fg.hex())
cx, cy := x0+cellW/2, y0+cellH/2
if a.round {
// One quarter circle from the horizontal to the vertical arm.
hx := x0 + cellW
if a.l {
hx = x0
}
vy := y0 + cellH
if a.u {
vy = y0
}
rad := cellW / 2
sx := cx + rad
if a.l {
sx = cx - rad
}
sy := cy + rad
if a.u {
sy = cy - rad
}
fmt.Fprintf(p, "M%s %sH%sQ%s %s %s %sV%s", f(hx), f(cy), f(sx), f(cx), f(cy), f(cx), f(sy), f(vy))
continue
}
if a.l || a.r {
l, r := cx, cx
if a.l {
l = x0
}
if a.r {
r = x0 + cellW
}
fmt.Fprintf(p, "M%s %sH%s", f(l), f(cy), f(r))
}
if a.u || a.d {
u, d := cy, cy
if a.u {
u = y0
}
if a.d {
d = y0 + cellH
}
fmt.Fprintf(p, "M%s %sV%s", f(cx), f(u), f(d))
}
}
}
for _, c := range order {
if p, ok := lines[c]; ok {
fmt.Fprintf(b, `<path d="%s" fill="none" stroke="%s" stroke-width="1.2"/>`+"\n", p.String(), c)
}
if p, ok := heavy[c]; ok {
fmt.Fprintf(b, `<path d="%s" fill="none" stroke="%s" stroke-width="2.4"/>`+"\n", p.String(), c)
}
}
}
// text writes runs of equally styled characters. Each run is stretched to
// its exact cell width so that columns line up with any font.
func text(b *strings.Builder, rows [][]cell, th *theme) {
fmt.Fprintf(b, `<g font-family="%s" font-size="%s" xml:space="preserve">`+"\n", fontFamily, f(fontSize))
drawn := func(c cell) bool {
_, box := boxChars[c.r]
_, block := blockChars[c.r]
return !c.cont && !box && !block
}
for y, row := range rows {
for x := 0; x < len(row); {
c := row[x]
if !drawn(c) || (c.blank && !c.st.under && !c.st.strike) {
x++
continue
}
fg, _, _ := th.colors(c.st)
var s strings.Builder
n := 0
for x+n < len(row) {
d := row[x+n]
if d.cont {
n++
continue
}
fg2, _, _ := th.colors(d.st)
if !drawn(d) || fg2 != fg || d.st.bold != c.st.bold || d.st.italic != c.st.italic ||
d.st.under != c.st.under || d.st.strike != c.st.strike || d.wide {
break
}
s.WriteRune(d.r)
n++
}
if n == 0 { // a wide character starts its own run
s.WriteRune(c.r)
n = 2
}
str := strings.TrimRight(s.String(), " ")
if c.st.under || c.st.strike {
str = s.String()
}
// Renderers collapse runs of spaces despite xml:space, so text
// is split at them and every piece is placed on its own.
for _, p := range pieces(str, c.st.under || c.st.strike) {
attrs := ""
if c.st.bold {
attrs += ` font-weight="700"`
}
if c.st.italic {
attrs += ` font-style="italic"`
}
switch {
case c.st.under && c.st.strike:
attrs += ` text-decoration="underline line-through"`
case c.st.under:
attrs += ` text-decoration="underline"`
case c.st.strike:
attrs += ` text-decoration="line-through"`
}
fmt.Fprintf(b, `<text x="%s" y="%s" fill="%s" textLength="%s" lengthAdjust="spacingAndGlyphs"%s>%s</text>`+"\n",
f(float64(x+p.col)*cellW), f(float64(y)*cellH+baseline), fg.hex(), f(float64(p.cells)*cellW), attrs, esc(p.text))
}
x += n
}
}
b.WriteString("</g>\n")
}
type piece struct {
text string
col, cells int
}
// pieces splits s at runs of two or more spaces (or at every space when the
// spaces themselves are decorated, where they are replaced by no-break
// spaces instead).
func pieces(s string, keepSpaces bool) []piece {
if keepSpaces {
return []piece{{strings.ReplaceAll(s, " ", " "), 0, ansi.StringWidth(s)}}
}
var out []piece
col := 0
for s != "" {
lead := len(s) - len(strings.TrimLeft(s, " "))
col += lead
s = s[lead:]
end := strings.Index(s, " ")
if end < 0 {
end = len(s)
}
t := strings.TrimRight(s[:end], " ")
if t != "" {
w := ansi.StringWidth(t)
out = append(out, piece{t, col, w})
col += w
}
s = s[len(t):]
}
return out
}
func f(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
func esc(s string) string {
return strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;").Replace(s)
}