Skip to content

Commit 6415765

Browse files
authored
Merge pull request #15 from agentstation/codex/resolve-svg-fonts
Embed installed SVG fonts before capture
2 parents eeb09ba + 74083f0 commit 6415765

15 files changed

Lines changed: 1230 additions & 58 deletions

‎README.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,14 @@ Use `--svg-font-file` or `VHS_SVG_FONT_FILE` to load an exact font into the capt
228228
This option overrides `Set FontFamily`. Supported file extensions are `.woff2`, `.woff`, `.ttf`, and `.otf`.
229229
Use a font whose license permits embedding.
230230

231+
For SVG output, a single installed family set with `Set FontFamily` also embeds automatically when `fc-match` is available.
232+
VHS loads that selected face before measuring the terminal. A separate named `WindowBarFontFamily` embeds its own face.
233+
Generic families and comma-separated fallback stacks keep their existing behavior.
234+
235+
With optional FontTools `pyftsubset`, optimized SVG output includes a smaller font with the displayed terminal, cursor, and title glyphs.
236+
If subsetting is unavailable or fails, VHS embeds the full selected face. If discovery is unavailable, capture continues with a diagnostic.
237+
An explicit font file takes priority and retains its exact bytes without subsetting.
238+
231239
## Record Tapes
232240

233241
VHS has the ability to generate tape files from your terminal actions!
@@ -976,7 +984,8 @@ This fork adds several command-line options to enhance VHS functionality:
976984
### Output Control
977985

