meta.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package fonts
  2. /*
  3. meta.go
  4. Checks that a decoded font is complete and reads what the font library
  5. shows about it: names, weight range, style, glyph count, the codepoints it
  6. covers and which writing systems those make up.
  7. */
  8. import (
  9. "encoding/binary"
  10. "errors"
  11. "fmt"
  12. "sort"
  13. "strings"
  14. "unicode"
  15. "unicode/utf16"
  16. )
  17. // Info describes one font file
  18. type Info struct {
  19. Family string `json:"family"`
  20. Style string `json:"style"`
  21. FullName string `json:"fullName"`
  22. Version string `json:"version"`
  23. Designer string `json:"designer"`
  24. License string `json:"license"`
  25. LicenseURL string `json:"licenseURL"`
  26. WeightMin int `json:"weightMin"`
  27. WeightMax int `json:"weightMax"`
  28. Italic bool `json:"italic"`
  29. Variable bool `json:"variable"`
  30. Outline string `json:"outline"` // "truetype" or "cff"
  31. NoEmbed bool `json:"noEmbed"` // the licence forbids embedding it in a document (OS/2 fsType)
  32. Glyphs int `json:"glyphs"`
  33. Codepoints int `json:"codepoints"`
  34. Scripts []string `json:"scripts"`
  35. }
  36. // Inspect validates a decoded font and reads its description and character
  37. // map. It fails for fonts a browser could not use.
  38. func Inspect(font *Font) (Info, map[uint32]uint16, error) {
  39. var info Info
  40. for _, tag := range []string{"cmap", "head", "hhea", "maxp", "name"} {
  41. if font.Table(tag) == nil {
  42. return info, nil, fmt.Errorf("the font has no %q table", tag)
  43. }
  44. }
  45. if !font.Has("hmtx") {
  46. return info, nil, errors.New(`the font has no "hmtx" table`)
  47. }
  48. head := font.Table("head")
  49. if len(head) < 54 || binary.BigEndian.Uint32(head[12:]) != headMagic {
  50. return info, nil, errors.New("the head table is damaged")
  51. }
  52. if upem := binary.BigEndian.Uint16(head[18:]); upem < 16 || upem > 16384 {
  53. return info, nil, fmt.Errorf("the font has an invalid unitsPerEm (%d)", upem)
  54. }
  55. numGlyphs, err := u16(font.Table("maxp"), 4)
  56. if err != nil || numGlyphs == 0 {
  57. return info, nil, errors.New("the maxp table is damaged")
  58. }
  59. info.Glyphs = int(numGlyphs)
  60. switch {
  61. case font.Has("glyf") && font.Has("loca"):
  62. info.Outline = "truetype"
  63. if !font.Transformed["glyf"] {
  64. if _, err := glyphOffsets(font, info.Glyphs); err != nil {
  65. return info, nil, err
  66. }
  67. }
  68. case font.Has("CFF ") || font.Has("CFF2"):
  69. info.Outline = "cff"
  70. default:
  71. return info, nil, errNoOutline
  72. }
  73. if !font.Transformed["hmtx"] {
  74. hhea := font.Table("hhea")
  75. if len(hhea) < 36 {
  76. return info, nil, errors.New("the hhea table is damaged")
  77. }
  78. numH := int(binary.BigEndian.Uint16(hhea[34:]))
  79. if numH == 0 || numH > info.Glyphs || len(font.Table("hmtx")) < 4*numH+2*(info.Glyphs-numH) {
  80. return info, nil, errors.New("the hmtx table does not match the glyph count")
  81. }
  82. }
  83. names, err := readNames(font.Table("name"))
  84. if err != nil {
  85. return info, nil, err
  86. }
  87. info.Family = firstOf(names[16], names[1])
  88. info.Style = firstOf(names[17], names[2], "Regular")
  89. info.FullName = firstOf(names[4], strings.TrimSpace(info.Family+" "+info.Style))
  90. info.Version = strings.TrimSpace(strings.TrimPrefix(names[5], "Version"))
  91. info.Designer = firstOf(names[9], names[8])
  92. info.License = clip(names[13], 600)
  93. info.LicenseURL = names[14]
  94. if info.Family == "" {
  95. return info, nil, errMissingName
  96. }
  97. info.WeightMin, info.WeightMax = 400, 400
  98. if os2 := font.Table("OS/2"); len(os2) >= 64 {
  99. w := int(binary.BigEndian.Uint16(os2[4:]))
  100. if w >= 1 && w <= 9 {
  101. w *= 100 // some old fonts use the 1-9 scale
  102. }
  103. if w >= 1 && w <= 1000 {
  104. info.WeightMin, info.WeightMax = w, w
  105. }
  106. info.Italic = binary.BigEndian.Uint16(os2[62:])&1 != 0
  107. }
  108. if binary.BigEndian.Uint16(head[44:])&2 != 0 {
  109. info.Italic = true
  110. }
  111. if os2 := font.Table("OS/2"); len(os2) >= 10 {
  112. info.NoEmbed = noEmbed(binary.BigEndian.Uint16(os2[8:]))
  113. }
  114. if fvar := font.Table("fvar"); fvar != nil {
  115. info.Variable = true
  116. if lo, hi, ok := weightAxis(fvar); ok {
  117. info.WeightMin, info.WeightMax = lo, hi
  118. // the names describe the default instance ("ExtraLight"), not the font
  119. info.Style = "Regular"
  120. if info.Italic {
  121. info.Style = "Italic"
  122. }
  123. }
  124. }
  125. cmap, err := ParseCmap(font.Table("cmap"), info.Glyphs)
  126. if err != nil {
  127. return info, nil, err
  128. }
  129. info.Codepoints = len(cmap)
  130. info.Scripts = scriptsOf(cmap)
  131. return info, cmap, nil
  132. }
  133. // noEmbed reads the OS/2 fsType embedding permissions: a font with only the
  134. // Restricted License bit of the usage bits set, or one that allows bitmaps
  135. // alone, must not be embedded in a document. Old fonts may set several
  136. // usage bits; the least restrictive one applies.
  137. func noEmbed(fsType uint16) bool {
  138. return fsType&0x000F == 0x0002 || fsType&0x0200 != 0
  139. }
  140. // glyphOffsets reads loca: glyph i occupies glyf[offsets[i]:offsets[i+1]]
  141. func glyphOffsets(font *Font, numGlyphs int) ([]uint32, error) {
  142. head, loca, glyf := font.Table("head"), font.Table("loca"), font.Table("glyf")
  143. long := len(head) >= 52 && binary.BigEndian.Uint16(head[50:]) == 1
  144. size := 2
  145. if long {
  146. size = 4
  147. }
  148. if len(loca) < (numGlyphs+1)*size {
  149. return nil, errors.New("the loca table is shorter than the glyph count")
  150. }
  151. offsets := make([]uint32, numGlyphs+1)
  152. for i := range offsets {
  153. if long {
  154. offsets[i] = binary.BigEndian.Uint32(loca[4*i:])
  155. } else {
  156. offsets[i] = uint32(binary.BigEndian.Uint16(loca[2*i:])) * 2
  157. }
  158. if i > 0 && offsets[i] < offsets[i-1] {
  159. return nil, errors.New("the loca table is out of order")
  160. }
  161. }
  162. if int64(offsets[numGlyphs]) > int64(len(glyf)) {
  163. return nil, errors.New("the loca table points past the glyf table")
  164. }
  165. return offsets, nil
  166. }
  167. func weightAxis(fvar []byte) (int, int, bool) {
  168. axesOffset, err1 := u16(fvar, 4)
  169. count, err2 := u16(fvar, 8)
  170. size, err3 := u16(fvar, 10)
  171. if err1 != nil || err2 != nil || err3 != nil || size < 20 {
  172. return 0, 0, false
  173. }
  174. for i := 0; i < int(count); i++ {
  175. rec, err := sub(fvar, int64(axesOffset)+int64(i)*int64(size), 20)
  176. if err != nil {
  177. return 0, 0, false
  178. }
  179. if string(rec[:4]) != "wght" {
  180. continue
  181. }
  182. lo := int(int32(binary.BigEndian.Uint32(rec[4:])) >> 16)
  183. hi := int(int32(binary.BigEndian.Uint32(rec[12:])) >> 16)
  184. if lo < 1 || hi > 1000 || lo > hi {
  185. return 0, 0, false
  186. }
  187. return lo, hi, true
  188. }
  189. return 0, 0, false
  190. }
  191. // readNames returns the best English (or first) string for each name id
  192. func readNames(table []byte) (map[uint16]string, error) {
  193. count, err1 := u16(table, 2)
  194. strOffset, err2 := u16(table, 4)
  195. if err1 != nil || err2 != nil {
  196. return nil, errors.New("the name table is damaged")
  197. }
  198. type pick struct {
  199. rank int
  200. text string
  201. }
  202. best := map[uint16]pick{}
  203. for i := 0; i < int(count); i++ {
  204. rec, err := sub(table, 6+12*int64(i), 12)
  205. if err != nil {
  206. return nil, errors.New("the name table is damaged")
  207. }
  208. platform := binary.BigEndian.Uint16(rec)
  209. encoding := binary.BigEndian.Uint16(rec[2:])
  210. language := binary.BigEndian.Uint16(rec[4:])
  211. id := binary.BigEndian.Uint16(rec[6:])
  212. length := binary.BigEndian.Uint16(rec[8:])
  213. offset := binary.BigEndian.Uint16(rec[10:])
  214. raw, err := sub(table, int64(strOffset)+int64(offset), int64(length))
  215. if err != nil {
  216. continue
  217. }
  218. rank, text := 0, ""
  219. switch {
  220. case platform == 3 && (encoding == 1 || encoding == 10):
  221. rank, text = 3, decodeUTF16(raw)
  222. if language == 0x0409 {
  223. rank = 4
  224. }
  225. case platform == 0:
  226. rank, text = 2, decodeUTF16(raw)
  227. case platform == 1 && encoding == 0:
  228. rank, text = 1, latin1(raw)
  229. if language == 0 {
  230. rank = 2
  231. }
  232. }
  233. text = clean(text)
  234. if rank > 0 && text != "" && rank > best[id].rank {
  235. best[id] = pick{rank, text}
  236. }
  237. }
  238. names := map[uint16]string{}
  239. for id, p := range best {
  240. names[id] = p.text
  241. }
  242. return names, nil
  243. }
  244. func decodeUTF16(b []byte) string {
  245. units := make([]uint16, len(b)/2)
  246. for i := range units {
  247. units[i] = binary.BigEndian.Uint16(b[2*i:])
  248. }
  249. return string(utf16.Decode(units))
  250. }
  251. func latin1(b []byte) string {
  252. r := make([]rune, len(b))
  253. for i, c := range b {
  254. r[i] = rune(c)
  255. }
  256. return string(r)
  257. }
  258. // clean drops control characters and trims a name to a sane length
  259. func clean(s string) string {
  260. s = strings.Map(func(r rune) rune {
  261. if unicode.IsControl(r) || r == unicode.ReplacementChar {
  262. return -1
  263. }
  264. return r
  265. }, s)
  266. return clip(strings.TrimSpace(s), 200)
  267. }
  268. func clip(s string, n int) string {
  269. r := []rune(s)
  270. if len(r) > n {
  271. return string(r[:n]) + "…"
  272. }
  273. return s
  274. }
  275. func firstOf(values ...string) string {
  276. for _, v := range values {
  277. if v != "" {
  278. return v
  279. }
  280. }
  281. return ""
  282. }
  283. // scriptRanges decides which writing systems a font covers: at least min
  284. // codepoints of the range must be mapped
  285. var scriptRanges = []struct {
  286. id string
  287. lo, hi uint32
  288. min int
  289. }{
  290. {"latin", 0x41, 0x7A, 50},
  291. {"greek", 0x391, 0x3C9, 40},
  292. {"cyrillic", 0x410, 0x44F, 60},
  293. {"hebrew", 0x5D0, 0x5EA, 27},
  294. {"arabic", 0x600, 0x6FF, 100},
  295. {"devanagari", 0x900, 0x97F, 80},
  296. {"thai", 0xE01, 0xE5B, 70},
  297. {"kana", 0x3041, 0x30FA, 150},
  298. {"han", 0x4E00, 0x9FFF, 3000},
  299. {"hangul", 0xAC00, 0xD7A3, 2000},
  300. }
  301. func scriptsOf(cmap map[uint32]uint16) []string {
  302. counts := make([]int, len(scriptRanges))
  303. for cp := range cmap {
  304. for i, s := range scriptRanges {
  305. if cp >= s.lo && cp <= s.hi {
  306. counts[i]++
  307. }
  308. }
  309. }
  310. scripts := []string{}
  311. for i, s := range scriptRanges {
  312. if counts[i] >= s.min {
  313. scripts = append(scripts, s.id)
  314. }
  315. }
  316. return scripts
  317. }
  318. // sortedCodepoints returns the keys of a character map in ascending order
  319. func sortedCodepoints(cmap map[uint32]uint16) []uint32 {
  320. cps := make([]uint32, 0, len(cmap))
  321. for cp := range cmap {
  322. cps = append(cps, cp)
  323. }
  324. sort.Slice(cps, func(i, j int) bool { return cps[i] < cps[j] })
  325. return cps
  326. }