fonts_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package fonts
  2. import (
  3. "bytes"
  4. "compress/zlib"
  5. "encoding/binary"
  6. "reflect"
  7. "testing"
  8. "golang.org/x/image/font/gofont/goregular"
  9. )
  10. // goFont is a small, permissively licensed TrueType font to test with
  11. func goFont(t *testing.T) []byte {
  12. t.Helper()
  13. return append([]byte(nil), goregular.TTF...)
  14. }
  15. // makeWOFF packs an sfnt into a WOFF 1.0 file, compressing every table
  16. func makeWOFF(t *testing.T, sfnt []byte) []byte {
  17. t.Helper()
  18. font, err := ParseSFNT(sfnt)
  19. if err != nil {
  20. t.Fatalf("ParseSFNT: %v", err)
  21. }
  22. tags := sortedTags(font.Tables)
  23. header := make([]byte, 44+20*len(tags))
  24. binary.BigEndian.PutUint32(header, sigWOFF)
  25. binary.BigEndian.PutUint32(header[4:], font.Flavor)
  26. binary.BigEndian.PutUint16(header[12:], uint16(len(tags)))
  27. var data []byte
  28. for i, tag := range tags {
  29. table := font.Tables[tag]
  30. var z bytes.Buffer
  31. w := zlib.NewWriter(&z)
  32. w.Write(table)
  33. w.Close()
  34. stored := z.Bytes()
  35. if len(stored) >= len(table) {
  36. stored = table
  37. }
  38. rec := header[44+20*i:]
  39. copy(rec, tag)
  40. binary.BigEndian.PutUint32(rec[4:], uint32(len(header)+len(data)))
  41. binary.BigEndian.PutUint32(rec[8:], uint32(len(stored)))
  42. binary.BigEndian.PutUint32(rec[12:], uint32(len(table)))
  43. data = append(data, stored...)
  44. for len(data)%4 != 0 {
  45. data = append(data, 0)
  46. }
  47. }
  48. out := append(header, data...)
  49. binary.BigEndian.PutUint32(out[8:], uint32(len(out)))
  50. return out
  51. }
  52. func TestDecodeDetectsContainers(t *testing.T) {
  53. sfnt := goFont(t)
  54. collection := append([]byte("ttcf"), make([]byte, 40)...)
  55. tests := []struct {
  56. name string
  57. data []byte
  58. container string
  59. wantErr bool
  60. }{
  61. {"truetype", sfnt, "sfnt", false},
  62. {"woff", makeWOFF(t, sfnt), "woff", false},
  63. {"collection", collection, "", true},
  64. {"garbage", []byte("definitely not a font file"), "", true},
  65. {"empty", nil, "", true},
  66. {"truncated directory", sfnt[:40], "", true},
  67. }
  68. for _, tt := range tests {
  69. t.Run(tt.name, func(t *testing.T) {
  70. _, container, err := Decode(tt.data)
  71. if (err != nil) != tt.wantErr {
  72. t.Fatalf("Decode error = %v, wantErr %v", err, tt.wantErr)
  73. }
  74. if !tt.wantErr && container != tt.container {
  75. t.Errorf("container = %q, want %q", container, tt.container)
  76. }
  77. })
  78. }
  79. }
  80. func TestInspectReadsNamesAndCoverage(t *testing.T) {
  81. font, _, err := Decode(goFont(t))
  82. if err != nil {
  83. t.Fatalf("Decode: %v", err)
  84. }
  85. info, cmap, err := Inspect(font)
  86. if err != nil {
  87. t.Fatalf("Inspect: %v", err)
  88. }
  89. if info.Family != "Go" || info.Style != "Regular" {
  90. t.Errorf("family/style = %q/%q, want Go/Regular", info.Family, info.Style)
  91. }
  92. if info.WeightMin != 400 || info.WeightMax != 400 || info.Italic || info.Variable {
  93. t.Errorf("weight %d-%d italic %v variable %v, want 400-400 upright static", info.WeightMin, info.WeightMax, info.Italic, info.Variable)
  94. }
  95. if info.Outline != "truetype" || info.Glyphs == 0 {
  96. t.Errorf("outline %q glyphs %d", info.Outline, info.Glyphs)
  97. }
  98. if cmap['A'] == 0 || info.Codepoints != len(cmap) {
  99. t.Errorf("cmap misses 'A' or count %d != %d", info.Codepoints, len(cmap))
  100. }
  101. if len(info.Scripts) == 0 || info.Scripts[0] != "latin" {
  102. t.Errorf("scripts = %v, want latin first", info.Scripts)
  103. }
  104. }
  105. func TestInspectRejectsIncompleteFonts(t *testing.T) {
  106. tests := []struct {
  107. name string
  108. drop string
  109. }{
  110. {"no cmap", "cmap"},
  111. {"no name", "name"},
  112. {"no outlines", "glyf"},
  113. {"no metrics", "hmtx"},
  114. }
  115. for _, tt := range tests {
  116. t.Run(tt.name, func(t *testing.T) {
  117. font, err := ParseSFNT(goFont(t))
  118. if err != nil {
  119. t.Fatalf("ParseSFNT: %v", err)
  120. }
  121. delete(font.Tables, tt.drop)
  122. if _, _, err := Inspect(font); err == nil {
  123. t.Errorf("Inspect without %q succeeded", tt.drop)
  124. }
  125. })
  126. }
  127. }
  128. func TestCmapRoundTrip(t *testing.T) {
  129. mappings := []Mapping{
  130. {0x41, 3}, {0x42, 4}, {0x43, 9}, // a run with non consecutive glyphs
  131. {0x4E00, 100}, {0x4E01, 101}, // consecutive both ways
  132. {0xFF01, 7},
  133. {0x20000, 200}, {0x20001, 201}, // beyond the BMP: format 12 only
  134. }
  135. table := BuildCmap(mappings)
  136. got, err := ParseCmap(table, 1000)
  137. if err != nil {
  138. t.Fatalf("ParseCmap: %v", err)
  139. }
  140. if len(got) != len(mappings) {
  141. t.Fatalf("got %d mappings, want %d", len(got), len(mappings))
  142. }
  143. for _, m := range mappings {
  144. if got[m.Codepoint] != m.Glyph {
  145. t.Errorf("U+%X -> %d, want %d", m.Codepoint, got[m.Codepoint], m.Glyph)
  146. }
  147. }
  148. // the format 4 subtable alone must agree for the BMP
  149. f4 := buildFormat4(mappings[:6])
  150. single := append([]byte{0, 0, 0, 1, 0, 3, 0, 1, 0, 0, 0, 12}, f4...)
  151. bmp, err := ParseCmap(single, 1000)
  152. if err != nil {
  153. t.Fatalf("ParseCmap(format 4): %v", err)
  154. }
  155. for _, m := range mappings[:6] {
  156. if bmp[m.Codepoint] != m.Glyph {
  157. t.Errorf("format 4: U+%X -> %d, want %d", m.Codepoint, bmp[m.Codepoint], m.Glyph)
  158. }
  159. }
  160. }
  161. func TestParseCmapDropsOutOfRangeGlyphs(t *testing.T) {
  162. table := BuildCmap([]Mapping{{0x41, 5}, {0x42, 50}})
  163. got, err := ParseCmap(table, 10)
  164. if err != nil {
  165. t.Fatalf("ParseCmap: %v", err)
  166. }
  167. if _, ok := got[0x42]; ok || got[0x41] != 5 {
  168. t.Errorf("got %v, want only U+41 -> 5", got)
  169. }
  170. }
  171. func TestWOFFDecodesToSameTables(t *testing.T) {
  172. sfnt := goFont(t)
  173. want, _ := ParseSFNT(sfnt)
  174. got, container, err := Decode(makeWOFF(t, sfnt))
  175. if err != nil || container != "woff" {
  176. t.Fatalf("Decode(woff) = %v, %q", err, container)
  177. }
  178. if !reflect.DeepEqual(got.Tables, want.Tables) {
  179. t.Error("WOFF tables differ from the sfnt ones")
  180. }
  181. }
  182. func TestWOFF2RoundTrip(t *testing.T) {
  183. want, _ := ParseSFNT(goFont(t))
  184. woff2, err := EncodeWOFF2(want.Flavor, want.Tables, 5)
  185. if err != nil {
  186. t.Fatalf("EncodeWOFF2: %v", err)
  187. }
  188. if len(woff2)%4 != 0 || int(binary.BigEndian.Uint32(woff2[8:])) != len(woff2) {
  189. t.Errorf("length field %d, file %d bytes", binary.BigEndian.Uint32(woff2[8:]), len(woff2))
  190. }
  191. if int(binary.BigEndian.Uint32(woff2[16:])) != sfntSize(want.Tables) {
  192. t.Error("totalSfntSize does not match the tables")
  193. }
  194. got, container, err := Decode(woff2)
  195. if err != nil || container != "woff2" {
  196. t.Fatalf("Decode(woff2) = %v, %q", err, container)
  197. }
  198. if len(got.Transformed) != 0 {
  199. t.Errorf("tables marked transformed: %v", got.Transformed)
  200. }
  201. if !reflect.DeepEqual(got.Tables, want.Tables) {
  202. t.Error("WOFF2 tables differ after a round trip")
  203. }
  204. }
  205. func TestBase128(t *testing.T) {
  206. for _, v := range []uint32{0, 1, 127, 128, 16383, 16384, 1 << 28, 0xFFFFFFFF} {
  207. enc := appendBase128(nil, v)
  208. off := 0
  209. got, err := readBase128(enc, &off)
  210. if err != nil || got != v || off != len(enc) {
  211. t.Errorf("round trip %d: got %d, %v, read %d of %d bytes", v, got, err, off, len(enc))
  212. }
  213. }
  214. bad := [][]byte{
  215. {0x80, 0x01}, // leading zero
  216. {0xFF, 0xFF, 0xFF, 0xFF, 0x7F}, // overflows 32 bits
  217. {0x81, 0x81, 0x81, 0x81, 0x81}, // never ends
  218. {0x81}, // truncated
  219. }
  220. for _, b := range bad {
  221. off := 0
  222. if _, err := readBase128(b, &off); err == nil {
  223. t.Errorf("readBase128(% x) succeeded", b)
  224. }
  225. }
  226. }
  227. func TestAssembleSFNTChecksums(t *testing.T) {
  228. font, _ := ParseSFNT(goFont(t))
  229. tables := map[string][]byte{}
  230. for tag, data := range font.Tables {
  231. tables[tag] = data
  232. }
  233. out, err := AssembleSFNT(font.Flavor, tables)
  234. if err != nil {
  235. t.Fatalf("AssembleSFNT: %v", err)
  236. }
  237. if checksum(out) != 0xB1B0AFBA {
  238. t.Errorf("file checksum %08x, want B1B0AFBA", checksum(out))
  239. }
  240. again, err := ParseSFNT(out)
  241. if err != nil || len(again.Tables) != len(font.Tables) {
  242. t.Fatalf("reparse: %v", err)
  243. }
  244. }
  245. /* ── GSUB ── */
  246. // builder writes big endian values and patches offsets
  247. type builder struct{ b []byte }
  248. func (w *builder) u16(values ...int) {
  249. for _, v := range values {
  250. w.b = binary.BigEndian.AppendUint16(w.b, uint16(v))
  251. }
  252. }
  253. func (w *builder) tag(s string) { w.b = append(w.b, s...) }
  254. func (w *builder) pos() int { return len(w.b) }
  255. func (w *builder) set16(at, v int) {
  256. binary.BigEndian.PutUint16(w.b[at:], uint16(v))
  257. }
  258. // testGSUB holds: liga f(10)+i(11) -> fi(50); calt chaining context on
  259. // B(20) running nested single subst B -> B.alt(60); salt A(30) -> 70
  260. func testGSUB() []byte {
  261. w := &builder{}
  262. w.u16(1, 0, 10, 12, 0) // version, scriptList, featureList, lookupList (patched)
  263. w.u16(0) // ScriptList: no scripts
  264. features := w.pos()
  265. w.u16(3)
  266. recs := []struct {
  267. tag string
  268. lookup int
  269. }{{"liga", 0}, {"calt", 1}, {"salt", 2}}
  270. for range recs {
  271. w.tag("xxxx")
  272. w.u16(0)
  273. }
  274. for i, r := range recs {
  275. copy(w.b[features+2+6*i:], r.tag)
  276. w.set16(features+2+6*i+4, w.pos()-features)
  277. w.u16(0, 1, r.lookup)
  278. }
  279. lookups := w.pos()
  280. w.set16(8, lookups)
  281. w.u16(4, 0, 0, 0, 0)
  282. lookup := func(i, kind int) int {
  283. w.set16(lookups+2+2*i, w.pos()-lookups)
  284. start := w.pos()
  285. w.u16(kind, 0, 1, 8)
  286. return start
  287. }
  288. coverage := func(subtable, field int, glyph int) {
  289. w.set16(field, w.pos()-subtable)
  290. w.u16(1, 1, glyph)
  291. }
  292. // 0: ligature f + i -> fi
  293. lookup(0, 4)
  294. sub := w.pos()
  295. w.u16(1, 0, 1, 0)
  296. coverage(sub, sub+2, 10)
  297. w.set16(sub+6, w.pos()-sub)
  298. set := w.pos()
  299. w.u16(1, 4)
  300. _ = set
  301. w.u16(50, 2, 11)
  302. // 1: chaining context format 3 on B, nested lookup 3
  303. lookup(1, 6)
  304. sub = w.pos()
  305. w.u16(3, 0, 1, 0, 0, 1, 0, 3) // format, backtrack 0, input 1 (cov patched), lookahead 0, 1 record (seq 0, lookup 3)
  306. coverage(sub, sub+6, 20)
  307. // 2: salt, single format 1 delta +40
  308. lookup(2, 1)
  309. sub = w.pos()
  310. w.u16(1, 0, 40)
  311. coverage(sub, sub+2, 30)
  312. // 3: nested, single format 2 B -> 60
  313. lookup(3, 1)
  314. sub = w.pos()
  315. w.u16(2, 0, 1, 60)
  316. coverage(sub, sub+2, 20)
  317. return w.b
  318. }
  319. func TestParseGSUBFollowsDefaultFeatures(t *testing.T) {
  320. rules, err := parseGSUB(testGSUB(), 100)
  321. if err != nil {
  322. t.Fatalf("parseGSUB: %v", err)
  323. }
  324. tests := []struct {
  325. name string
  326. start []int
  327. want []int
  328. absent []int
  329. }{
  330. {"ligature needs every component", []int{10}, nil, []int{50}},
  331. {"ligature with both components", []int{10, 11}, []int{50}, nil},
  332. {"nested contextual lookup", []int{20}, []int{60}, nil},
  333. {"optional feature not followed", []int{30}, nil, []int{70}},
  334. }
  335. for _, tt := range tests {
  336. t.Run(tt.name, func(t *testing.T) {
  337. keep := make([]bool, 100)
  338. for _, g := range tt.start {
  339. keep[g] = true
  340. }
  341. rules.closure(keep)
  342. for _, g := range tt.want {
  343. if !keep[g] {
  344. t.Errorf("glyph %d not reached", g)
  345. }
  346. }
  347. for _, g := range tt.absent {
  348. if keep[g] {
  349. t.Errorf("glyph %d reached", g)
  350. }
  351. }
  352. })
  353. }
  354. }
  355. func TestParseGSUBToleratesDamage(t *testing.T) {
  356. table := testGSUB()
  357. for cut := 0; cut < len(table); cut++ {
  358. parseGSUB(table[:cut], 100) // must not panic
  359. }
  360. for i := range table {
  361. damaged := append([]byte(nil), table...)
  362. damaged[i] ^= 0xFF
  363. parseGSUB(damaged, 100)
  364. }
  365. }
  366. func TestComponents(t *testing.T) {
  367. glyph := []byte{0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0} // numberOfContours -1, bbox
  368. // component 1: words args, a scale, more components
  369. glyph = binary.BigEndian.AppendUint16(glyph, 0x0001|0x0008|0x0020)
  370. glyph = binary.BigEndian.AppendUint16(glyph, 7)
  371. glyph = append(glyph, 0, 0, 0, 0, 0x40, 0)
  372. // component 2: byte args, last
  373. glyph = binary.BigEndian.AppendUint16(glyph, 0)
  374. glyph = binary.BigEndian.AppendUint16(glyph, 9)
  375. glyph = append(glyph, 0, 0)
  376. if got := components(glyph); !reflect.DeepEqual(got, []uint16{7, 9}) {
  377. t.Errorf("components = %v, want [7 9]", got)
  378. }
  379. if got := components([]byte{0, 1, 0, 0, 0, 0, 0, 0, 0, 0}); got != nil {
  380. t.Errorf("simple glyph has components %v", got)
  381. }
  382. if got := components(glyph[:13]); len(got) > 1 {
  383. t.Errorf("truncated composite yields %v", got)
  384. }
  385. }
  386. func TestSliceGvar(t *testing.T) {
  387. // 3 glyphs, 1 axis, 1 shared tuple, short offsets
  388. gvar := []byte{0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 28, 0, 3, 0, 0, 0, 0, 0, 30}
  389. gvar = binary.BigEndian.AppendUint16(gvar, 0) // offsets / 2
  390. gvar = binary.BigEndian.AppendUint16(gvar, 2)
  391. gvar = binary.BigEndian.AppendUint16(gvar, 3)
  392. gvar = binary.BigEndian.AppendUint16(gvar, 5)
  393. gvar = append(gvar, 0x40, 0) // shared tuple at 28
  394. gvar = append(gvar, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3) // data at 30: 4 + 2 + 4 bytes
  395. out, err := sliceGvar(gvar, []bool{true, false, true})
  396. if err != nil {
  397. t.Fatalf("sliceGvar: %v", err)
  398. }
  399. if binary.BigEndian.Uint16(out[14:])&1 == 0 {
  400. t.Error("output does not use long offsets")
  401. }
  402. shared := binary.BigEndian.Uint32(out[8:])
  403. if !bytes.Equal(out[shared:shared+2], []byte{0x40, 0}) {
  404. t.Error("shared tuples not copied")
  405. }
  406. base := binary.BigEndian.Uint32(out[16:])
  407. offs := make([]uint32, 4)
  408. for i := range offs {
  409. offs[i] = binary.BigEndian.Uint32(out[20+4*i:])
  410. }
  411. if want := []uint32{0, 4, 4, 8}; !reflect.DeepEqual(offs, want) {
  412. t.Fatalf("offsets = %v, want %v", offs, want)
  413. }
  414. if !bytes.Equal(out[base:base+8], []byte{1, 1, 1, 1, 3, 3, 3, 3}) {
  415. t.Errorf("data = % x", out[base:base+8])
  416. }
  417. if _, err := sliceGvar(gvar, []bool{true}); err == nil {
  418. t.Error("glyph count mismatch accepted")
  419. }
  420. }
  421. func TestUnicodeRange(t *testing.T) {
  422. tests := []struct {
  423. cps []uint32
  424. gap uint32
  425. want string
  426. }{
  427. {nil, 0, ""},
  428. {[]uint32{0x41}, 0, "U+41"},
  429. {[]uint32{0x41, 0x42, 0x43, 0x50}, 0, "U+41-43, U+50"},
  430. {[]uint32{0x41, 0x42, 0x43, 0x50}, 16, "U+41-50"},
  431. }
  432. for _, tt := range tests {
  433. if got := unicodeRange(tt.cps, tt.gap); got != tt.want {
  434. t.Errorf("unicodeRange(%v, %d) = %q, want %q", tt.cps, tt.gap, got, tt.want)
  435. }
  436. }
  437. }