oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package slidestest
4
5// The motivating case, in Chromium (final review, I7): a variable WOFF2
6// upload, as Timeless Sans is. Each file here is built in the test from
7// Liberation Mono (SIL OFL) renamed "Var Sans", given an fvar with a
8// wght axis from 100 to 900, and wrapped in WOFF2 with the brotli writer,
9// as estilo's typeface tests build theirs. It is held to the gate's rule
10// as a static TTF is: loaded in time, it is the first and only face the
11// headings are drawn in; late past the deadline, it commits to the
12// stack's next family and never swaps in; brought in by a collaborator
13// while the editor is open, the change waits for it.
14//
15// WebKit is not checked: this machine has no Playwright engines, so the
16// WebKit tests skip here (see the final fix report).
17
18import (
19 "bytes"
20 "encoding/binary"
21 "net/http"
22 "sort"
23 "strings"
24 "testing"
25 "time"
26
27 "github.com/andybalholm/brotli"
28 "github.com/chromedp/chromedp"
29
30 "amadan.net/oficina/slides/internal/slides"
31 "amadan.net/oficina/slides/internal/slides/fonts"
32)
33
34type sfntTable struct {
35 tag string
36 data []byte
37}
38
39func sfntTablesOf(t *testing.T, sfnt []byte) (uint32, []sfntTable) {
40 t.Helper()
41 n := int(binary.BigEndian.Uint16(sfnt[4:]))
42 var out []sfntTable
43 for i := 0; i < n; i++ {
44 rec := sfnt[12+16*i:]
45 off, length := binary.BigEndian.Uint32(rec[8:]), binary.BigEndian.Uint32(rec[12:])
46 out = append(out, sfntTable{string(rec[:4]), bytes.Clone(sfnt[off : off+length])})
47 }
48 sort.Slice(out, func(i, j int) bool { return out[i].tag < out[j].tag })
49 return binary.BigEndian.Uint32(sfnt), out
50}
51
52// wghtAxis is an fvar of one wght axis, 100 to 900, default 400.
53func wghtAxis() []byte {
54 var b []byte
55 for _, v := range []uint16{1, 0, 16, 2, 1, 20, 0, 8} {
56 b = binary.BigEndian.AppendUint16(b, v)
57 }
58 b = append(b, "wght"...)
59 for _, v := range []float64{100, 400, 900} {
60 b = binary.BigEndian.AppendUint32(b, uint32(int32(v*65536)))
61 }
62 b = binary.BigEndian.AppendUint16(b, 0)
63 return binary.BigEndian.AppendUint16(b, 256)
64}
65
66var woff2KnownTags = []string{"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ", "VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS", "GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc", "bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop", "trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill"}
67
68func base128(n uint32) []byte {
69 var out []byte
70 for {
71 out = append([]byte{byte(n & 0x7F)}, out...)
72 if n >>= 7; n == 0 {
73 break
74 }
75 }
76 for i := 0; i < len(out)-1; i++ {
77 out[i] |= 0x80
78 }
79 return out
80}
81
82// woff2Of wraps tables in WOFF2: glyf and loca with the null transform,
83// the rest untransformed, one brotli stream.
84func woff2Of(flavor uint32, ts []sfntTable) []byte {
85 var dir, stream []byte
86 sfntSize := 12 + 16*len(ts)
87 for _, tb := range ts {
88 idx := 63
89 for i, k := range woff2KnownTags {
90 if k == tb.tag {
91 idx = i
92 }
93 }
94 version := byte(0)
95 if tb.tag == "glyf" || tb.tag == "loca" {
96 version = 3
97 }
98 dir = append(dir, version<<6|byte(idx))
99 if idx == 63 {
100 dir = append(dir, tb.tag...)
101 }
102 dir = append(dir, base128(uint32(len(tb.data)))...)
103 stream = append(stream, tb.data...)
104 sfntSize += (len(tb.data) + 3) &^ 3
105 }
106 var z bytes.Buffer
107 w := brotli.NewWriterLevel(&z, 5)
108 w.Write(stream)
109 w.Close()
110 total := 48 + len(dir) + z.Len()
111 padded := (total + 3) &^ 3
112 var b []byte
113 b = append(b, "wOF2"...)
114 b = binary.BigEndian.AppendUint32(b, flavor)
115 b = binary.BigEndian.AppendUint32(b, uint32(padded))
116 b = binary.BigEndian.AppendUint16(b, uint16(len(ts)))
117 b = binary.BigEndian.AppendUint16(b, 0)
118 b = binary.BigEndian.AppendUint32(b, uint32(sfntSize))
119 b = binary.BigEndian.AppendUint32(b, uint32(z.Len()))
120 b = append(b, make([]byte, 4+20)...)
121 b = append(b, dir...)
122 b = append(b, z.Bytes()...)
123 return append(b, make([]byte, padded-total)...)
124}
125
126// variableWOFF2 is Liberation Mono's regular called name, variable in
127// weight from 100 to 900, as a WOFF2.
128func variableWOFF2(t *testing.T, name string) []byte {
129 t.Helper()
130 f, err := fonts.Parse(libFont(t, "LiberationMono-Regular.ttf"))
131 if err != nil {
132 t.Fatal(err)
133 }
134 renamed, err := f.Renamed(name, 400, false)
135 if err != nil {
136 t.Fatal(err)
137 }
138 flavor, ts := sfntTablesOf(t, renamed)
139 ts = append(ts, sfntTable{"fvar", wghtAxis()})
140 sort.Slice(ts, func(i, j int) bool { return ts[i].tag < ts[j].tag })
141 return woff2Of(flavor, ts)
142}
143
144// variableRig is a font rig with a paper deck, and Var Sans in the
145// library as a variable WOFF2, recorded for the deck. use sets the
146// headings in it; without it the deck takes it on later.
147func variableRig(t *testing.T, use bool) (fr *fontRig, sqid, ref, fam string) {
148 t.Helper()
149 fr = newFontRigWith(t, dirStore(t))
150 data := variableWOFF2(t, "Var Sans")
151 if rec := uploadFonts(t, fr.app, fr.cookies, upFile{"var.woff2", data}); rec.Code != http.StatusOK {
152 t.Fatalf("upload: %d\n%s", rec.Code, rec.Body)
153 }
154 var row slides.LibraryFont
155 if err := fr.app.db.G.Where("ref = ?", sha(data)).First(&row).Error; err != nil {
156 t.Fatal(err)
157 }
158 if !row.Variable || row.Format != "woff2" || row.WeightMin != 100 || row.WeightMax != 900 || row.Pictures {
159 t.Fatalf("the upload is %+v, want a variable woff2, 100 to 900, not for pictures", row)
160 }
161 sqid = fr.deck(t, "Variable", paperDeck)
162 fam = recordFamily(t, fr, sqid, row.CSSName)
163 if use {
164 fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"'Var Sans', Liberation Serif, Georgia, serif","body":""}}]`)
165 }
166 fr.probeAlso("Var Sans")
167 return fr, sqid, sha(data), fam
168}
169
170// seenIn sorts the faces runs were seen in: any in Var Sans loaded, and
171// any in Var Sans's fallback.
172func seenIn(p probe) (web, fallback bool) {
173 for _, faces := range p.Seen {
174 for f := range faces {
175 web = web || strings.Contains(f, "var sans:web")
176 fallback = fallback || strings.Contains(f, "var sans:system")
177 }
178 }
179 return web, fallback
180}
181
182func TestFontAVariableWOFF2UploadLoadsInTime(t *testing.T) {
183 fr, sqid, ref, _ := variableRig(t, true)
184 share := "/s/" + mintShareLink(t, fr.app, "/d/"+sqid, fr.cookies)
185 fr.match.Store(ref)
186 fr.slow.Store(int64(time.Second))
187 for _, c := range []struct{ name, path string }{
188 {"viewer", "/d/" + sqid + "?slide=1"},
189 {"share link", share + "?slide=1"},
190 {"editor", "/d/" + sqid + "/edit"},
191 } {
192 t.Run(c.name, func(t *testing.T) {
193 start := time.Now()
194 fr.goTo(t, c.path)
195 if waited := time.Since(start); waited < 950*time.Millisecond {
196 t.Fatalf("the slide was shown %v after navigating, before the variable face could have arrived", waited)
197 }
198 fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
199 p := fr.clean(t)
200 webEverywhere(t, p)
201 sameLayout(t, p)
202 if web, fallback := seenIn(p); !web || fallback {
203 t.Errorf("headings seen in the variable face %v, in its fallback %v", web, fallback)
204 }
205 var weights []string
206 fr.eval(t, `[...document.fonts].filter((f) => f.family.replace(/["']/g, '') === 'Var Sans').map((f) => f.weight + ' ' + f.status)`, &weights)
207 if strings.Join(weights, "|") != "100 900 loaded" {
208 t.Errorf("the page's Var Sans faces: %v, want one, its weight the range", weights)
209 }
210 })
211 }
212}
213
214func TestFontAVariableWOFF2UploadLateCommitsToItsFallback(t *testing.T) {
215 fr, sqid, ref, _ := variableRig(t, true)
216 fr.match.Store(ref)
217 fr.slow.Store(int64(4 * time.Second))
218 fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
219 fr.shown(t)
220 fr.rig.Run(chromedp.Sleep(4 * time.Second))
221 if fr.hits(ref) == 0 {
222 t.Fatal("the variable face was never requested")
223 }
224 p := fr.clean(t)
225 sameLayout(t, p)
226 if web, fallback := seenIn(p); web || !fallback {
227 t.Errorf("late: headings seen in the variable face %v (it arrived after the page was shown), in its fallback %v", web, fallback)
228 }
229 var st struct {
230 Committed bool
231 Faces int
232 }
233 fr.eval(t, `({ Committed: window.slidesFonts.committed('u:Var Sans'), Faces: [...document.fonts].filter((f) => f.family.replace(/["']/g, '') === 'Var Sans').length })`, &st)
234 if !st.Committed || st.Faces != 0 {
235 t.Errorf("committed %v, %d of its faces in the page", st.Committed, st.Faces)
236 }
237}
238
239func TestFontAVariableWOFF2UploadArrivingLiveWaits(t *testing.T) {
240 fr, sqid, ref, fam := variableRig(t, false)
241 fr.goTo(t, "/d/"+sqid+"/edit")
242 fr.editable(t)
243 fr.until(t, `document.documentElement.getAttribute('data-slides-fonts-prefetch') === 'done'`)
244 fr.match.Store(ref)
245 fr.slow.Store(int64(time.Second))
246 fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"'Var Sans', Liberation Serif, Georgia, serif","body":""}}]`)
247 fr.until(t, `(() => { const h = document.querySelector('[slides-stage] [data-id="head00000001"]');
248 return !!h && /var sans/i.test(getComputedStyle(h).fontFamily) })()`)
249 fr.rig.Run(chromedp.Sleep(2 * time.Second))
250 p := fr.cleanAcross(t)
251 if web, fallback := seenIn(p); !web || fallback {
252 t.Errorf("live: headings seen in the variable face %v, in its fallback %v", web, fallback)
253 }
254 var loaded bool
255 fr.eval(t, `window.slidesFonts.loaded('u:Var Sans')`, &loaded)
256 if !loaded {
257 t.Error("the variable family is not loaded")
258 }
259}
260