oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fonts_test
2
3import (
4 "encoding/binary"
5 "regexp"
6 "strings"
7 "testing"
8
9 "github.com/carlosframework/docs/internal/fonts"
10)
11
12func family(t *testing.T, key string) *fonts.Family {
13 t.Helper()
14 f, ok := fonts.ByKey(key)
15 if !ok {
16 t.Fatalf("no family %q", key)
17 }
18 return f
19}
20
21// Paul's ruling, 2026-10-24: "it kind of has to be Carlito". An unmarked
22// run is in Carlito, a code run in Liberation Mono, and the picker opens
23// with Carlito and Caladea.
24func TestTheDefaultIsCarlito(t *testing.T) {
25 if fonts.Default.Key != "carlito" || fonts.Default.Name != "Carlito" {
26 t.Errorf("the default family is %s (%s), want Carlito", fonts.Default.Key, fonts.Default.Name)
27 }
28 if got := fonts.ForMarks(nil); got != fonts.Default {
29 t.Errorf("an unmarked run resolves to %s, want the default", got.Key)
30 }
31 if fonts.Code.Key != "mono" {
32 t.Errorf("code is set in %s, want Liberation Mono", fonts.Code.Key)
33 }
34 if len(fonts.Families) < 2 || fonts.Families[0].Key != "carlito" || fonts.Families[1].Key != "caladea" {
35 t.Errorf("the picker must open with Carlito then Caladea")
36 }
37}
38
39// The shortlist, by name. Sixteen families; adding one is a decision,
40// not a side effect.
41func TestTheShortlist(t *testing.T) {
42 want := []string{"Carlito", "Caladea", "Inter", "Source Sans 3", "IBM Plex Sans", "Source Serif 4",
43 "Literata", "EB Garamond", "Liberation Sans", "Liberation Serif", "Liberation Mono", "Noto Sans",
44 "Zilla Slab", "JetBrains Mono", "Playfair Display", "Caveat"}
45 var got []string
46 for _, f := range fonts.Families {
47 got = append(got, f.Name)
48 }
49 if strings.Join(got, ", ") != strings.Join(want, ", ") {
50 t.Errorf("families:\n got %v\nwant %v", got, want)
51 }
52}
53
54// The three keys Liberation always had keep their meaning, so a
55// document written before there were sixteen families looks the same.
56func TestTheOldKeysStillMeanLiberation(t *testing.T) {
57 for key, name := range map[string]string{"sans": "Liberation Sans", "serif": "Liberation Serif", "mono": "Liberation Mono"} {
58 if f := family(t, key); f.Name != name {
59 t.Errorf("font_%s is %s, want %s", key, f.Name, name)
60 }
61 }
62 if _, ok := fonts.ByKey("comic"); ok {
63 t.Error("an unknown key must be a miss, not a silent default")
64 }
65}
66
67// Two font marks on one run resolve to the one latest in the manifest,
68// which is the innermost span fragment.rs writes.
69func TestForMarksTakesTheInnermost(t *testing.T) {
70 got := fonts.ForMarks([]string{"font_carlito", "strong", "font_mono", "font_inter"})
71 if got.Key != "mono" {
72 t.Errorf("got %s, want mono (latest in manifest order)", got.Key)
73 }
74 if got := fonts.ForMarks([]string{"font_nope", "em"}); got != fonts.Default {
75 t.Errorf("unknown marks resolve to %s, want the default", got.Key)
76 }
77}
78
79// The editor finds the fonts a collaborator's update introduces by
80// looking for "font_<key>" in its bytes (NO-FOUT §6). That only works if
81// no key's mark is inside another's.
82func TestNoMarkContainsAnother(t *testing.T) {
83 for _, a := range fonts.Families {
84 for _, b := range fonts.Families {
85 if a != b && strings.Contains(b.Mark(), a.Mark()) {
86 t.Errorf("%s contains %s: a byte scan for one finds the other", b.Mark(), a.Mark())
87 }
88 }
89 }
90 key := regexp.MustCompile(`^[a-z][a-z0-9]*$`)
91 for _, f := range fonts.Families {
92 if !key.MatchString(f.Key) {
93 t.Errorf("key %q: keys are lower-case letters and digits, so mark, class and CSS agree", f.Key)
94 }
95 }
96}
97
98// Word round trips (Paul's default 5): Carlito is written as Calibri
99// and Caladea as Cambria, and both read back.
100func TestDocxNames(t *testing.T) {
101 for name, key := range map[string]string{
102 "Calibri": "carlito", "Cambria": "caladea", "calibri": "carlito",
103 "Arial": "sans", "Times New Roman": "serif", "Courier New": "mono",
104 "Carlito": "carlito", "Inter": "inter", "Source Serif 4": "sourceserif",
105 } {
106 f, ok := fonts.ByDocxName(name)
107 if !ok || f.Key != key {
108 t.Errorf("%q imports as %v, want %s", name, f, key)
109 }
110 }
111 if family(t, "carlito").Docx.Name != "Calibri" || family(t, "caladea").Docx.Name != "Cambria" {
112 t.Error("Carlito must export as Calibri and Caladea as Cambria")
113 }
114 if _, ok := fonts.ByDocxName("Wingdings"); ok {
115 t.Error("an unknown Word font must be a miss")
116 }
117}
118
119func TestEveryFaceParses(t *testing.T) {
120 n := 0
121 for _, f := range fonts.Families {
122 n += len(f.Styles())
123 }
124 if all := fonts.All(); len(all) != n || n < 60 {
125 t.Fatalf("want %d faces, got %d", n, len(all))
126 }
127 for _, face := range fonts.All() {
128 font, err := face.Parsed()
129 if err != nil {
130 t.Fatalf("%s: %v", face.File, err)
131 }
132 if font.UnitsPerEm == 0 || font.NumGlyphs == 0 {
133 t.Errorf("%s: unitsPerEm=%d numGlyphs=%d", face.File, font.UnitsPerEm, font.NumGlyphs)
134 }
135 if font.Ascender <= 0 || font.Descender >= 0 {
136 t.Errorf("%s: implausible vertical metrics asc=%d desc=%d", face.File, font.Ascender, font.Descender)
137 }
138 for _, r := range "The quick brown fox, 0123456789 — “quoted” café" {
139 if font.GlyphIndex(r) == 0 {
140 t.Errorf("%s: no glyph for %q", face.File, r)
141 }
142 }
143 }
144}
145
146// Every family has its four styles, except the two handwriting and
147// display faces whose designers drew no italic.
148func TestFamiliesHaveTheirStyles(t *testing.T) {
149 for _, f := range fonts.Families {
150 want := 4
151 if f.Key == "caveat" {
152 want = 2
153 }
154 if got := len(f.Styles()); got != want {
155 t.Errorf("%s has %d styles, want %d", f.Name, got, want)
156 }
157 // No italic stays upright rather than borrowing another family.
158 if face := f.Face(true, true); face.Family != f {
159 t.Errorf("%s bold italic resolves to another family", f.Name)
160 }
161 }
162}
163
164// Advance widths are what every measurement in internal/pdf is built
165// on. A monospace face is the one where a wrong answer is unmissable:
166// every glyph must advance by the same amount.
167func TestMonoAdvancesAreUniform(t *testing.T) {
168 font, err := family(t, "mono").Face(false, false).Parsed()
169 if err != nil {
170 t.Fatal(err)
171 }
172 want := font.Advance(font.GlyphIndex('m'))
173 if want == 0 {
174 t.Fatal("no advance for 'm'")
175 }
176 for _, r := range "il.MW@" {
177 if got := font.Advance(font.GlyphIndex(r)); got != want {
178 t.Errorf("mono advance for %q = %d, want %d", r, got, want)
179 }
180 }
181}
182
183// The proportional faces must NOT be uniform — the same assertion the
184// other way round, so a bug that returned one constant width for
185// everything cannot pass both tests.
186func TestProportionalAdvancesDiffer(t *testing.T) {
187 font, err := family(t, "serif").Face(false, false).Parsed()
188 if err != nil {
189 t.Fatal(err)
190 }
191 narrow := font.Advance(font.GlyphIndex('i'))
192 wide := font.Advance(font.GlyphIndex('W'))
193 if narrow == 0 || wide == 0 || narrow >= wide {
194 t.Errorf("serif advances: i=%d W=%d, want 0 < i < W", narrow, wide)
195 }
196}
197
198func TestWidthEmScalesWithTheString(t *testing.T) {
199 font, err := family(t, "serif").Face(false, false).Parsed()
200 if err != nil {
201 t.Fatal(err)
202 }
203 one, gids := font.WidthEm("n")
204 two, _ := font.WidthEm("nn")
205 if len(gids) != 1 {
206 t.Errorf("WidthEm returned %d gids for one rune", len(gids))
207 }
208 if one <= 0 {
209 t.Fatalf("width of %q is %v", "n", one)
210 }
211 if diff := two - 2*one; diff > 1e-9 || diff < -1e-9 {
212 t.Errorf("width(nn)=%v, want 2*width(n)=%v", two, 2*one)
213 }
214}
215
216// The subset has to be a font a reader can actually use, so this
217// parses the output rather than checking that it got smaller. Glyph
218// ids must survive unchanged (the whole design — see truetype.go), the
219// kept glyphs must still have outlines, and a dropped glyph must be
220// empty rather than missing.
221func TestSubsetKeepsGlyphIdsAndOutlines(t *testing.T) {
222 face := family(t, "serif").Face(false, false)
223 font, err := face.Parsed()
224 if err != nil {
225 t.Fatal(err)
226 }
227
228 keep := map[uint16]bool{}
229 const sample = "Hello"
230 for _, r := range sample {
231 keep[font.GlyphIndex(r)] = true
232 }
233
234 sub, err := font.Subset(keep)
235 if err != nil {
236 t.Fatal(err)
237 }
238 if len(sub) >= len(face.Data) {
239 t.Errorf("subset is %d bytes, original is %d — not a subset", len(sub), len(face.Data))
240 }
241
242 reparsed, err := fonts.Parse(sub)
243 if err != nil {
244 t.Fatalf("the subset does not parse: %v", err)
245 }
246 if reparsed.NumGlyphs != font.NumGlyphs {
247 t.Errorf("subset numGlyphs=%d, want %d unchanged", reparsed.NumGlyphs, font.NumGlyphs)
248 }
249 if reparsed.UnitsPerEm != font.UnitsPerEm {
250 t.Errorf("subset unitsPerEm=%d, want %d", reparsed.UnitsPerEm, font.UnitsPerEm)
251 }
252 for _, r := range sample {
253 gid := font.GlyphIndex(r)
254 if got := reparsed.Advance(gid); got != font.Advance(gid) {
255 t.Errorf("advance for %q changed: %d -> %d", r, font.Advance(gid), got)
256 }
257 if !glyphHasOutline(t, sub, gid) {
258 t.Errorf("kept glyph for %q has no outline in the subset", r)
259 }
260 }
261
262 // A glyph nobody asked for must be gone. 'Z' is not in "Hello".
263 if gid := font.GlyphIndex('Z'); gid != 0 && glyphHasOutline(t, sub, gid) {
264 t.Errorf("glyph for 'Z' survived a subset that did not ask for it")
265 }
266}
267
268// The hinting tables travel with the glyphs. ISO 32000-1 §9.9 requires
269// cvt /fpgm/prep to be in an embedded font whose instructions need
270// them, and Liberation's glyph programs call functions defined in fpgm
271// and read values from cvt — so a subset without them is executing
272// instructions against definitions that are not in the file.
273func TestSubsetKeepsTheHintingTables(t *testing.T) {
274 face := family(t, "serif").Face(false, false)
275 font, err := face.Parsed()
276 if err != nil {
277 t.Fatal(err)
278 }
279 sub, err := font.Subset(map[uint16]bool{font.GlyphIndex('A'): true})
280 if err != nil {
281 t.Fatal(err)
282 }
283 for _, tag := range []string{"cvt ", "fpgm", "prep"} {
284 if !fontHasTable(t, sub, tag) {
285 t.Errorf("the subset dropped %q, which its glyph instructions need", tag)
286 }
287 }
288 // And it is still a subset: the hinting tables are tens of
289 // kilobytes, not hundreds.
290 if len(sub) >= len(face.Data)/2 {
291 t.Errorf("subset is %d bytes against a %d-byte face — the hinting tables should not cost that much",
292 len(sub), len(face.Data))
293 }
294}
295
296// fontHasTable reports whether a built font file carries a table.
297func fontHasTable(t *testing.T, file []byte, tag string) bool {
298 t.Helper()
299 if len(file) < 12 {
300 t.Fatal("not a font")
301 }
302 n := int(file[4])<<8 | int(file[5])
303 for i := 0; i < n; i++ {
304 rec := 12 + i*16
305 if rec+4 > len(file) {
306 break
307 }
308 if string(file[rec:rec+4]) == tag {
309 return true
310 }
311 }
312 return false
313}
314
315// A composite glyph's components must come along, or the accent
316// renders as nothing.
317func TestSubsetFollowsCompositeComponents(t *testing.T) {
318 face := family(t, "serif").Face(false, false)
319 font, err := face.Parsed()
320 if err != nil {
321 t.Fatal(err)
322 }
323 gid := font.GlyphIndex('é')
324 if gid == 0 {
325 t.Skip("no é in this face")
326 }
327 sub, err := font.Subset(map[uint16]bool{gid: true})
328 if err != nil {
329 t.Fatal(err)
330 }
331 if !glyphHasOutline(t, sub, gid) {
332 t.Fatal("é itself is missing from its own subset")
333 }
334 // 'e' was never asked for; it must still be present, because é is
335 // assembled from it. (If this face happens to draw é as a simple
336 // glyph, the assertion still holds trivially — é has an outline
337 // either way — so this cannot pass by accident on a face where
338 // there is nothing to follow.)
339 base := font.GlyphIndex('e')
340 if isComposite(t, face.Data, font, gid) && !glyphHasOutline(t, sub, base) {
341 t.Error("é is composite but its base glyph was dropped from the subset")
342 }
343}
344
345// glyphHasOutline reports whether gid occupies bytes in the file's
346// glyf table — the actual question a reader asks when it draws.
347func glyphHasOutline(t *testing.T, file []byte, gid uint16) bool {
348 t.Helper()
349 f, err := fonts.Parse(file)
350 if err != nil {
351 t.Fatalf("parse: %v", err)
352 }
353 return f.GlyphLen(gid) > 0
354}
355
356func isComposite(t *testing.T, file []byte, orig *fonts.Font, gid uint16) bool {
357 t.Helper()
358 f, err := fonts.Parse(file)
359 if err != nil {
360 t.Fatalf("parse: %v", err)
361 }
362 return f.GlyphIsComposite(gid)
363}
364
365func TestFacePathsAreUniqueAndHashed(t *testing.T) {
366 seen := map[string]bool{}
367 hashed := regexp.MustCompile(`^/static/fonts/[A-Za-z0-9-]+\.[0-9a-f]{16}\.woff2$`)
368 for _, f := range fonts.All() {
369 if !hashed.MatchString(f.Path) {
370 t.Errorf("%s: unexpected path %q", f.File, f.Path)
371 }
372 if seen[f.Path] {
373 t.Errorf("duplicate path %q", f.Path)
374 }
375 seen[f.Path] = true
376 data, kind, ok := fonts.Asset(f.Path)
377 if !ok || kind != "font/woff2" || string(data) != string(f.Web) {
378 t.Errorf("Asset(%q) does not serve %s's woff2", f.Path, f.File)
379 }
380 }
381 for _, f := range fonts.Families {
382 if !hashed.MatchString(f.PreviewPath()) || seen[f.PreviewPath()] {
383 t.Errorf("%s preview path %q", f.Name, f.PreviewPath())
384 }
385 seen[f.PreviewPath()] = true
386 }
387}
388
389// The browser and the PDF use one font program: the woff2 holds the
390// same tables as the TrueType file, in a lossless wrapper. Read the
391// woff2 table directory and compare it with the sfnt's.
392func TestTheWebFileWrapsTheSameFont(t *testing.T) {
393 for _, f := range fonts.All() {
394 w := f.Web
395 if len(w) < 48 || string(w[:4]) != "wOF2" {
396 t.Fatalf("%s: not a woff2", f.Path)
397 }
398 if binary.BigEndian.Uint32(w[4:]) != binary.BigEndian.Uint32(f.Data[0:]) {
399 t.Errorf("%s: the woff2 flavor is not the TrueType file's", f.Path)
400 }
401 woffTables := int(binary.BigEndian.Uint16(w[12:]))
402 sfntTables := int(binary.BigEndian.Uint16(f.Data[4:]))
403 // A woff2 may drop DSIG (its signature cannot survive the
404 // wrapper); nothing else.
405 if woffTables != sfntTables && woffTables != sfntTables-1 {
406 t.Errorf("%s: %d tables in the woff2, %d in the TrueType file", f.File, woffTables, sfntTables)
407 }
408 if got := binary.BigEndian.Uint32(w[16:]); int(got) < len(f.Data)*9/10 || int(got) > len(f.Data)*11/10 {
409 t.Errorf("%s: the woff2 unpacks to %d bytes, the TrueType file is %d", f.File, got, len(f.Data))
410 }
411 }
412}
413
414// The OFL (and Apache for none of these) requires the licence to travel
415// with the fonts. Each family's licence is served.
416func TestLicenceTravelsWithTheFonts(t *testing.T) {
417 paths := fonts.LicencePaths()
418 if len(paths) < 14 {
419 t.Fatalf("only %d licence files are served", len(paths))
420 }
421 for _, p := range paths {
422 data, kind, ok := fonts.Asset(p)
423 if !ok || !strings.HasPrefix(kind, "text/plain") {
424 t.Errorf("%s is not served as text", p)
425 continue
426 }
427 if !strings.Contains(strings.ToUpper(string(data)), "OPEN FONT LICENSE") {
428 t.Errorf("%s is not the OFL", p)
429 }
430 }
431}
432
433// The reserved names. The OFL forbids a modified version from using
434// them, so these families are their authors' files byte for byte; only
435// the preview subsets are cut, and those are renamed.
436func TestReservedNamesAreDeclared(t *testing.T) {
437 for _, key := range []string{"carlito", "sourcesans", "sourceserif", "plexsans", "playfair", "sans", "serif", "mono"} {
438 if family(t, key).Reserved == "" {
439 t.Errorf("%s's licence reserves its name; the manifest must say so", key)
440 }
441 }
442 for _, f := range fonts.Families {
443 if strings.Contains(f.PreviewCSSName(), f.Name) || (f.Reserved != "" && strings.Contains(f.PreviewCSSName(), f.Reserved)) {
444 t.Errorf("%s's preview subset is a modified font and must not carry the name", f.Name)
445 }
446 }
447}
448
449// The stylesheet: every face with font-display: block, never swap; the
450// default on [docs-text]; a fallback for each family that does not name
451// the private face.
452func TestTheStylesheet(t *testing.T) {
453 css := string(fonts.Stylesheet())
454 if strings.Contains(css, "swap") || strings.Contains(css, "optional") {
455 t.Error("a face that swaps is a flash of unstyled text")
456 }
457 for _, f := range fonts.All() {
458 rule := `src:url("` + f.Path + `") format("woff2");font-weight:` + map[bool]string{true: "700", false: "400"}[f.Bold()]
459 if !strings.Contains(css, rule) {
460 t.Errorf("%s is not declared", f.File)
461 }
462 }
463 // Without the gate (no JavaScript, or it never arrived) the text is
464 // in its system faces, which name no web face, so nothing is fetched
465 // for it, held or swapped (review finding 7). The web faces are on
466 // only under data-docs-faces="web", which the gate sets once they
467 // have loaded, and never for a family it committed.
468 if !strings.Contains(css, "\n[docs-text]{font-family:"+fonts.Default.FallbackCSS()+";font-synthesis:none}") {
469 t.Error("[docs-text]'s own rule is not the system faces")
470 }
471 for _, line := range strings.Split(css, "\n") {
472 if strings.Contains(line, `"Docs `) && !strings.HasPrefix(line, "@font-face") &&
473 !strings.HasPrefix(line, `html[data-docs-faces="web"]:not([data-docs-fonts-fallback~=`) &&
474 !strings.HasPrefix(line, `html[data-docs-previews="web"]`) {
475 t.Errorf("a rule uses a web face without the gate having turned it on: %s", line)
476 }
477 }
478 if !strings.Contains(css, `html[data-docs-faces="web"]:not([data-docs-fonts-fallback~="carlito"]) [docs-text]{font-family:"Docs Carlito", "Calibri"`) {
479 t.Error("[docs-text] is not set in Docs Carlito once the web faces are on")
480 }
481 if !strings.Contains(css, `@media screen{html[data-docs-fonts="pending"] [docs-page]{visibility:hidden}}`) {
482 t.Error("the hold is not screen-only on <html>")
483 }
484 if got := strings.Count(css, "font-display:block"); got != len(fonts.All())+len(fonts.Families) {
485 t.Errorf("%d faces block, want every face and every preview", got)
486 }
487 for _, f := range fonts.Families {
488 if strings.Contains(f.FallbackCSS(), "Docs ") {
489 t.Errorf("%s's fallback names a private face, which would swap in when it arrived", f.Name)
490 }
491 }
492 data, kind, ok := fonts.Asset(fonts.StylesheetPath())
493 if !ok || string(data) != css || !strings.HasPrefix(kind, "text/css") {
494 t.Error("the stylesheet is not served at its path")
495 }
496}
497