Fonts: bound the cmap readers; uploaded runs keep the deck's stack
Uploaded fonts now reach Parse, so its counts are untrusted. A format 12 group ending at 0xFFFFFFFF wrapped its counter and never ended; such groups are refused, and format 4 segments and format 12 groups may cover the BMP and Unicode at most once, and map at most 131,072 runes. A run set in an upload names the deck's own stack (the upload, then the fallbacks the deck wrote), not the built-in stack it falls back to; faces resolve per family and stack, and the PDF gets each face once. The TrueType table helpers the tests shared by copy move to fonts/fontstest.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+385
−123
internal/slides/export_fonts_test.go+2 −36internal/slides/fonts/fontstest/fontstest.go+88 −0internal/slides/fonts/hostile_test.go+151 −0internal/slides/fonts/truetype.go+34 −6internal/slides/fonts/uploaded.go+17 −10internal/slides/fonts/uploaded_test.go+2 −2internal/slides/layout/layout.go+31 −14internal/slides/layout/uploaded_test.go+60 −55
diff --git a/internal/slides/export_fonts_test.go b/internal/slides/export_fonts_test.go| index 7d024ef..6ca433d 100644 |
| --- a/internal/slides/export_fonts_test.go |
| +++ b/internal/slides/export_fonts_test.go |
| @@ -4,7 +4,6 @@ import ( |
| "bytes" |
| "context" |
| "crypto/sha256" |
| - "encoding/binary" |
| "encoding/hex" |
| "errors" |
| "io" |
| @@ -17,6 +16,7 @@ import ( |
| "time" |
| "amadan.net/oficina/slides/internal/slides/deck" |
| + "amadan.net/oficina/slides/internal/slides/fonts/fontstest" |
| "amadan.net/oficina/slides/internal/slides/layout" |
| "amadan.net/oficina/slides/internal/slides/svg" |
| @@ -117,7 +117,7 @@ func TestAVariableFontFallsBackInPicturesAndPDF(t *testing.T) { |
| data []byte |
| }{ |
| "marked": {deck.FontFace{Ref: uploadedRef, Format: "ttf", Weight: [2]int{100, 900}}, serif}, |
| - "marked for pictures by hand": {deck.FontFace{Ref: uploadedRef, Format: "ttf", Weight: [2]int{400, 400}, Pictures: true}, addTable(t, serif, "fvar", make([]byte, 16))}, |
| + "marked for pictures by hand": {deck.FontFace{Ref: uploadedRef, Format: "ttf", Weight: [2]int{400, 400}, Pictures: true}, fontstest.WithTable(t, serif, "fvar", make([]byte, 16))}, |
| } { |
| t.Run(name, func(t *testing.T) { |
| d := uploadedDeck(c.face) |
| @@ -211,40 +211,6 @@ func TestTheFontLoaderReadsTheObjectStore(t *testing.T) { |
| } |
| } |
| -// addTable is a TrueType file with one more table in it. |
| -func addTable(t *testing.T, data []byte, tag string, body []byte) []byte { |
| - t.Helper() |
| - n := int(binary.BigEndian.Uint16(data[4:])) |
| - type rec struct { |
| - tag string |
| - body []byte |
| - } |
| - var recs []rec |
| - for i := 0; i < n; i++ { |
| - at := 12 + i*16 |
| - off := binary.BigEndian.Uint32(data[at+8:]) |
| - length := binary.BigEndian.Uint32(data[at+12:]) |
| - recs = append(recs, rec{string(data[at : at+4]), data[off : off+length]}) |
| - } |
| - recs = append(recs, rec{tag, body}) |
| - sort.Slice(recs, func(i, j int) bool { return recs[i].tag < recs[j].tag }) |
| - head := make([]byte, 12+16*len(recs)) |
| - copy(head, data[:4]) |
| - binary.BigEndian.PutUint16(head[4:], uint16(len(recs))) |
| - var out []byte |
| - for i, r := range recs { |
| - at := 12 + i*16 |
| - copy(head[at:], r.tag) |
| - binary.BigEndian.PutUint32(head[at+8:], uint32(len(head)+len(out))) |
| - binary.BigEndian.PutUint32(head[at+12:], uint32(len(r.body))) |
| - out = append(out, r.body...) |
| - for len(out)%4 != 0 { |
| - out = append(out, 0) |
| - } |
| - } |
| - return append(head, out...) |
| -} |
| - |
| // A face stored the way uploads store one — Put into the object store, |
| // which keys it by its SHA-256 — is what the loader reads back by ref, |
| // through a real store rather than a fake that takes any key. |
diff --git a/internal/slides/fonts/fontstest/fontstest.go b/internal/slides/fonts/fontstest/fontstest.go| new file mode 100644 |
| index 0000000..dfba609 |
| --- /dev/null |
| +++ b/internal/slides/fonts/fontstest/fontstest.go |
| @@ -0,0 +1,88 @@ |
| +// Package fontstest builds altered TrueType files for tests: a |
| +// Liberation face with a table added or replaced, or with other |
| +// embedding flags. Only tests import it. |
| +package fontstest |
| + |
| +import ( |
| + "encoding/binary" |
| + "sort" |
| + "testing" |
| +) |
| + |
| +// table is one entry of a TrueType table directory. |
| +type table struct { |
| + tag string |
| + body []byte |
| +} |
| + |
| +// tables reads data's table directory. |
| +func tables(tb testing.TB, data []byte) []table { |
| + tb.Helper() |
| + if len(data) < 12 { |
| + tb.Fatal("fontstest: not a TrueType file") |
| + } |
| + n := int(binary.BigEndian.Uint16(data[4:])) |
| + var out []table |
| + for i := 0; i < n; i++ { |
| + at := 12 + i*16 |
| + off := int(binary.BigEndian.Uint32(data[at+8:])) |
| + length := int(binary.BigEndian.Uint32(data[at+12:])) |
| + if at+16 > len(data) || off+length > len(data) { |
| + tb.Fatal("fontstest: table directory runs past the file") |
| + } |
| + out = append(out, table{string(data[at : at+4]), data[off : off+length]}) |
| + } |
| + return out |
| +} |
| + |
| +// build writes a TrueType file from tables, in tag order, each padded |
| +// to four bytes. Checksums are left zero: nothing under test reads them. |
| +func build(version []byte, ts []table) []byte { |
| + sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag }) |
| + head := make([]byte, 12+16*len(ts)) |
| + copy(head, version) |
| + binary.BigEndian.PutUint16(head[4:], uint16(len(ts))) |
| + var body []byte |
| + for i, t := range ts { |
| + at := 12 + i*16 |
| + copy(head[at:], t.tag) |
| + binary.BigEndian.PutUint32(head[at+8:], uint32(len(head)+len(body))) |
| + binary.BigEndian.PutUint32(head[at+12:], uint32(len(t.body))) |
| + body = append(body, t.body...) |
| + for len(body)%4 != 0 { |
| + body = append(body, 0) |
| + } |
| + } |
| + return append(head, body...) |
| +} |
| + |
| +// WithTable is data with table tag set to body: replaced when data has |
| +// one, added when it does not. |
| +func WithTable(tb testing.TB, data []byte, tag string, body []byte) []byte { |
| + tb.Helper() |
| + ts := tables(tb, data) |
| + replaced := false |
| + for i := range ts { |
| + if ts[i].tag == tag { |
| + ts[i].body, replaced = body, true |
| + } |
| + } |
| + if !replaced { |
| + ts = append(ts, table{tag, body}) |
| + } |
| + return build(data[:4], ts) |
| +} |
| + |
| +// WithFsType is data with its OS/2 embedding flags set to fsType. |
| +func WithFsType(tb testing.TB, data []byte, fsType uint16) []byte { |
| + tb.Helper() |
| + for _, t := range tables(tb, data) { |
| + if t.tag == "OS/2" { |
| + os2 := append([]byte(nil), t.body...) |
| + binary.BigEndian.PutUint16(os2[8:], fsType) |
| + return WithTable(tb, data, "OS/2", os2) |
| + } |
| + } |
| + tb.Fatal("fontstest: no OS/2 table") |
| + return nil |
| +} |
diff --git a/internal/slides/fonts/hostile_test.go b/internal/slides/fonts/hostile_test.go| new file mode 100644 |
| index 0000000..3d775bb |
| --- /dev/null |
| +++ b/internal/slides/fonts/hostile_test.go |
| @@ -0,0 +1,151 @@ |
| +package fonts |
| + |
| +import ( |
| + "encoding/binary" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/slides/internal/slides/fonts/fontstest" |
| +) |
| + |
| +// Uploaded fonts reach Parse from the object store, so every count in |
| +// a file is somebody else's number. These are the ones that drove a |
| +// loop or an allocation past what the table's own bytes hold. |
| + |
| +// parseWithin parses data and fails the test if that takes longer than |
| +// d: a parse that does not finish is the bug, whatever it returns. |
| +func parseWithin(t *testing.T, data []byte, d time.Duration) error { |
| + t.Helper() |
| + done := make(chan error, 1) |
| + go func() { |
| + _, err := Parse(data) |
| + done <- err |
| + }() |
| + select { |
| + case err := <-done: |
| + return err |
| + case <-time.After(d): |
| + t.Fatalf("Parse did not return within %v", d) |
| + return nil |
| + } |
| +} |
| + |
| +// cmapWith is a cmap table with one Unicode subtable, sub, under |
| +// platform/encoding. |
| +func cmapWith(platform, encoding uint16, sub []byte) []byte { |
| + head := make([]byte, 12) |
| + binary.BigEndian.PutUint16(head[2:], 1) |
| + binary.BigEndian.PutUint16(head[4:], platform) |
| + binary.BigEndian.PutUint16(head[6:], encoding) |
| + binary.BigEndian.PutUint32(head[8:], 12) |
| + return append(head, sub...) |
| +} |
| + |
| +// cmap12 is a format 12 subtable of groups {start, end, glyph}. |
| +func cmap12(groups ...[3]uint32) []byte { |
| + sub := make([]byte, 16+12*len(groups)) |
| + binary.BigEndian.PutUint16(sub, 12) |
| + binary.BigEndian.PutUint32(sub[4:], uint32(len(sub))) |
| + binary.BigEndian.PutUint32(sub[12:], uint32(len(groups))) |
| + for i, g := range groups { |
| + for j, v := range g { |
| + binary.BigEndian.PutUint32(sub[16+i*12+j*4:], v) |
| + } |
| + } |
| + return sub |
| +} |
| + |
| +// cmap4 is a format 4 subtable of segments {start, end}, each mapped |
| +// by delta 0 and no range offset. |
| +func cmap4(segs ...[2]uint16) []byte { |
| + n := len(segs) |
| + sub := make([]byte, 16+8*n) |
| + binary.BigEndian.PutUint16(sub, 4) |
| + binary.BigEndian.PutUint16(sub[2:], uint16(min(len(sub), 0xffff))) |
| + binary.BigEndian.PutUint16(sub[6:], uint16(2*n)) |
| + for i, s := range segs { |
| + binary.BigEndian.PutUint16(sub[14+i*2:], s[1]) // endCode |
| + binary.BigEndian.PutUint16(sub[16+2*n+i*2:], s[0]) // startCode |
| + } |
| + return sub |
| +} |
| + |
| +func serifBytes() []byte { return Data(Face{Family: Serif}) } |
| + |
| +// A group ending at 0xFFFFFFFF wrapped the 32-bit counter to zero, and |
| +// the loop never ended (Task 7 review). Codepoints past U+10FFFF are |
| +// not Unicode; the font is refused. |
| +func TestACmapGroupPastUnicodeIsRefused(t *testing.T) { |
| + for _, g := range [][3]uint32{ |
| + {0xffffffff, 0xffffffff, 1}, |
| + {0xfffffff0, 0xffffffff, 1}, |
| + {0x10ffff, 0x110000, 1}, |
| + } { |
| + data := fontstest.WithTable(t, serifBytes(), "cmap", cmapWith(3, 10, cmap12(g))) |
| + if err := parseWithin(t, data, 5*time.Second); err == nil { |
| + t.Errorf("group %#x..%#x parsed", g[0], g[1]) |
| + } |
| + } |
| +} |
| + |
| +// Groups are bounded by the bytes present, but each could still span |
| +// all of Unicode: ten thousand of them was ten billion iterations. |
| +// Real groups are sorted and disjoint, so together they cover Unicode |
| +// at most once; more is refused. |
| +func TestCmapGroupsCoverUnicodeAtMostOnce(t *testing.T) { |
| + groups := make([][3]uint32, 10000) |
| + for i := range groups { |
| + groups[i] = [3]uint32{0, 0x10ffff, 1} |
| + } |
| + data := fontstest.WithTable(t, serifBytes(), "cmap", cmapWith(3, 10, cmap12(groups...))) |
| + if err := parseWithin(t, data, 5*time.Second); err == nil { |
| + t.Error("overlapping groups covering Unicode ten thousand times parsed") |
| + } |
| +} |
| + |
| +// The same for format 4: 32,767 segments each spanning the BMP was two |
| +// billion iterations. |
| +func TestCmap4SegmentsCoverTheBMPAtMostOnce(t *testing.T) { |
| + segs := make([][2]uint16, 32767) |
| + for i := range segs { |
| + segs[i] = [2]uint16{0, 0xfffe} |
| + } |
| + data := fontstest.WithTable(t, serifBytes(), "cmap", cmapWith(3, 1, cmap4(segs...))) |
| + if err := parseWithin(t, data, 5*time.Second); err == nil { |
| + t.Error("overlapping segments covering the BMP 32,767 times parsed") |
| + } |
| +} |
| + |
| +// The twelve built-in faces still parse under the bounds, with every |
| +// rune they mapped before. |
| +func TestTheBoundsAdmitRealFonts(t *testing.T) { |
| + for _, f := range All() { |
| + font, err := Parse(Data(f)) |
| + if err != nil { |
| + t.Fatalf("%s: %v", f.File(), err) |
| + } |
| + if len(font.cmap) < 2000 { |
| + t.Errorf("%s maps only %d runes", f.File(), len(font.cmap)) |
| + } |
| + } |
| +} |
| + |
| +// Disjoint groups, each restarting at glyph 1 and as long as the font |
| +// has glyphs — a few kilobytes — mapped every rune of Unicode to a real |
| +// glyph: a map of tens of megabytes per face. No font this app draws |
| +// with maps more than maxCmapRunes; one that does is refused. |
| +func TestACmapMapsABoundedNumberOfRunes(t *testing.T) { |
| + serif, err := Parse(serifBytes()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + span := uint32(serif.NumGlyphs) - 2 |
| + var groups [][3]uint32 |
| + for start := uint32(0); start+span <= 0x10ffff; start += span + 1 { |
| + groups = append(groups, [3]uint32{start, start + span, 1}) |
| + } |
| + data := fontstest.WithTable(t, serifBytes(), "cmap", cmapWith(3, 10, cmap12(groups...))) |
| + if font, err := Parse(data); err == nil { |
| + t.Errorf("a cmap of %d runes from %d bytes of groups parsed", len(font.cmap), 12*len(groups)) |
| + } |
| +} |
diff --git a/internal/slides/fonts/truetype.go b/internal/slides/fonts/truetype.go| index e4ff3c8..42d48bd 100644 |
| --- a/internal/slides/fonts/truetype.go |
| +++ b/internal/slides/fonts/truetype.go |
| @@ -8,8 +8,11 @@ |
| // the two in step by hand until then: a fix here is a fix over there. |
| // |
| // Changed from the original: Face.Parsed reads its bytes through |
| -// Data(face) rather than a Data field, because this package's Face is |
| -// three fields and no payload (fonts.go says why). |
| +// Data(face) rather than a Data field, because this package's Face |
| +// carries no payload (fonts.go says why); and the cmap readers refuse a |
| +// codepoint past U+10FFFF and segments or groups that together span |
| +// more than Unicode, because uploaded fonts now reach Parse (Docs needs |
| +// the same two bounds: the 0xFFFFFFFF group hangs its parser too). |
| package fonts |
| @@ -19,6 +22,7 @@ import ( |
| "fmt" |
| "sort" |
| "sync" |
| + "unicode" |
| ) |
| // A minimal TrueType reader and subsetter — enough to measure text and |
| @@ -296,6 +300,11 @@ func (f *Font) parseCmap4(sub []byte) error { |
| if rangeBase+seg*2 > len(sub) { |
| return errShortTable |
| } |
| + // Segments are sorted and disjoint, so together they span the BMP |
| + // at most once. The bytes bound the segment count but not their |
| + // spans: 32,767 overlapping segments of the whole BMP were two |
| + // billion iterations. Past one BMP's worth, the table is refused. |
| + covered := 0 |
| for i := 0; i < seg; i++ { |
| end := binary.BigEndian.Uint16(sub[endBase+i*2:]) |
| start := binary.BigEndian.Uint16(sub[startBase+i*2:]) |
| @@ -304,6 +313,9 @@ func (f *Font) parseCmap4(sub []byte) error { |
| if start > end { |
| continue |
| } |
| + if covered += int(end) - int(start) + 1; covered > 0x10000 { |
| + return errors.New("fonts: cmap format 4 segments overlap") |
| + } |
| for c := uint32(start); c <= uint32(end); c++ { |
| if c == 0xFFFF { |
| continue // the required terminating segment, not a character |
| @@ -332,6 +344,12 @@ func (f *Font) parseCmap4(sub []byte) error { |
| return nil |
| } |
| +// maxCmapRunes is the most runes a font may map: twice the glyph ids a |
| +// font can have. Groups covering Unicode once can still map every rune |
| +// of it, from a few kilobytes of table, into a map of tens of |
| +// megabytes. |
| +const maxCmapRunes = 2 << 16 |
| + |
| func (f *Font) parseCmap12(sub []byte) error { |
| nGroups, ok := be32(sub, 12) |
| if !ok { |
| @@ -345,6 +363,12 @@ func (f *Font) parseCmap12(sub []byte) error { |
| if max := (len(sub) - 16) / 12; max >= 0 && nGroups > uint32(max) { |
| nGroups = uint32(max) |
| } |
| + // Groups are sorted and disjoint, so together they cover Unicode |
| + // at most once; the bytes bound how many there are, not how much |
| + // each spans, so the spans are counted too. And no codepoint is past |
| + // U+10FFFF: a group ending at 0xFFFFFFFF wrapped the counter below |
| + // to zero and never ended. |
| + covered := uint64(0) |
| for i := uint32(0); i < nGroups; i++ { |
| at := 16 + int(i)*12 |
| start, ok1 := be32(sub, at) |
| @@ -356,15 +380,19 @@ func (f *Font) parseCmap12(sub []byte) error { |
| if start > end { |
| continue |
| } |
| - // A pathological group spanning the whole of Unicode would |
| - // otherwise build a map with a million entries. |
| - if end-start > 0x10FFFF { |
| - continue |
| + if end > unicode.MaxRune { |
| + return fmt.Errorf("fonts: cmap maps %#x, past the end of Unicode", end) |
| + } |
| + if covered += uint64(end-start) + 1; covered > unicode.MaxRune+1 { |
| + return errors.New("fonts: cmap format 12 groups overlap") |
| } |
| for c := start; c <= end; c++ { |
| g := gid + (c - start) |
| if g != 0 && g < uint32(f.NumGlyphs) { |
| f.cmap[rune(c)] = uint16(g) |
| + if len(f.cmap) > maxCmapRunes { |
| + return fmt.Errorf("fonts: cmap maps more than %d runes", maxCmapRunes) |
| + } |
| } |
| } |
| } |
diff --git a/internal/slides/fonts/uploaded.go b/internal/slides/fonts/uploaded.go| index fd38c6c..84ae2b1 100644 |
| --- a/internal/slides/fonts/uploaded.go |
| +++ b/internal/slides/fonts/uploaded.go |
| @@ -15,12 +15,15 @@ import ( |
| // Uploaded is one uploaded face a picture can be drawn with: the CSS |
| // family the deck names it by, the weight (400 or 700) and slope it is |
| -// set for, and the parsed font. |
| +// set for, and the parsed font. Fallback is the rest of the deck's |
| +// stack after the uploaded name, as the deck wrote it, so a picture |
| +// names the stack the deck chose. |
| type Uploaded struct { |
| - CSS string |
| - Weight int |
| - Italic bool |
| - Font *Font |
| + CSS string |
| + Weight int |
| + Italic bool |
| + Font *Font |
| + Fallback string |
| // family is the faces of the same upload by slot (see slot), shared |
| // by all of them, so a face that turns bold or italic part-way |
| @@ -83,13 +86,17 @@ func (f Face) Upload() *Uploaded { |
| return nil |
| } |
| -// Stack is the CSS font-family a picture writes for f: the uploaded |
| -// family first when f is drawn in one, then its Family's stack — so a |
| -// browser that has the uploaded font shows it, and one that does not |
| -// shows the face the text was measured with when it fell back. |
| +// Stack is the CSS font-family a picture writes for f. Drawn in an |
| +// upload, it is the deck's own stack — the uploaded family, then the |
| +// fallbacks the deck named after it — so a browser that has the font |
| +// shows it and one that does not falls back as the deck said. Drawn in |
| +// a built-in face, it is that face's stack, as it always was. |
| func (f Face) Stack() string { |
| if u := f.Upload(); u != nil { |
| - return "'" + u.CSS + "', " + f.Family.Stack() |
| + if u.Fallback == "" { |
| + return "'" + u.CSS + "'" |
| + } |
| + return "'" + u.CSS + "', " + u.Fallback |
| } |
| return f.Family.Stack() |
| } |
diff --git a/internal/slides/fonts/uploaded_test.go b/internal/slides/fonts/uploaded_test.go| index ae225d0..3b6c29d 100644 |
| --- a/internal/slides/fonts/uploaded_test.go |
| +++ b/internal/slides/fonts/uploaded_test.go |
| @@ -25,7 +25,7 @@ func TestAnUploadWithoutTheStyleMeasuresTheBuiltInFace(t *testing.T) { |
| parsedMu.Unlock() |
| t.Cleanup(func() { parsedMu.Lock(); parsed = saved; parsedMu.Unlock() }) |
| - up := UploadedFamily(&Uploaded{CSS: "Upload", Weight: 400, Font: serifRegular(t)}) |
| + up := UploadedFamily(&Uploaded{CSS: "Upload", Weight: 400, Font: serifRegular(t), Fallback: "Georgia, serif"}) |
| bold := Face{Family: Sans, Bold: true, Uploaded: up} |
| if bold.Upload() != nil { |
| t.Fatal("a bold face found a regular-only upload") |
| @@ -39,7 +39,7 @@ func TestAnUploadWithoutTheStyleMeasuresTheBuiltInFace(t *testing.T) { |
| t.Errorf("stack %q, name %q: the fallback face should be named as itself", bold.Stack(), bold.Name()) |
| } |
| regular := Face{Family: Sans, Uploaded: up} |
| - if regular.Stack() != "'Upload', "+Sans.Stack() || regular.Name() != "Upload 400" { |
| + if regular.Stack() != "'Upload', Georgia, serif" || regular.Name() != "Upload 400" { |
| t.Errorf("stack %q, name %q", regular.Stack(), regular.Name()) |
| } |
| } |
diff --git a/internal/slides/layout/layout.go b/internal/slides/layout/layout.go| index 31353e2..2e2e142 100644 |
| --- a/internal/slides/layout/layout.go |
| +++ b/internal/slides/layout/layout.go |
| @@ -48,20 +48,31 @@ type Renderer struct { |
| // did not load or is not a face a picture may draw with. |
| parsed map[string]*fonts.Font |
| // families is each uploaded family resolved so far, by its CSS name |
| - // folded to lower case: one of its faces (fonts.UploadedFamily), or |
| - // nil for a family with none to draw with. |
| + // folded to lower case and the stack after it: one of its faces |
| + // (fonts.UploadedFamily), or nil for a family with none to draw |
| + // with. The stack is part of the key because a picture names it. |
| families map[string]*fonts.Uploaded |
| // used is every uploaded face some run of this render is drawn |
| - // in, in the order first drawn — what the PDF has to be handed, and |
| - // no more: a style uploaded and never set costs an export nothing. |
| + // in, once per family, weight and slope, in the order first drawn — |
| + // what the PDF has to be handed, and no more: a style uploaded and |
| + // never set costs an export nothing. |
| used []*fonts.Uploaded |
| - seen map[*fonts.Uploaded]bool |
| + seen map[usedKey]bool |
| +} |
| + |
| +// usedKey is one face as the PDF tells faces apart. The same face |
| +// resolved under two stacks (a heading's and a body's) is two Uploaded |
| +// values and one font. |
| +type usedKey struct { |
| + css string |
| + weight int |
| + italic bool |
| } |
| // New is a render of d. |
| func New(d *deck.Deck, o Options) *Renderer { |
| return &Renderer{d: d, opts: o, parsed: map[string]*fonts.Font{}, |
| - families: map[string]*fonts.Uploaded{}, seen: map[*fonts.Uploaded]bool{}} |
| + families: map[string]*fonts.Uploaded{}, seen: map[usedKey]bool{}} |
| } |
| // Layout draws the deck's slide at index; see the package's Layout. |
| @@ -87,8 +98,12 @@ func (r *Renderer) note(ops []Op) { |
| continue |
| } |
| for _, run := range t.Runs { |
| - if u := run.Face.Upload(); u != nil && !r.seen[u] { |
| - r.seen[u] = true |
| + u := run.Face.Upload() |
| + if u == nil { |
| + continue |
| + } |
| + if k := (usedKey{strings.ToLower(u.CSS), u.Weight, u.Italic}); !r.seen[k] { |
| + r.seen[k] = true |
| r.used = append(r.used, u) |
| } |
| } |
| @@ -114,15 +129,17 @@ func (r *Renderer) declared(name string) (deck.FontFamily, bool) { |
| return deck.FontFamily{}, false |
| } |
| -// family resolves an uploaded family to the faces a picture can draw |
| -// with, once per render: for each of regular, italic, bold and bold |
| +// family resolves an uploaded family, named first in a stack whose |
| +// remainder is rest, to the faces a picture can draw with, once per |
| +// render and stack: for each of regular, italic, bold and bold |
| // italic, the first face marked for pictures that covers the weight |
| // (400 or 700) and has the slope, and whose bytes load, parse, are not |
| // a variable font and allow embedding. The checks after the mark are |
| // there because a deck's meta.fontFiles is a document anyone with the |
| // deck can write, and the mark is only what it says. |
| -func (r *Renderer) family(fam deck.FontFamily) *fonts.Uploaded { |
| - key := strings.ToLower(fam.CSS) |
| +func (r *Renderer) family(fam deck.FontFamily, rest string) *fonts.Uploaded { |
| + rest = strings.TrimSpace(rest) |
| + key := strings.ToLower(fam.CSS) + "\x00" + rest |
| if u, ok := r.families[key]; ok { |
| return u |
| } |
| @@ -135,7 +152,7 @@ func (r *Renderer) family(fam deck.FontFamily) *fonts.Uploaded { |
| continue |
| } |
| if font := r.font(face.Ref); font != nil { |
| - faces = append(faces, &fonts.Uploaded{CSS: fam.CSS, Weight: weight, Italic: italic, Font: font}) |
| + faces = append(faces, &fonts.Uploaded{CSS: fam.CSS, Weight: weight, Italic: italic, Font: font, Fallback: rest}) |
| break |
| } |
| } |
| @@ -249,7 +266,7 @@ func (e *engine) stackFace(theme string, role fonts.Role, stack string, upload b |
| if fam, ok := e.render.declared(first); ok { |
| face := e.stackFace(theme, role, rest, false) |
| if upload { |
| - face.Uploaded = e.render.family(fam) |
| + face.Uploaded = e.render.family(fam, rest) |
| } |
| return face |
| } |
diff --git a/internal/slides/layout/uploaded_test.go b/internal/slides/layout/uploaded_test.go| index f7f5c7b..10df318 100644 |
| --- a/internal/slides/layout/uploaded_test.go |
| +++ b/internal/slides/layout/uploaded_test.go |
| @@ -1,7 +1,6 @@ |
| package layout_test |
| import ( |
| - "encoding/binary" |
| "encoding/xml" |
| "errors" |
| "math" |
| @@ -14,6 +13,7 @@ import ( |
| "amadan.net/oficina/slides/internal/slides/deck" |
| "amadan.net/oficina/slides/internal/slides/fonts" |
| + "amadan.net/oficina/slides/internal/slides/fonts/fontstest" |
| "amadan.net/oficina/slides/internal/slides/layout" |
| "amadan.net/oficina/slides/internal/slides/svg" |
| ) |
| @@ -31,7 +31,9 @@ const ( |
| var sansStack = fonts.Sans.Stack() |
| -func uploadStack() string { return "'" + uploadCSS + "', " + sansStack } |
| +// uploadStack is the deck's own stack, as uploadDeck writes it: what a |
| +// run set in the upload names. |
| +func uploadStack() string { return "'" + uploadCSS + "', Liberation Sans, sans-serif" } |
| func libFile(t *testing.T, name string) []byte { |
| t.Helper() |
| @@ -315,7 +317,7 @@ func TestAVariableFontFallsBackInPicturesAndPDF(t *testing.T) { |
| fallsBack(t, map[string][]byte{refRegular: serif}, face) |
| }) |
| t.Run("marked for pictures by hand", func(t *testing.T) { |
| - fallsBack(t, map[string][]byte{refRegular: withTable(t, serif, "fvar", make([]byte, 16))}, regularFace(refRegular)) |
| + fallsBack(t, map[string][]byte{refRegular: fontstest.WithTable(t, serif, "fvar", make([]byte, 16))}, regularFace(refRegular)) |
| }) |
| } |
| @@ -328,7 +330,7 @@ func TestARestrictedFontFallsBack(t *testing.T) { |
| }) |
| t.Run("marked for pictures by hand", func(t *testing.T) { |
| for _, fsType := range []uint16{0x0002, 0x0100, 0x0200} { |
| - fallsBack(t, map[string][]byte{refRegular: withFsType(t, serif, fsType)}, regularFace(refRegular)) |
| + fallsBack(t, map[string][]byte{refRegular: fontstest.WithFsType(t, serif, fsType)}, regularFace(refRegular)) |
| } |
| }) |
| } |
| @@ -384,57 +386,6 @@ func TestAFamilyNeitherBuiltInNorUploadedStillWarns(t *testing.T) { |
| } |
| } |
| -// withTable is a TrueType file with one more table in it. |
| -func withTable(t *testing.T, data []byte, tag string, body []byte) []byte { |
| - t.Helper() |
| - n := int(binary.BigEndian.Uint16(data[4:])) |
| - type rec struct { |
| - tag string |
| - body []byte |
| - } |
| - var recs []rec |
| - for i := 0; i < n; i++ { |
| - at := 12 + i*16 |
| - off := binary.BigEndian.Uint32(data[at+8:]) |
| - length := binary.BigEndian.Uint32(data[at+12:]) |
| - recs = append(recs, rec{string(data[at : at+4]), data[off : off+length]}) |
| - } |
| - recs = append(recs, rec{tag, body}) |
| - sort.Slice(recs, func(i, j int) bool { return recs[i].tag < recs[j].tag }) |
| - head := make([]byte, 12+16*len(recs)) |
| - copy(head, data[:4]) |
| - binary.BigEndian.PutUint16(head[4:], uint16(len(recs))) |
| - var bodyBytes []byte |
| - for i, r := range recs { |
| - at := 12 + i*16 |
| - copy(head[at:], r.tag) |
| - binary.BigEndian.PutUint32(head[at+8:], uint32(len(head)+len(bodyBytes))) |
| - binary.BigEndian.PutUint32(head[at+12:], uint32(len(r.body))) |
| - bodyBytes = append(bodyBytes, r.body...) |
| - for len(bodyBytes)%4 != 0 { |
| - bodyBytes = append(bodyBytes, 0) |
| - } |
| - } |
| - return append(head, bodyBytes...) |
| -} |
| - |
| -// withFsType is a TrueType file whose OS/2 embedding flags are fsType. |
| -func withFsType(t *testing.T, data []byte, fsType uint16) []byte { |
| - t.Helper() |
| - out := append([]byte(nil), data...) |
| - n := int(binary.BigEndian.Uint16(out[4:])) |
| - for i := 0; i < n; i++ { |
| - at := 12 + i*16 |
| - if string(out[at:at+4]) == "OS/2" { |
| - off := binary.BigEndian.Uint32(out[at+8:]) |
| - binary.BigEndian.PutUint16(out[off+8:], fsType) |
| - return out |
| - } |
| - } |
| - t.Fatal("no OS/2 table") |
| - return nil |
| -} |
| - |
| // A bold upload sets the heading, which is bold. |
| func TestAnUploadedBoldFaceSetsTheHeading(t *testing.T) { |
| bold := regularFace(refItalic) |
| @@ -491,3 +442,57 @@ func TestOnlyTheFacesARunUsesAreHandedOn(t *testing.T) { |
| t.Errorf("after a second layout, %d faces", n) |
| } |
| } |
| + |
| +// A run set in the upload names the deck's stack — the upload, then |
| +// the fallbacks the deck chose — not the built-in stack it was |
| +// measured against when it fell back. |
| +func TestAnUploadedRunKeepsTheDecksStack(t *testing.T) { |
| + d := uploadDeck(regularFace(refRegular)) |
| + d.Meta.Fonts.Body = "'" + uploadCSS + "', Georgia, serif" |
| + l := newLoader(map[string][]byte{refRegular: libFile(t, "LiberationSerif-Regular.ttf")}) |
| + p, warnings, err := layout.New(d, layout.Options{Fonts: l.load}).Layout(0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Georgia is neither built in nor uploaded: the bold run, which has |
| + // no upload, is measured in a substitute, and says so as it always |
| + // did. The upload itself is never the subject of a warning. |
| + for _, w := range warnings { |
| + if w.Kind == layout.WarnFont && strings.Contains(w.Detail, uploadCSS) { |
| + t.Errorf("a warning names the upload: %s", w.Detail) |
| + } |
| + } |
| + spans := tspans(t, svg.Encode(p, svg.Options{})) |
| + if got, want := spanNamed(t, spans, "plain words").attrs["font-family"], "'"+uploadCSS+"', Georgia, serif"; got != want { |
| + t.Errorf("the uploaded run names %q, want the deck's %q", got, want) |
| + } |
| + // The heading's stack names the upload with other fallbacks: the |
| + // two runs of one family keep their own stacks. |
| + heading := regularFace(refItalic) |
| + heading.Weight = [2]int{700, 700} |
| + d = uploadDeck(regularFace(refRegular), heading) |
| + d.Meta.Fonts.Body = "'" + uploadCSS + "', Georgia, serif" |
| + l = newLoader(map[string][]byte{ |
| + refRegular: libFile(t, "LiberationSerif-Regular.ttf"), |
| + refItalic: libFile(t, "LiberationSerif-Bold.ttf"), |
| + }) |
| + r := layout.New(d, layout.Options{Fonts: l.load}) |
| + if p, _, err = r.Layout(0); err != nil { |
| + t.Fatal(err) |
| + } |
| + spans = tspans(t, svg.Encode(p, svg.Options{})) |
| + if got, want := spanNamed(t, spans, "Heading").attrs["font-family"], uploadStack(); got != want { |
| + t.Errorf("the heading names %q, want %q", got, want) |
| + } |
| + if got, want := spanNamed(t, spans, "plain words").attrs["font-family"], "'"+uploadCSS+"', Georgia, serif"; got != want { |
| + t.Errorf("the body names %q, want %q", got, want) |
| + } |
| + if n := len(r.Uploaded()); n != 2 { |
| + t.Errorf("%d faces handed on, want the regular and the bold once each", n) |
| + } |
| + for ref, n := range l.reads { |
| + if n > 1 { |
| + t.Errorf("face %s read %d times", ref[:8], n) |
| + } |
| + } |
| +} |