oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1package layout_test
2
3import (
4 "encoding/xml"
5 "errors"
6 "math"
7 "os"
8 "path/filepath"
9 "sort"
10 "strconv"
11 "strings"
12 "testing"
13
14 "amadan.net/oficina/slides/internal/slides/deck"
15 "amadan.net/oficina/slides/internal/slides/fonts"
16 "amadan.net/oficina/slides/internal/slides/fonts/fontstest"
17 "amadan.net/oficina/slides/internal/slides/layout"
18 "amadan.net/oficina/slides/internal/slides/svg"
19)
20
21// The "uploaded" font in these tests is Liberation Serif (SIL OFL,
22// already in ../fonts/files) set under another CSS name in a theme
23// whose every face is Liberation Sans, so a run measured or drawn in
24// the upload cannot be mistaken for the fallback.
25const (
26 uploadCSS = "Test Upload"
27 refRegular = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
28 refItalic = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
29 uploadSize = 10
30)
31
32var sansStack = fonts.Sans.Stack()
33
34// uploadStack is the deck's own stack, as uploadDeck writes it: what a
35// run set in the upload names.
36func uploadStack() string { return "'" + uploadCSS + "', Liberation Sans, sans-serif" }
37
38func libFile(t *testing.T, name string) []byte {
39 t.Helper()
40 b, err := os.ReadFile(filepath.Join("..", "fonts", "files", name))
41 if err != nil {
42 t.Fatal(err)
43 }
44 return b
45}
46
47// loader is an injectable Options.Fonts over a map, counting reads.
48type loader struct {
49 files map[string][]byte
50 reads map[string]int
51}
52
53func newLoader(files map[string][]byte) *loader {
54 return &loader{files: files, reads: map[string]int{}}
55}
56
57func (l *loader) load(ref string) ([]byte, error) {
58 l.reads[ref]++
59 b, ok := l.files[ref]
60 if !ok {
61 return nil, errors.New("no such font")
62 }
63 return b, nil
64}
65
66// uploadDeck is one title-body slide, theme ink (Liberation Sans
67// throughout), whose heading and body name the uploaded family first.
68func uploadDeck(faces ...deck.FontFace) *deck.Deck {
69 return &deck.Deck{
70 Meta: deck.Meta{
71 Theme: "ink", Aspect: "16:9",
72 Fonts: &deck.Fonts{Heading: "'" + uploadCSS + "', Liberation Sans, sans-serif", Body: "'" + uploadCSS + "', Liberation Sans, sans-serif"},
73 FontFiles: []deck.FontFamily{{Family: "Test Upload family", CSS: uploadCSS, Faces: faces}},
74 },
75 Slides: []deck.Slide{{
76 ID: "up1", Layout: "flow", Template: "title-body",
77 Blocks: []deck.Block{
78 {ID: "h1", Type: "heading", Region: "heading",
79 Props: map[string]any{"level": float64(1)}, Text: txt("Heading")},
80 {ID: "t1", Type: "text", Region: "body", Props: map[string]any{"size": "m"},
81 Text: deck.Text{{
82 {T: "plain words "},
83 {T: "bold", B: true},
84 {T: " then "},
85 {T: "slanted", I: true},
86 {T: " then "},
87 {T: "code", C: true},
88 }}},
89 },
90 }},
91 }
92}
93
94func regularFace(ref string) deck.FontFace {
95 return deck.FontFace{Ref: ref, Format: "ttf", Weight: [2]int{400, 400}, Pictures: true}
96}
97
98// runsOf is every run the paint list draws, in order, with the x it is
99// drawn at.
100type placedRun struct {
101 layout.Run
102 X float64
103}
104
105func runsOf(p layout.Paint) []placedRun {
106 var out []placedRun
107 for _, op := range p.Ops {
108 txt, ok := op.(layout.Text)
109 if !ok {
110 continue
111 }
112 x := txt.X
113 for _, r := range txt.Runs {
114 out = append(out, placedRun{r, x})
115 w, _ := fonts.Advance(r.Face, r.Size, r.S)
116 x += w
117 }
118 }
119 return out
120}
121
122func runNamed(t *testing.T, runs []placedRun, s string) placedRun {
123 t.Helper()
124 for _, r := range runs {
125 if strings.TrimSpace(r.S) == s {
126 return r
127 }
128 }
129 t.Fatalf("no run %q in %v", s, runs)
130 return placedRun{}
131}
132
133// tspans is every <tspan> in an SVG: its text and attributes.
134type tspan struct {
135 text string
136 attrs map[string]string
137}
138
139func tspans(t *testing.T, out []byte) []tspan {
140 t.Helper()
141 dec := xml.NewDecoder(strings.NewReader(string(out)))
142 var spans []tspan
143 var cur *tspan
144 for {
145 tok, err := dec.Token()
146 if err != nil {
147 break
148 }
149 switch v := tok.(type) {
150 case xml.StartElement:
151 if v.Name.Local == "tspan" {
152 cur = &tspan{attrs: map[string]string{}}
153 for _, a := range v.Attr {
154 cur.attrs[a.Name.Local] = a.Value
155 }
156 }
157 case xml.CharData:
158 if cur != nil {
159 cur.text += string(v)
160 }
161 case xml.EndElement:
162 if v.Name.Local == "tspan" && cur != nil {
163 spans = append(spans, *cur)
164 cur = nil
165 }
166 }
167 }
168 return spans
169}
170
171func spanNamed(t *testing.T, spans []tspan, s string) tspan {
172 t.Helper()
173 for _, sp := range spans {
174 if strings.TrimSpace(sp.text) == s {
175 return sp
176 }
177 }
178 t.Fatalf("no tspan %q", s)
179 return tspan{}
180}
181
182// serifWidth is s's width at size summed straight from Liberation
183// Serif's own tables: what an upload of it measures.
184func serifWidth(t *testing.T, file string, size float64, s string) float64 {
185 t.Helper()
186 f, err := fonts.Parse(libFile(t, file))
187 if err != nil {
188 t.Fatal(err)
189 }
190 var w float64
191 for _, r := range s {
192 w += float64(f.Advance(f.GlyphIndex(r))) / float64(f.UnitsPerEm) * size
193 }
194 return w
195}
196
197func noFontWarning(t *testing.T, ws []layout.Warning) {
198 t.Helper()
199 for _, w := range ws {
200 if w.Kind == layout.WarnFont {
201 t.Errorf("a font warning for an uploaded family: %s", w.Detail)
202 }
203 }
204}
205
206func TestAStaticTrueTypeUploadIsMeasuredAndDrawn(t *testing.T) {
207 l := newLoader(map[string][]byte{
208 refRegular: libFile(t, "LiberationSerif-Regular.ttf"),
209 refItalic: libFile(t, "LiberationSerif-Italic.ttf"),
210 })
211 italic := regularFace(refItalic)
212 italic.Italic = true
213 d := uploadDeck(regularFace(refRegular), italic)
214
215 r := layout.New(d, layout.Options{Fonts: l.load})
216 p, warnings, err := r.Layout(0)
217 if err != nil {
218 t.Fatal(err)
219 }
220 noFontWarning(t, warnings)
221 runs := runsOf(p)
222
223 // Measured: the regular and italic runs are as wide as Liberation
224 // Serif's own advances say, which is not what the fallback says.
225 plain := runNamed(t, runs, "plain words")
226 want := serifWidth(t, "LiberationSerif-Regular.ttf", plain.Size, plain.S)
227 got, _ := fonts.Advance(plain.Face, plain.Size, plain.S)
228 if math.Abs(got-want) > 1e-9 {
229 t.Errorf("the regular run measures %v, want the upload's %v", got, want)
230 }
231 if sans, _ := fonts.Advance(fonts.Face{Family: fonts.Sans}, plain.Size, plain.S); math.Abs(sans-want) < 1 {
232 t.Fatalf("the fallback measures %v and the upload %v: the test cannot tell them apart", sans, want)
233 }
234 bold := runNamed(t, runs, "bold")
235 if math.Abs(bold.X-(plain.X+want)) > 1e-6 {
236 t.Errorf("the run after the upload starts at %v, want %v (placed by the upload's advances)", bold.X, plain.X+want)
237 }
238 slanted := runNamed(t, runs, "slanted")
239 if got, want := func() float64 { w, _ := fonts.Advance(slanted.Face, slanted.Size, slanted.S); return w }(),
240 serifWidth(t, "LiberationSerif-Italic.ttf", slanted.Size, slanted.S); math.Abs(got-want) > 1e-9 {
241 t.Errorf("the italic run measures %v, want the italic upload's %v", got, want)
242 }
243 // Bold has no uploaded face: CSS chooses the regular one for it (and
244 // a browser thickens it, keeping its advances), so it is measured in
245 // the regular upload (weights_test.go).
246 if got, want := func() float64 { w, _ := fonts.Advance(bold.Face, bold.Size, bold.S); return w }(),
247 serifWidth(t, "LiberationSerif-Regular.ttf", bold.Size, bold.S); math.Abs(got-want) > 1e-9 {
248 t.Errorf("the bold run measures %v, want the regular upload's %v", got, want)
249 }
250
251 // Drawn: the SVG names the uploaded family first, then the
252 // fallback, on the runs set in it, and only the fallback elsewhere.
253 spans := tspans(t, svg.Encode(p, svg.Options{}))
254 for _, c := range []struct{ run, family string }{
255 {"plain words", uploadStack()},
256 {"slanted", uploadStack()},
257 {"bold", uploadStack()},
258 {"Heading", uploadStack()},
259 {"code", fonts.Mono.Stack()},
260 } {
261 if got := spanNamed(t, spans, c.run).attrs["font-family"]; got != c.family {
262 t.Errorf("%q is drawn in %q, want %q", c.run, got, c.family)
263 }
264 }
265 sp := spanNamed(t, spans, "bold")
266 x, _ := strconv.ParseFloat(sp.attrs["x"], 64)
267 if math.Abs(x-(plain.X+want)) > 0.01 {
268 t.Errorf("the picture places the run after the upload at %v, want %v", x, plain.X+want)
269 }
270
271 // One render reads and parses each face at most once, however many
272 // times it lays out.
273 if _, _, err := r.Layout(0); err != nil {
274 t.Fatal(err)
275 }
276 for ref, n := range l.reads {
277 if n > 1 {
278 t.Errorf("face %s was read %d times in one render", ref[:8], n)
279 }
280 }
281 // Regular, italic, and the regular face set for bold.
282 if len(r.Uploaded()) != 3 {
283 t.Errorf("the render used %d uploaded faces, want 3", len(r.Uploaded()))
284 }
285}
286
287// fallsBack lays out uploadDeck(faces) with files and asserts every run
288// is in the fallback, the picture never names the upload, and nothing
289// warns about it.
290func fallsBack(t *testing.T, files map[string][]byte, faces ...deck.FontFace) {
291 t.Helper()
292 r := layout.New(uploadDeck(faces...), layout.Options{Fonts: newLoader(files).load})
293 p, warnings, err := r.Layout(0)
294 if err != nil {
295 t.Fatal(err)
296 }
297 noFontWarning(t, warnings)
298 for _, run := range runsOf(p) {
299 if run.Face.Upload() != nil {
300 t.Errorf("%q is set in the upload", run.S)
301 }
302 }
303 for _, sp := range tspans(t, svg.Encode(p, svg.Options{})) {
304 if strings.Contains(sp.attrs["font-family"], uploadCSS) {
305 t.Errorf("%q names the upload: %q", sp.text, sp.attrs["font-family"])
306 }
307 }
308 if n := len(r.Uploaded()); n != 0 {
309 t.Errorf("the render used %d uploaded faces, want none", n)
310 }
311}
312
313func TestAVariableFontFallsBackInPicturesAndPDF(t *testing.T) {
314 serif := libFile(t, "LiberationSerif-Regular.ttf")
315 t.Run("marked", func(t *testing.T) {
316 face := deck.FontFace{Ref: refRegular, Format: "ttf", Weight: [2]int{100, 900}}
317 fallsBack(t, map[string][]byte{refRegular: serif}, face)
318 })
319 t.Run("marked for pictures by hand", func(t *testing.T) {
320 fallsBack(t, map[string][]byte{refRegular: fontstest.WithTable(t, serif, "fvar", make([]byte, 16))}, regularFace(refRegular))
321 })
322}
323
324func TestARestrictedFontFallsBack(t *testing.T) {
325 serif := libFile(t, "LiberationSerif-Regular.ttf")
326 t.Run("marked", func(t *testing.T) {
327 face := regularFace(refRegular)
328 face.Pictures = false
329 fallsBack(t, map[string][]byte{refRegular: serif}, face)
330 })
331 t.Run("marked for pictures by hand", func(t *testing.T) {
332 for _, fsType := range []uint16{0x0002, 0x0100, 0x0200} {
333 fallsBack(t, map[string][]byte{refRegular: fontstest.WithFsType(t, serif, fsType)}, regularFace(refRegular))
334 }
335 })
336}
337
338func TestAWOFF2FallsBack(t *testing.T) {
339 woff2 := append([]byte("wOF2\x00\x01\x00\x00"), make([]byte, 64)...)
340 t.Run("marked", func(t *testing.T) {
341 fallsBack(t, map[string][]byte{refRegular: woff2},
342 deck.FontFace{Ref: refRegular, Format: "woff2", Weight: [2]int{400, 400}})
343 })
344 t.Run("marked for pictures by hand", func(t *testing.T) {
345 face := regularFace(refRegular)
346 face.Format = "woff2"
347 fallsBack(t, map[string][]byte{refRegular: woff2}, face)
348 })
349}
350
351func TestAnUploadThatDoesNotLoadFallsBack(t *testing.T) {
352 fallsBack(t, nil, regularFace(refRegular))
353 // No loader at all (no object store): the same.
354 r := layout.New(uploadDeck(regularFace(refRegular)), layout.Options{})
355 _, warnings, err := r.Layout(0)
356 if err != nil {
357 t.Fatal(err)
358 }
359 noFontWarning(t, warnings)
360}
361
362// A family that is neither in this build nor uploaded to the deck is
363// still the warning it always was.
364func TestAFamilyNeitherBuiltInNorUploadedStillWarns(t *testing.T) {
365 d := uploadDeck(regularFace(refRegular))
366 d.Meta.Fonts = &deck.Fonts{Heading: "'Elsewhere Sans', Liberation Sans", Body: "'" + uploadCSS + "', 'Elsewhere Sans', serif"}
367 r := layout.New(d, layout.Options{Fonts: newLoader(nil).load})
368 _, warnings, err := r.Layout(0)
369 if err != nil {
370 t.Fatal(err)
371 }
372 var details []string
373 for _, w := range warnings {
374 if w.Kind == layout.WarnFont {
375 details = append(details, w.Detail)
376 }
377 }
378 sort.Strings(details)
379 if len(details) != 2 || !strings.Contains(details[0], "Elsewhere Sans") || !strings.Contains(details[1], "Elsewhere Sans") {
380 t.Errorf("want one warning per stack naming Elsewhere Sans, got %q", details)
381 }
382 for _, d := range details {
383 if strings.Contains(d, uploadCSS) {
384 t.Errorf("a warning names the uploaded family: %q", d)
385 }
386 }
387}
388
389// A bold upload sets the heading, which is bold, and (as CSS would,
390// with nothing lighter) the regular text.
391func TestAnUploadedBoldFaceSetsTheHeading(t *testing.T) {
392 bold := regularFace(refItalic)
393 bold.Weight = [2]int{700, 700}
394 l := newLoader(map[string][]byte{refItalic: libFile(t, "LiberationSerif-Bold.ttf")})
395 p, _, err := layout.New(uploadDeck(bold), layout.Options{Fonts: l.load}).Layout(0)
396 if err != nil {
397 t.Fatal(err)
398 }
399 runs := runsOf(p)
400 h := runNamed(t, runs, "Heading")
401 if u := h.Face.Upload(); u == nil || u.Weight != 700 {
402 t.Fatalf("the heading is not set in the bold upload")
403 }
404 // With no lighter face, CSS sets regular text in the bold one too.
405 if u := runNamed(t, runs, "plain words").Face.Upload(); u == nil || u.Weight != 400 {
406 t.Error("regular text is not set in the bold upload")
407 }
408 if got := spanNamed(t, tspans(t, svg.Encode(p, svg.Options{})), "Heading").attrs["font-family"]; got != uploadStack() {
409 t.Errorf("the heading is drawn in %q", got)
410 }
411}
412
413// Only the uploaded faces some run is drawn in go to the PDF: a style
414// the deck uploaded and never sets costs the export nothing.
415func TestOnlyTheFacesARunUsesAreHandedOn(t *testing.T) {
416 italic := regularFace(refItalic)
417 italic.Italic = true
418 bold := regularFace(strings.Repeat("e", 64))
419 bold.Weight = [2]int{700, 700}
420 d := uploadDeck(regularFace(refRegular), italic, bold)
421 d.Slides[0].Blocks = []deck.Block{{ID: "t1", Type: "text", Region: "body", Text: txt("Only upright words here")}}
422 l := newLoader(map[string][]byte{
423 refRegular: libFile(t, "LiberationSerif-Regular.ttf"),
424 refItalic: libFile(t, "LiberationSerif-Italic.ttf"),
425 strings.Repeat("e", 64): libFile(t, "LiberationSerif-Bold.ttf"),
426 })
427 r := layout.New(d, layout.Options{Fonts: l.load})
428 if _, _, err := r.Layout(0); err != nil {
429 t.Fatal(err)
430 }
431 used := r.Uploaded()
432 if len(used) != 1 || used[0].Weight != 400 || used[0].Italic {
433 var got []string
434 for _, u := range used {
435 got = append(got, u.CSS+" "+strconv.Itoa(u.Weight)+" "+strconv.FormatBool(u.Italic))
436 }
437 t.Errorf("handed on %q, want only the regular face", got)
438 }
439 // Laying the slide out again hands on nothing twice.
440 if _, _, err := r.Layout(0); err != nil {
441 t.Fatal(err)
442 }
443 if n := len(r.Uploaded()); n != 1 {
444 t.Errorf("after a second layout, %d faces", n)
445 }
446}
447
448// A run set in the upload names the deck's stack — the upload, then
449// the fallbacks the deck chose — not the built-in stack it was
450// measured against when it fell back.
451func TestAnUploadedRunKeepsTheDecksStack(t *testing.T) {
452 d := uploadDeck(regularFace(refRegular))
453 d.Meta.Fonts.Body = "'" + uploadCSS + "', Georgia, serif"
454 l := newLoader(map[string][]byte{refRegular: libFile(t, "LiberationSerif-Regular.ttf")})
455 p, warnings, err := layout.New(d, layout.Options{Fonts: l.load}).Layout(0)
456 if err != nil {
457 t.Fatal(err)
458 }
459 // Georgia is neither built in nor uploaded: the bold run, which has
460 // no upload, is measured in a substitute, and says so as it always
461 // did. The upload itself is never the subject of a warning.
462 for _, w := range warnings {
463 if w.Kind == layout.WarnFont && strings.Contains(w.Detail, uploadCSS) {
464 t.Errorf("a warning names the upload: %s", w.Detail)
465 }
466 }
467 spans := tspans(t, svg.Encode(p, svg.Options{}))
468 if got, want := spanNamed(t, spans, "plain words").attrs["font-family"], "'"+uploadCSS+"', Georgia, serif"; got != want {
469 t.Errorf("the uploaded run names %q, want the deck's %q", got, want)
470 }
471 // The heading's stack names the upload with other fallbacks: the
472 // two runs of one family keep their own stacks.
473 heading := regularFace(refItalic)
474 heading.Weight = [2]int{700, 700}
475 d = uploadDeck(regularFace(refRegular), heading)
476 d.Meta.Fonts.Body = "'" + uploadCSS + "', Georgia, serif"
477 l = newLoader(map[string][]byte{
478 refRegular: libFile(t, "LiberationSerif-Regular.ttf"),
479 refItalic: libFile(t, "LiberationSerif-Bold.ttf"),
480 })
481 r := layout.New(d, layout.Options{Fonts: l.load})
482 if p, _, err = r.Layout(0); err != nil {
483 t.Fatal(err)
484 }
485 spans = tspans(t, svg.Encode(p, svg.Options{}))
486 if got, want := spanNamed(t, spans, "Heading").attrs["font-family"], uploadStack(); got != want {
487 t.Errorf("the heading names %q, want %q", got, want)
488 }
489 if got, want := spanNamed(t, spans, "plain words").attrs["font-family"], "'"+uploadCSS+"', Georgia, serif"; got != want {
490 t.Errorf("the body names %q, want %q", got, want)
491 }
492 if n := len(r.Uploaded()); n != 2 {
493 t.Errorf("%d faces handed on, want the regular and the bold once each", n)
494 }
495 for ref, n := range l.reads {
496 if n > 1 {
497 t.Errorf("face %s read %d times", ref[:8], n)
498 }
499 }
500}
501