Fonts: a slide picture carries the uploaded faces it draws in
Thumbnails measured runs with an uploaded face but only named its family, and an SVG shown in an <img> sees none of the page's fonts: the runs were drawn in the stack's next family at positions measured for another (final review, I2). With svg.Options.EmbedFonts, which the thumbnails set, a picture's own <style> carries each uploaded face it draws in as an @font-face: a web subset of the glyphs drawn (fonts.WebSubset: Subset's tables plus a cmap, the renamed name table, the restyled OS/2 and a post without glyph names) as a data: URL. The thumbnail CSP allows font-src data:. The PDF export is unchanged: its module gets the renamed faces themselves.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+391
−13
internal/slides/fonts/truetype.go+12 −1internal/slides/fonts/uploaded.go+132 −9internal/slides/fonts/websubset_test.go+42 −0internal/slides/svg/embed_test.go+40 −0internal/slides/svg/svg.go+69 −1internal/slides/thumbs.go+4 −1internal/slidestest/thumbs_test.go+1 −1internal/slidestest/thumbs_uploaded_browser_test.go+91 −0
diff --git a/internal/slides/fonts/truetype.go b/internal/slides/fonts/truetype.go| index 795d6d4..e3e74ff 100644 |
| --- a/internal/slides/fonts/truetype.go |
| +++ b/internal/slides/fonts/truetype.go |
| @@ -527,6 +527,17 @@ func componentsOf(glyph []byte) []uint16 { |
| // glyph kept). Glyph ids are unchanged — see this file's header for |
| // why that is the whole design. |
| func (f *Font) Subset(keep map[uint16]bool) ([]byte, error) { |
| + out, err := f.subsetTables(keep) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return buildSfnt(out, 2*len(f.data)) |
| +} |
| + |
| +// subsetTables is Subset's tables, before they are put in a file: the |
| +// PDF's subset is these alone, and a web subset (WebSubset) adds the |
| +// tables a browser needs to load it. |
| +func (f *Font) subsetTables(keep map[uint16]bool) (map[string][]byte, error) { |
| loca, err := f.locaOffsets() |
| if err != nil { |
| return nil, err |
| @@ -630,7 +641,7 @@ func (f *Font) Subset(keep map[uint16]bool) ([]byte, error) { |
| return nil, fmt.Errorf("%w: %s", errNoTable, tag) |
| } |
| } |
| - return buildSfnt(out, 2*len(f.data)) |
| + return out, nil |
| } |
| // errTooLarge is a font built from another's tables that would be more |
diff --git a/internal/slides/fonts/uploaded.go b/internal/slides/fonts/uploaded.go| index 2e007d6..17b9bb9 100644 |
| --- a/internal/slides/fonts/uploaded.go |
| +++ b/internal/slides/fonts/uploaded.go |
| @@ -177,15 +177,7 @@ func (f *Font) Renamed(family string, weight int, italic bool) ([]byte, error) { |
| return nil, err |
| } |
| tables["name"] = name |
| - if os2, ok := f.tables["OS/2"]; ok && len(os2) >= 64 { |
| - os2 = append([]byte(nil), os2...) |
| - binary.BigEndian.PutUint16(os2[4:], uint16(weight)) |
| - sel := binary.BigEndian.Uint16(os2[62:]) |
| - sel &^= 0x0001 | 0x0200 // italic, oblique |
| - if italic { |
| - sel |= 0x0001 |
| - } |
| - binary.BigEndian.PutUint16(os2[62:], sel) |
| + if os2 := f.restyled(weight, italic); os2 != nil { |
| tables["OS/2"] = os2 |
| } |
| head := append([]byte(nil), tables["head"]...) |
| @@ -194,6 +186,137 @@ func (f *Font) Renamed(family string, weight int, italic bool) ([]byte, error) { |
| return buildSfnt(tables, 2*len(f.data)) |
| } |
| +// restyled is a copy of the font's OS/2 table with its weight and slope |
| +// set to weight and italic, or nil when it has none to copy. |
| +func (f *Font) restyled(weight int, italic bool) []byte { |
| + os2, ok := f.tables["OS/2"] |
| + if !ok || len(os2) < 64 { |
| + return nil |
| + } |
| + os2 = append([]byte(nil), os2...) |
| + binary.BigEndian.PutUint16(os2[4:], uint16(weight)) |
| + sel := binary.BigEndian.Uint16(os2[62:]) |
| + sel &^= 0x0001 | 0x0200 // italic, oblique |
| + if italic { |
| + sel |= 0x0001 |
| + } |
| + binary.BigEndian.PutUint16(os2[62:], sel) |
| + return os2 |
| +} |
| + |
| +// WebSubset is a font a browser can load holding only the glyphs text |
| +// draws (Subset's, ids unchanged), called family, at weight and slope: |
| +// for a slide picture shown in an <img>, which sees none of the page's |
| +// fonts and so carries its uploaded faces itself (svg.Options.EmbedFonts; |
| +// final review, I2). To Subset's tables it adds the ones a browser's |
| +// font sanitiser requires: a cmap of text's characters to their glyphs, |
| +// the renamed name table, the OS/2 table restyled as Renamed does, and a |
| +// post table without glyph names. Never more than twice the file. |
| +func (f *Font) WebSubset(text, family string, weight int, italic bool) ([]byte, error) { |
| + keep := map[uint16]bool{} |
| + chars := map[rune]uint16{} |
| + for _, r := range text { |
| + if g := f.GlyphIndex(r); g != 0 { |
| + keep[g] = true |
| + chars[r] = g |
| + } |
| + } |
| + tables, err := f.subsetTables(keep) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if tables["name"], err = renameTable(f.tables["name"], family); err != nil { |
| + return nil, err |
| + } |
| + os2 := f.restyled(weight, italic) |
| + if os2 == nil { |
| + return nil, fmt.Errorf("%w: OS/2", errNoTable) |
| + } |
| + tables["OS/2"] = os2 |
| + post := make([]byte, 32) |
| + binary.BigEndian.PutUint32(post, 0x00030000) // version 3: no glyph names |
| + if old := f.tables["post"]; len(old) >= 16 { |
| + copy(post[4:16], old[4:16]) // italic angle, underline position and thickness |
| + } |
| + tables["post"] = post |
| + tables["cmap"] = cmapOf(chars) |
| + return buildSfnt(tables, 2*len(f.data)) |
| +} |
| + |
| +// cmapOf is a cmap table mapping chars to their glyphs: a format 4 |
| +// subtable (Windows, BMP) for the characters below U+FFFF, while they |
| +// fit one, and a format 12 subtable (Windows, full repertoire) for all. |
| +func cmapOf(chars map[rune]uint16) []byte { |
| + runes := make([]rune, 0, len(chars)) |
| + for r := range chars { |
| + runes = append(runes, r) |
| + } |
| + sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] }) |
| + |
| + // Format 12: one group per character. |
| + f12 := make([]byte, 16+12*len(runes)) |
| + binary.BigEndian.PutUint16(f12, 12) |
| + binary.BigEndian.PutUint32(f12[4:], uint32(len(f12))) |
| + binary.BigEndian.PutUint32(f12[12:], uint32(len(runes))) |
| + for i, r := range runes { |
| + at := 16 + 12*i |
| + binary.BigEndian.PutUint32(f12[at:], uint32(r)) |
| + binary.BigEndian.PutUint32(f12[at+4:], uint32(r)) |
| + binary.BigEndian.PutUint32(f12[at+8:], uint32(chars[r])) |
| + } |
| + |
| + // Format 4: one segment per BMP character, then the 0xFFFF one. |
| + var bmp []rune |
| + for _, r := range runes { |
| + if r < 0xFFFF { |
| + bmp = append(bmp, r) |
| + } |
| + } |
| + var f4 []byte |
| + if n := len(bmp) + 1; 16+8*n <= 0xFFFF { |
| + f4 = make([]byte, 16+8*n) |
| + binary.BigEndian.PutUint16(f4, 4) |
| + binary.BigEndian.PutUint16(f4[2:], uint16(len(f4))) |
| + binary.BigEndian.PutUint16(f4[6:], uint16(2*n)) |
| + sel := 0 |
| + for 1<<(sel+1) <= n { |
| + sel++ |
| + } |
| + binary.BigEndian.PutUint16(f4[8:], uint16(2<<sel)) |
| + binary.BigEndian.PutUint16(f4[10:], uint16(sel)) |
| + binary.BigEndian.PutUint16(f4[12:], uint16(2*n-2<<sel)) |
| + ends, starts, deltas := 14, 16+2*n, 16+4*n // idRangeOffset stays 0 |
| + for i, r := range append(bmp, 0xFFFF) { |
| + binary.BigEndian.PutUint16(f4[ends+2*i:], uint16(r)) |
| + binary.BigEndian.PutUint16(f4[starts+2*i:], uint16(r)) |
| + delta := uint16(1) // 0xFFFF to glyph 0 |
| + if r != 0xFFFF { |
| + delta = chars[r] - uint16(r) |
| + } |
| + binary.BigEndian.PutUint16(f4[deltas+2*i:], delta) |
| + } |
| + } |
| + |
| + type sub struct { |
| + encoding uint16 |
| + data []byte |
| + } |
| + var subs []sub |
| + if f4 != nil { |
| + subs = append(subs, sub{1, f4}) |
| + } |
| + subs = append(subs, sub{10, f12}) |
| + out := make([]byte, 4+8*len(subs)) |
| + binary.BigEndian.PutUint16(out[2:], uint16(len(subs))) |
| + for i, s := range subs { |
| + binary.BigEndian.PutUint16(out[4+8*i:], 3) |
| + binary.BigEndian.PutUint16(out[4+8*i+2:], s.encoding) |
| + binary.BigEndian.PutUint32(out[4+8*i+4:], uint32(len(out))) |
| + out = append(out, s.data...) |
| + } |
| + return out |
| +} |
| + |
| // nameRecord is one string of a name table. |
| type nameRecord struct { |
| platform, encoding, language, id uint16 |
diff --git a/internal/slides/fonts/websubset_test.go b/internal/slides/fonts/websubset_test.go| new file mode 100644 |
| index 0000000..a34fc32 |
| --- /dev/null |
| +++ b/internal/slides/fonts/websubset_test.go |
| @@ -0,0 +1,42 @@ |
| +package fonts |
| + |
| +import ( |
| + "testing" |
| + |
| + "amadan.net/oficina/estilo.git/typeface" |
| +) |
| + |
| +// A slide picture carries an uploaded face as a web subset (final |
| +// review, I2): a font a browser's sanitiser takes, mapping the drawn |
| +// characters to the same glyphs as the whole face, called by the deck's |
| +// name, and small. |
| +func TestAWebSubsetIsAFontOfTheDrawnGlyphs(t *testing.T) { |
| + orig := serifRegular(t) |
| + const text = "Café ÿ — ok" |
| + b, err := orig.WebSubset(text, "Test Upload", 700, true) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sub, err := Parse(b) |
| + if err != nil { |
| + t.Fatalf("the subset does not parse: %v", err) |
| + } |
| + for _, r := range text { |
| + if got, want := sub.GlyphIndex(r), orig.GlyphIndex(r); got != want { |
| + t.Errorf("%q maps to glyph %d, the face's is %d", r, got, want) |
| + } |
| + } |
| + if sub.GlyphIndex('Z') != 0 { |
| + t.Error("a character not drawn is mapped") |
| + } |
| + face, err := typeface.Inspect(b) |
| + if err != nil { |
| + t.Fatalf("typeface.Inspect refuses the subset: %v", err) |
| + } |
| + if face.Family != "Test Upload" || face.Weight != 700 || !face.Italic { |
| + t.Errorf("the subset is %q %d italic %v", face.Family, face.Weight, face.Italic) |
| + } |
| + if len(b) > len(orig.data)/4 { |
| + t.Errorf("the subset of %d characters is %d bytes of a %d-byte face", len([]rune(text)), len(b), len(orig.data)) |
| + } |
| +} |
diff --git a/internal/slides/svg/embed_test.go b/internal/slides/svg/embed_test.go| new file mode 100644 |
| index 0000000..9d27449 |
| --- /dev/null |
| +++ b/internal/slides/svg/embed_test.go |
| @@ -0,0 +1,40 @@ |
| +package svg |
| + |
| +import ( |
| + "bytes" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/slides/internal/slides/fonts" |
| + "amadan.net/oficina/slides/internal/slides/layout" |
| +) |
| + |
| +// With EmbedFonts, a picture carries each uploaded face it draws in as |
| +// an @font-face of its own (final review, I2); without it, and for the |
| +// built-in faces, it carries none. |
| +func TestAPictureCarriesTheUploadedFacesItDraws(t *testing.T) { |
| + f, err := fonts.Parse(fonts.Data(fonts.Face{Family: fonts.Serif})) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + up := fonts.UploadedFamily(&fonts.Uploaded{CSS: "Test Upload", Weight: 400, Font: f, Fallback: "serif"}) |
| + p := layout.Paint{W: 100, H: 50, Ops: []layout.Op{layout.Text{X: 1, Y: 20, Runs: []layout.Run{ |
| + {S: "upload", Size: 10, Face: fonts.Face{Family: fonts.Sans, Uploaded: up}}, |
| + {S: " built in", Size: 10, Face: fonts.Face{Family: fonts.Sans}}, |
| + {S: " again", Size: 10, Face: fonts.Face{Family: fonts.Sans, Uploaded: up}}, |
| + }}}} |
| + with := Encode(p, Options{EmbedFonts: true}) |
| + if n := bytes.Count(with, []byte("@font-face")); n != 1 { |
| + t.Fatalf("%d @font-face rules, want one for the one uploaded face:\n%s", n, with[:min(len(with), 600)]) |
| + } |
| + if !bytes.Contains(with, []byte(`@font-face{font-family:'Test Upload';src:url(data:font/ttf;base64,`)) || |
| + !bytes.Contains(with, []byte(`font-weight:400;font-style:normal}`)) { |
| + t.Errorf("the rule is not the upload's: %s", with[:min(len(with), 400)]) |
| + } |
| + if !strings.Contains(string(with), "<defs>\n<style>") { |
| + t.Error("the rule is not in the picture's own <style>") |
| + } |
| + if without := Encode(p, Options{}); bytes.Contains(without, []byte("@font-face")) { |
| + t.Error("a picture without EmbedFonts carries a face") |
| + } |
| +} |
diff --git a/internal/slides/svg/svg.go b/internal/slides/svg/svg.go| index 9e92074..f4ebb21 100644 |
| --- a/internal/slides/svg/svg.go |
| +++ b/internal/slides/svg/svg.go |
| @@ -85,6 +85,17 @@ type Options struct { |
| // fallback, and it only draws where the SVG is fetched as a |
| // document; inside an `<img>` a browser will not load it. |
| AssetURL func(asset string) string |
| + |
| + // EmbedFonts puts every uploaded face a run is drawn in (a deck's |
| + // meta.fontFiles, Face.Upload) into the picture itself: an |
| + // @font-face in its own <style>, a subset of the glyphs it draws as |
| + // a data: URL (fonts.WebSubset). A picture shown in an `<img>` sees |
| + // none of the page's fonts, and its runs were measured in the |
| + // upload, so without it they are drawn in the stack's next family at |
| + // positions measured for another (final review, I2). The thumbnails |
| + // set it; the PDF export does not, since the PDF module is handed |
| + // the renamed faces themselves (fonts.Renamed). |
| + EmbedFonts bool |
| } |
| // Encode writes p as an SVG document. |
| @@ -96,6 +107,7 @@ type Options struct { |
| func Encode(p layout.Paint, o Options) []byte { |
| w := &writer{o: o} |
| w.body(p) |
| + style := w.fontFaces() |
| var out bytes.Buffer |
| out.WriteString(xml.Header) |
| @@ -105,8 +117,9 @@ func Encode(p layout.Paint, o Options) []byte { |
| // The title first, because an assistive technology reads the first |
| // <title> child of the root as the name of the whole picture. |
| out.WriteString("<title>" + esc(o.Title) + "</title>\n") |
| - if w.defs.Len() > 0 { |
| + if w.defs.Len() > 0 || style != "" { |
| out.WriteString("<defs>\n") |
| + out.WriteString(style) |
| out.Write(w.defs.Bytes()) |
| out.WriteString("</defs>\n") |
| } |
| @@ -125,6 +138,60 @@ type writer struct { |
| // slide of arrows in one colour defines one arrowhead. |
| arrows map[layout.Fill]string |
| n int |
| + // uploaded is, with EmbedFonts, each uploaded face a run is drawn in |
| + // and the text drawn in it, in the order first drawn. |
| + uploaded []*embedded |
| +} |
| + |
| +// embedded is one uploaded face a picture carries, and what it draws. |
| +type embedded struct { |
| + face *fonts.Uploaded |
| + text strings.Builder |
| +} |
| + |
| +// embed notes that r is drawn in an uploaded face, with EmbedFonts. |
| +// Faces are told apart as the PDF tells them (layout's usedKey): the |
| +// same face resolved under two stacks is one face here. |
| +func (w *writer) embed(r layout.Run) { |
| + u := r.Face.Upload() |
| + if !w.o.EmbedFonts || u == nil || u.Font == nil { |
| + return |
| + } |
| + for _, e := range w.uploaded { |
| + if strings.EqualFold(e.face.CSS, u.CSS) && e.face.Weight == u.Weight && e.face.Italic == u.Italic { |
| + e.text.WriteString(r.S) |
| + return |
| + } |
| + } |
| + e := &embedded{face: u} |
| + e.text.WriteString(r.S) |
| + w.uploaded = append(w.uploaded, e) |
| +} |
| + |
| +// fontFaces is the <style> carrying every uploaded face the picture |
| +// draws in, each a subset of the glyphs it draws (fonts.WebSubset) as a |
| +// data: URL, or "" when there is none. A face that cannot be subset is |
| +// left out, and its runs fall back as they would have. |
| +func (w *writer) fontFaces() string { |
| + var rules []string |
| + for _, e := range w.uploaded { |
| + b, err := e.face.Font.WebSubset(e.text.String(), e.face.CSS, e.face.Weight, e.face.Italic) |
| + if err != nil { |
| + continue |
| + } |
| + style := "normal" |
| + if e.face.Italic { |
| + style = "italic" |
| + } |
| + // The name passed deck.FontCSSName (layout draws no other): no |
| + // quote, backslash or angle bracket to escape. |
| + rules = append(rules, fmt.Sprintf(`@font-face{font-family:'%s';src:url(data:font/ttf;base64,%s) format('truetype');font-weight:%d;font-style:%s}`, |
| + e.face.CSS, base64.StdEncoding.EncodeToString(b), e.face.Weight, style)) |
| + } |
| + if len(rules) == 0 { |
| + return "" |
| + } |
| + return "<style>" + strings.Join(rules, "\n") + "</style>\n" |
| } |
| // id mints a document-unique id under this package's own prefix, so |
| @@ -282,6 +349,7 @@ func (w *writer) text(t layout.Text) { |
| span = `<a href="` + href + `">` + span + `</a>` |
| } |
| w.out.WriteString(span) |
| + w.embed(r) |
| adv, _ := fonts.Advance(r.Face, r.Size, r.S) |
| x += adv |
| } |
diff --git a/internal/slides/thumbs.go b/internal/slides/thumbs.go| index b597bc5..522172c 100644 |
| --- a/internal/slides/thumbs.go |
| +++ b/internal/slides/thumbs.go |
| @@ -201,6 +201,7 @@ func (a *app) thumbnail(r *http.Request, d Deck, view *deck.Deck, index int, bas |
| assets := assetBaseFor(base) |
| return svg.Encode(paint, svg.Options{ |
| Title: slideLabel(r, view.Slides[index], index+1), |
| + EmbedFonts: true, |
| InlineImages: a.assetBytes(r.Context(), d, view), |
| AssetURL: func(id string) string { |
| asset, ok := view.Assets[id] |
| @@ -306,8 +307,10 @@ func (a *app) assetBytes(ctx context.Context, d Deck, view *deck.Deck) func(stri |
| func thumbHeaders(w http.ResponseWriter, etag string) { |
| w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8") |
| w.Header().Set("X-Content-Type-Options", "nosniff") |
| + // font-src data: for the uploaded faces a picture carries in its own |
| + // <style> (svg.Options.EmbedFonts); it loads no font from anywhere. |
| w.Header().Set("Content-Security-Policy", |
| - "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:") |
| + "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src data:") |
| w.Header().Set("ETag", etag) |
| w.Header().Set("Cache-Control", "private, max-age=0, must-revalidate") |
| } |
diff --git a/internal/slidestest/thumbs_test.go b/internal/slidestest/thumbs_test.go| index 8972295..79fbf2d 100644 |
| --- a/internal/slidestest/thumbs_test.go |
| +++ b/internal/slidestest/thumbs_test.go |
| @@ -58,7 +58,7 @@ func checkThumbHeaders(t *testing.T, rec *httptest.ResponseRecorder, where strin |
| {"Content-Type", "image/svg+xml; charset=utf-8"}, |
| {"X-Content-Type-Options", "nosniff"}, |
| {"Cache-Control", "private, max-age=0, must-revalidate"}, |
| - {"Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:"}, |
| + {"Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; font-src data:"}, |
| } { |
| if got := rec.Header().Get(c.header); got != c.want { |
| t.Errorf("%s: %s = %q, want %q", where, c.header, got, c.want) |
diff --git a/internal/slidestest/thumbs_uploaded_browser_test.go b/internal/slidestest/thumbs_uploaded_browser_test.go| new file mode 100644 |
| index 0000000..2d85225 |
| --- /dev/null |
| +++ b/internal/slidestest/thumbs_uploaded_browser_test.go |
| @@ -0,0 +1,91 @@ |
| +//go:build browser |
| + |
| +package slidestest |
| + |
| +// A slide picture shown in an <img> draws an uploaded font's own glyphs |
| +// (final review, I2). The picture is measured with the upload, and an |
| +// SVG in an <img> sees none of the page's fonts, so the picture carries |
| +// the face itself: before, it named a family the browser did not have |
| +// and drew the stack's next one at positions measured for another. |
| +// |
| +// The upload is Liberation Mono's regular called "Oddity Sans 2", a |
| +// name no machine has installed. The heading is a row of i, whose ink |
| +// in a monospace face is far wider than in the serif after it in the |
| +// stack. The picture's ink is set beside the same text drawn on a |
| +// canvas in the same upload, loaded from the deck as the page loads it. |
| + |
| +import ( |
| + "math" |
| + "testing" |
| + "time" |
| + |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +func TestASlidePictureDrawsInItsUploadedFont(t *testing.T) { |
| + fr := newFontRigWith(t, dirStore(t)) |
| + css, ref := uploadFamily(t, fr, "LiberationMono-Regular.ttf", "Oddity Sans 2") |
| + const text = "iiiiiiiiiiiiiiii" |
| + sqid := fr.deck(t, "Picture", `[{"op":"set_meta","theme":"paper","title":"Picture"}, |
| + {"op":"add_slide","id":"slideone0001","layout":"flow","template":"title"}, |
| + {"op":"add_block","slide":"slideone0001","id":"head00000001","type":"heading","region":"heading","props":{"level":1},"markdown":"`+text+`"}]`) |
| + fam := recordFamily(t, fr, sqid, css) |
| + fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"'`+css+`', Liberation Serif, Georgia, serif","body":""}}]`) |
| + fr.rig.Run(fr.navigate("/fonts"), chromedp.WaitReady(`body`)) |
| + fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) |
| + |
| + var got struct { |
| + Picture, Canvas float64 |
| + Size float64 |
| + Error string |
| + } |
| + fr.eval(t, `(async () => { |
| + try { |
| + const url = '/d/`+sqid+`/slides/slideone0001.svg' |
| + const svg = new DOMParser().parseFromString(await (await fetch(url)).text(), 'image/svg+xml') |
| + const [, , W, H] = svg.documentElement.getAttribute('viewBox').split(' ').map(Number) |
| + const span = [...svg.querySelectorAll('tspan')].find((s) => s.textContent.trim() === '`+text+`') |
| + if (!span) return { Error: 'no tspan for the heading' } |
| + const size = Number(span.getAttribute('font-size')) |
| + const weight = span.getAttribute('font-weight') || '400' |
| + const y = Number(span.parentElement.getAttribute('y')) |
| + // ink is the width of everything not the background in rows y-size..y+size/4. |
| + const ink = (ctx) => { |
| + const top = Math.max(0, Math.floor(y - size)), h = Math.ceil(size * 1.25) |
| + const d = ctx.getImageData(0, top, W, h).data |
| + const bg = ctx.getImageData(0, 0, 1, 1).data |
| + let lo = W, hi = -1 |
| + for (let r = 0; r < h; r++) for (let x = 0; x < W; x++) { |
| + const i = (r * W + x) * 4 |
| + if (Math.abs(d[i] - bg[0]) + Math.abs(d[i + 1] - bg[1]) + Math.abs(d[i + 2] - bg[2]) > 96) { lo = Math.min(lo, x); hi = Math.max(hi, x) } |
| + } |
| + return hi < 0 ? 0 : hi - lo + 1 |
| + } |
| + const img = new Image() |
| + img.src = url |
| + await img.decode() |
| + const a = Object.assign(document.createElement('canvas'), { width: W, height: H }).getContext('2d') |
| + a.drawImage(img, 0, 0, W, H) |
| + const face = new FontFace('Reference Upload', 'url("/d/`+sqid+`/fonts/`+ref+`")', { weight }) |
| + await face.load() |
| + document.fonts.add(face) |
| + const b = Object.assign(document.createElement('canvas'), { width: W, height: H }).getContext('2d') |
| + b.fillStyle = '#ffffff' |
| + b.fillRect(0, 0, W, H) |
| + b.fillStyle = '#000000' |
| + b.font = weight + ' ' + size + 'px "Reference Upload"' |
| + b.fillText('`+text+`', 20, y) |
| + return { Picture: ink(a), Canvas: ink(b), Size: size } |
| + } catch (e) { return { Error: String(e) } } |
| + })()`, &got) |
| + if got.Error != "" { |
| + t.Fatal(got.Error) |
| + } |
| + t.Logf("ink: picture %v px, the upload on a canvas %v px, at %v px", got.Picture, got.Canvas, got.Size) |
| + if got.Canvas < 100 { |
| + t.Fatalf("the reference text is %v px wide: the check cannot see the font", got.Canvas) |
| + } |
| + if math.Abs(got.Picture-got.Canvas) > 0.05*got.Canvas { |
| + t.Errorf("the heading's ink in the picture is %v px wide, in the uploaded font %v px (size %v): the picture is not drawn in the upload", got.Picture, got.Canvas, got.Size) |
| + } |
| +} |