978986
```sh
979-
# Disable SVG minification and short class names (optimization is enabled by default)
987+
# Disable SVG minification, short class names, and automatic font subsetting
988+
# Optimization is enabled by default
980989
vhs demo.tape --no-svg-opt
981990

982991
# Specify multiple output formats

‎command.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,7 @@ func ExecuteSetFontSize(c parser.Command, v *VHS) error {
534534
// ExecuteSetFontFamily applies the font family on the vhs.
535535
func ExecuteSetFontFamily(c parser.Command, v *VHS) error {
536536
v.Options.FontFamily = c.Args
537-
_, err := v.Page.Eval(fmt.Sprintf("() => term.options.fontFamily = '%s'", withSymbolsFallback(c.Args)))
537+
_, err := v.Page.Eval("family => term.options.fontFamily = family", withSymbolsFallback(c.Args))
538538
if err != nil {
539539
return fmt.Errorf("failed to set font family: %w", err)
540540
}

‎docs/demo-capture.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,14 @@ This option overrides `Set FontFamily` for capture and SVG output.
9595
The caller must supply a font whose license permits embedding.
9696
The file loads before capture, without `fc-match` or `pyftsubset`.
9797

98+
Single named installed families now use optional `fc-match` discovery before capture.
99+
The capture browser and SVG use the same selected face, including the actual face index in font collections.
100+
Optional `pyftsubset` reduces automatic fonts to all displayed frame, cursor, and applicable title glyphs.
101+
A separate named title family embeds a separate face.
102+
103+
Failed or missing subsetting retains the full selected font.
104+
Explicit file bytes remain unchanged. Generic families and fallback stacks do not use automatic embedding.
105+
98106
## Validation
99107

100108
The Go suite and race checks pass. Focused regressions cover slow capture, hidden spans,

‎evaluator.go‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,12 +163,17 @@ func Evaluate(ctx context.Context, tape string, out io.Writer, opts ...Evaluator
163163
_ = v.Cleanup()
164164
}()
165165

166-
teardown := func() []error {
166+
teardown := func(prepareFonts bool) []error {
167167
cancel()
168168
var errs []error
169169
for err := range ch {
170170
errs = append(errs, err)
171171
}
172+
if prepareFonts && len(errs) == 0 {
173+
if err := v.prepareSVGFonts(ctx); err != nil {
174+
errs = append(errs, err)
175+
}
176+
}
172177
// Commands have stopped, so browser cleanup cannot interrupt their rod calls.
173178
_ = v.terminate()
174179
return errs
@@ -179,12 +184,12 @@ func Evaluate(ctx context.Context, tape string, out io.Writer, opts ...Evaluator
179184
select {
180185
case err := <-ch:
181186
if err != nil {
182-
return append([]error{err}, teardown()...)
187+
return append([]error{err}, teardown(false)...)
183188
}
184189
default:
185190
}
186191
if ctx.Err() != nil {
187-
return append(teardown(), ctx.Err())
192+
return append(teardown(false), ctx.Err())
188193
}
189194

190195
// When changing the FontFamily, FontSize, LineHeight, Padding
@@ -207,7 +212,7 @@ func Evaluate(ctx context.Context, tape string, out io.Writer, opts ...Evaluator
207212
_, _ = fmt.Fprintln(out, Highlight(cmd, !v.isRecording() || cmd.Type == token.SHOW || cmd.Type == token.HIDE || isSetting))
208213
err := Execute(cmd, &v)
209214
if err != nil {
210-
return append(teardown(), err)
215+
return append(teardown(false), err)
211216
}
212217
}
213218

@@ -223,7 +228,7 @@ func Evaluate(ctx context.Context, tape string, out io.Writer, opts ...Evaluator
223228
opt(&v)
224229
}
225230

226-
if errs := teardown(); len(errs) > 0 {
231+
if errs := teardown(true); len(errs) > 0 {
227232
return errs
228233
}
229234
if err := v.Render(ctx); err != nil {

‎svg.go‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ type SVGConfig struct {
7272
FontData string
7373
FontMIME string
7474
FontFormat string
75+
TitleFont svgFont
7576
}
7677

7778
// TerminalState represents a unique terminal state for deduplication.
@@ -145,6 +146,14 @@ type SVGGenerator struct {
145146

146147
// NewSVGGenerator creates a new SVG generator.
147148
func NewSVGGenerator(opts SVGConfig) *SVGGenerator {
149+
if opts.FontData != "" && strings.Contains(opts.FontFamily, ",") {
150+
opts.FontFamily = captureFontFamily
151+
if opts.Style != nil {
152+
style := *opts.Style
153+
style.FontFamily = captureFontFamily
154+
opts.Style = &style
155+
}
156+
}
148157
// Get character dimensions from the first frame if available
149158
charWidth := float64(opts.FontSize) * 0.55 // fallback
150159
charHeight := float64(opts.FontSize) * 1.2 // fallback
@@ -994,8 +1003,15 @@ func (g *SVGGenerator) generateStyles() string {
9941003
g.writeNewline(&sb)
9951004

9961005
if g.options.FontData != "" {
997-
fmt.Fprintf(&sb, `@font-face { font-family: "%s"; src: url("data:%s;base64,%s") format("%s"); }`,
998-
captureFontFamily, g.options.FontMIME, g.options.FontData, g.options.FontFormat)
1006+
family := g.options.FontFamily
1007+
if family == "" {
1008+
family = svgDefaultFontFamily
1009+
}
1010+
sb.WriteString((svgFont{data: g.options.FontData, mime: g.options.FontMIME, format: g.options.FontFormat}).cssFace(family))
1011+
g.writeNewline(&sb)
1012+
}
1013+
if g.options.TitleFont.data != "" {
1014+
sb.WriteString(g.options.TitleFont.cssFace(titleFontFamily))
9991015
g.writeNewline(&sb)
10001016
}
10011017

@@ -1078,8 +1094,8 @@ func (g *SVGGenerator) generateStyles() string {
10781094
foregroundColor = defaultForegroundColor
10791095
}
10801096
// Use a simpler font stack for better compatibility
1081-
textStyle := fmt.Sprintf("fill: %s; font-family: %s, monospace; font-size: %spx;",
1082-
foregroundColor, fontFamily, formatCoord(g.fontSize))
1097+
textStyle := fmt.Sprintf("fill: %s; font-family: %s; font-size: %spx;",
1098+
foregroundColor, buildSVGFontFamily(fontFamily), formatCoord(g.fontSize))
10831099
// Don't apply letter-spacing in SVG as it causes cursor misalignment
10841100
// The character positions from xterm.js already account for the terminal's letter spacing
10851101
_, _ = fmt.Fprintf(&sb, ".%s { %s }", textClass, textStyle)
@@ -1747,6 +1763,9 @@ func (g *SVGGenerator) generateWindowBar() string {
17471763
if style.WindowBarTitle != "" {
17481764
// Get the appropriate font family with fallbacks
17491765
fontFamily := getWindowBarFontFamily(style, g.options.FontFamily)
1766+
if g.options.TitleFont.data != "" {
1767+
fontFamily = buildSVGFontFamily(titleFontFamily)
1768+
}
17501769
// Get the appropriate font size with fallback
17511770
fontSize := style.WindowBarFontSize
17521771
if fontSize == 0 {
@@ -1783,7 +1802,7 @@ func (g *SVGGenerator) generateWindowBar() string {
17831802
// Window controls occupy roughly 80px on each side
17841803
centerX := g.options.Width / 2
17851804
_, _ = fmt.Fprintf(&sb, `<text x="%d" y="%d" text-anchor="middle" font-family="%s" font-size="%d" fill="#cccccc">`,
1786-
centerX, yPos, fontFamily, fontSize)
1805+
centerX, yPos, html.EscapeString(fontFamily), fontSize)
17871806
sb.WriteString(html.EscapeString(style.WindowBarTitle))
17881807
sb.WriteString(`</text>`)
17891808
g.writeNewline(&sb)
@@ -2103,20 +2122,19 @@ func parseFontFamily(fontFamily string) []string {
21032122
func buildSVGFontFamily(fontFamily string) string {
21042123
fonts := parseFontFamily(fontFamily)
21052124

2106-
// Build a new list without quotes - SVG will handle the attribute quoting
2125+
// Preserve ordinary names and quote names with CSS metacharacters.
21072126
fontList := make([]string, 0, len(fonts)+1)
21082127
hasMonospace := false
21092128

21102129
for _, font := range fonts {
21112130
// Check if this is a generic font family
21122131
if font == svgDefaultFontFamily || font == uiMonospaceFont || font == "sans-serif" || font == "serif" {
2113-
fontList = append(fontList, font)
2132+
fontList = append(fontList, cssFontFamily(font))
21142133
if font == svgDefaultFontFamily {
21152134
hasMonospace = true
21162135
}
21172136
} else {
2118-
// Add font names as-is, SVG attribute will be quoted
2119-
fontList = append(fontList, font)
2137+
fontList = append(fontList, cssFontFamily(font))
21202138
}
21212139
}
21222140

‎svg_font.go‎

Lines changed: 60 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,42 @@
11
package main
22

33
import (
4+
"context"
45
"encoding/base64"
56
"fmt"
7+
"log"
68
"os"
79
"path/filepath"
810
"strings"
911
)
1012

11-
const captureFontFamily = "VHS Capture Font"
13+
const (
14+
captureFontFamily = "VHS Capture Font"
15+
fontMIMETTF = "font/ttf"
16+
fontMIMEOTF = "font/otf"
17+
fontFormatTTF = "truetype"
18+
fontFormatOTF = "opentype"
19+
fontFormatWOFF2 = "woff2"
20+
)
1221

1322
type svgFont struct {
1423
data string
1524
mime string
1625
format string
26+
auto bool
1727
}
1828

1929
func readSVGFont(path string) (svgFont, error) {
2030
var font svgFont
2131
switch strings.ToLower(filepath.Ext(path)) {
2232
case ".woff2":
23-
font.mime, font.format = "font/woff2", "woff2"
33+
font.mime, font.format = "font/woff2", fontFormatWOFF2
2434
case ".woff":
2535
font.mime, font.format = "font/woff", "woff"
2636
case ".ttf":
27-
font.mime, font.format = "font/ttf", "truetype"
37+
font.mime, font.format = fontMIMETTF, fontFormatTTF
2838
case ".otf":
29-
font.mime, font.format = "font/otf", "opentype"
39+
font.mime, font.format = fontMIMEOTF, fontFormatOTF
3040
default:
3141
return font, fmt.Errorf("SVG font file must use .woff2, .woff, .ttf, or .otf")
3242
}
@@ -46,23 +56,63 @@ func (vhs *VHS) installSVGFont() error {
4656
if path == "" {
4757
path = os.Getenv("VHS_SVG_FONT_FILE")
4858
}
49-
if path == "" {
59+
if path == "" && vhs.Options.Video.Output.SVG == "" {
5060
return nil
5161
}
52-
font, err := readSVGFont(path)
62+
ctx := vhs.Page.GetContext()
63+
font, err := selectSVGFont(ctx, path, vhs.Options.FontFamily)
5364
if err != nil {
5465
return err
5566
}
67+
if font.data != "" {
68+
if err := vhs.loadSVGFont(captureFontFamily, font); err != nil {
69+
return err
70+
}
71+
vhs.svgFont = font
72+
if font.auto {
73+
vhs.svgOriginalFamily = vhs.Options.FontFamily
74+
}
75+
vhs.Options.FontFamily = captureFontFamily
76+
}
77+
if vhs.Options.Video.Output.SVG == "" {
78+
return nil
79+
}
80+
style := vhs.Options.Video.Style
81+
if style.WindowBar != "" && style.WindowBarTitle != "" && style.WindowBarFontFamily != "" {
82+
title, err := selectSVGFont(ctx, "", style.WindowBarFontFamily)
83+
if err != nil {
84+
return err
85+
}
86+
if title.data != "" {
87+
if err := vhs.loadSVGFont(titleFontFamily, title); err != nil {
88+
return err
89+
}
90+
vhs.svgTitleFont = title
91+
}
92+
}
93+
return nil
94+
}
95+
96+
func (vhs *VHS) loadSVGFont(family string, font svgFont) error {
5697
url := "data:" + font.mime + ";base64," + font.data
57-
_, err = vhs.Page.Eval(`async (family, url) => {
98+
_, err := vhs.Page.Eval(`async (family, url) => {
5899
const font = new FontFace(family, 'url("' + url + '")');
59100
await font.load();
60101
document.fonts.add(font);
61-
}`, captureFontFamily, url)
102+
}`, family, url)
62103
if err != nil {
63104
return fmt.Errorf("failed to load SVG font in capture browser: %w", err)
64105
}
65-
vhs.svgFont = font
66-
vhs.Options.FontFamily = captureFontFamily
67106
return nil
68107
}
108+
109+
func selectSVGFont(ctx context.Context, path, family string) (svgFont, error) {
110+
if path != "" {
111+
return readSVGFont(path)
112+
}
113+
return discoverSVGFont(ctx, family)
114+
}
115+
116+
func fontDiagnostic(family, message string) {
117+
log.Printf("SVG font %q: %s", family, message)
118+
}

0 commit comments

Comments
 (0)
⌂ 换网址