sources.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package fonts
  2. /*
  3. sources.go
  4. The library as documents use it. The Office apps set text in an
  5. installed family by its own name, the way they use the faces they ship:
  6. a page declares every face itself from Sources (the slice files
  7. fonts.css names, each with its unicode-range), and the Office PDF export
  8. embeds the whole font from FileData, the way it embeds a shipped face.
  9. Both only need a login - any user may set text in the system fonts. Only
  10. an administrator installs or removes them (manage.go).
  11. A face is handed over whole only when a document may embed it: its
  12. licence allows that (OS/2 fsType, Info.NoEmbed), and its tables are all
  13. here (a WOFF2 upload with transformed glyph tables is served to the
  14. browser as it is, but cannot be rebuilt into a font file here).
  15. The file handed over is the installed one when it can be, else a copy
  16. made once and kept in the cache folder: a WOFF / WOFF2 upload unpacked,
  17. and a TrueType font whose glyphs are not padded to an even length padded
  18. (padGlyphs). The font is the same; the padding is for fontkit, which the
  19. PDF export subsets with: it pads each glyph it copies in loca but not in
  20. glyf, so after the first odd-length glyph every glyph of the subset was
  21. read a byte off and drew garbage, or nothing.
  22. */
  23. import (
  24. "encoding/binary"
  25. "errors"
  26. "net/http"
  27. "os"
  28. "path/filepath"
  29. "sort"
  30. "strings"
  31. "sync"
  32. )
  33. // SliceView is one file a face is loaded from and the characters it holds
  34. type SliceView struct {
  35. Name string `json:"name"` // slice/<key>/<name>.woff2 below the fonts folder
  36. Range string `json:"range"` // CSS unicode-range, "" for the whole font
  37. }
  38. // SourceFace is one face of a family as a page declares it
  39. type SourceFace struct {
  40. Key string `json:"key"`
  41. Style string `json:"style"`
  42. WeightMin int `json:"weightMin"`
  43. WeightMax int `json:"weightMax"`
  44. Italic bool `json:"italic"`
  45. Variable bool `json:"variable"`
  46. Embed bool `json:"embed"` // a document may embed it (FileData)
  47. File string `json:"file"` // the whole font below the fonts folder, "" without Embed
  48. Slices []SliceView `json:"slices"`
  49. }
  50. // SourceFamily is one installed family and its faces
  51. type SourceFamily struct {
  52. Name string `json:"name"`
  53. Faces []SourceFace `json:"faces"`
  54. }
  55. // embeddable reports whether a document may carry the face
  56. func embeddable(f *Face) bool {
  57. return f.plain && !f.Info.NoEmbed
  58. }
  59. // fileExt is the extension FileData's font goes by
  60. func fileExt(f *Face) string {
  61. if f.Info.Outline == "cff" {
  62. return ".otf"
  63. }
  64. return ".ttf"
  65. }
  66. // Sources lists every installed family with the files of its faces
  67. func (l *Library) Sources() []SourceFamily {
  68. l.mu.RLock()
  69. defer l.mu.RUnlock()
  70. out := make([]SourceFamily, 0, len(l.families))
  71. for _, fam := range l.families {
  72. sf := SourceFamily{Name: fam.Name, Faces: []SourceFace{}}
  73. for _, f := range fam.Faces {
  74. v := SourceFace{
  75. Key: f.Key, Style: f.Info.Style,
  76. WeightMin: f.Info.WeightMin, WeightMax: f.Info.WeightMax,
  77. Italic: f.Info.Italic, Variable: f.Info.Variable,
  78. Embed: embeddable(f), Slices: []SliceView{},
  79. }
  80. if v.Embed {
  81. v.File = "file/" + f.Key + fileExt(f)
  82. }
  83. if f.sliced {
  84. for _, c := range f.cold {
  85. v.Slices = append(v.Slices, SliceView{Name: c.name, Range: c.ranges})
  86. }
  87. } else {
  88. v.Slices = append(v.Slices, SliceView{Name: "all"})
  89. }
  90. sf.Faces = append(sf.Faces, v)
  91. }
  92. out = append(out, sf)
  93. }
  94. sort.Slice(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
  95. return out
  96. }
  97. // embeddedFace returns the face a key names when a document may embed it
  98. func (l *Library) embeddedFace(key string) *Face {
  99. l.mu.RLock()
  100. face := l.faces[key]
  101. l.mu.RUnlock()
  102. if face == nil || !embeddable(face) {
  103. return nil
  104. }
  105. return face
  106. }
  107. // glyphsAligned reports whether every glyph of a TrueType font starts on an
  108. // even offset; a font without glyf / loca has nothing to align
  109. func glyphsAligned(font *Font, numGlyphs int) bool {
  110. if font.Table("glyf") == nil || font.Table("loca") == nil {
  111. return true
  112. }
  113. offsets, err := glyphOffsets(font, numGlyphs)
  114. if err != nil {
  115. return true // a damaged loca is not ours to rewrite
  116. }
  117. for _, o := range offsets {
  118. if o%2 != 0 {
  119. return false
  120. }
  121. }
  122. return true
  123. }
  124. // padGlyphs rewrites glyf so every glyph starts on a 4-byte boundary, with
  125. // a long loca to match. Only the padding between glyphs changes.
  126. func padGlyphs(tables map[string][]byte) error {
  127. maxp := tables["maxp"]
  128. if len(maxp) < 6 || len(tables["head"]) < 54 {
  129. return errors.New("the maxp or head table is damaged")
  130. }
  131. n := int(binary.BigEndian.Uint16(maxp[4:]))
  132. font := &Font{Tables: tables}
  133. offsets, err := glyphOffsets(font, n)
  134. if err != nil {
  135. return err
  136. }
  137. glyf := tables["glyf"]
  138. out := make([]byte, 0, len(glyf)+3*n)
  139. loca := make([]byte, 4*(n+1))
  140. for i := 0; i < n; i++ {
  141. binary.BigEndian.PutUint32(loca[4*i:], uint32(len(out)))
  142. out = append(out, glyf[offsets[i]:offsets[i+1]]...)
  143. for len(out)%4 != 0 {
  144. out = append(out, 0)
  145. }
  146. }
  147. binary.BigEndian.PutUint32(loca[4*n:], uint32(len(out)))
  148. head := append([]byte(nil), tables["head"]...)
  149. binary.BigEndian.PutUint16(head[50:], 1) // indexToLocFormat: long
  150. tables["glyf"], tables["loca"], tables["head"] = out, loca, head
  151. return nil
  152. }
  153. // FilePath returns the font file a face is handed over as - the installed
  154. // file, or a copy made on first use (see above) - and its extension
  155. func (l *Library) FilePath(key string) (string, string, error) {
  156. face := l.embeddedFace(key)
  157. if face == nil {
  158. return "", "", ErrNotFound
  159. }
  160. ext := fileExt(face)
  161. if (face.Format == "ttf" || face.Format == "otf") && face.aligned {
  162. return face.path, ext, nil
  163. }
  164. target := filepath.Join(l.opts.CacheDir, face.Key, "whole"+ext)
  165. if _, err := os.Stat(target); err == nil {
  166. return target, ext, nil
  167. }
  168. l.genMu.Lock()
  169. lock := l.inflight[target]
  170. if lock == nil {
  171. lock = &sync.Mutex{}
  172. l.inflight[target] = lock
  173. }
  174. l.genMu.Unlock()
  175. lock.Lock()
  176. defer func() {
  177. lock.Unlock()
  178. l.genMu.Lock()
  179. delete(l.inflight, target)
  180. l.genMu.Unlock()
  181. }()
  182. if _, err := os.Stat(target); err == nil {
  183. return target, ext, nil // made while we waited
  184. }
  185. data, err := os.ReadFile(face.path)
  186. if err != nil {
  187. return "", "", err
  188. }
  189. font, _, err := Decode(data)
  190. if err != nil {
  191. return "", "", err
  192. }
  193. tables := make(map[string][]byte, len(font.Tables))
  194. for tag, t := range font.Tables {
  195. tables[tag] = t
  196. }
  197. if !face.aligned {
  198. if err := padGlyphs(tables); err != nil {
  199. return "", "", err
  200. }
  201. }
  202. sfnt, err := AssembleSFNT(font.Flavor, tables)
  203. if err != nil {
  204. return "", "", err
  205. }
  206. if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
  207. return "", "", err
  208. }
  209. tmp := target + ".tmp"
  210. if err := os.WriteFile(tmp, sfnt, 0644); err != nil {
  211. return "", "", err
  212. }
  213. if err := os.Rename(tmp, target); err != nil {
  214. os.Remove(tmp)
  215. return "", "", err
  216. }
  217. return target, ext, nil
  218. }
  219. // FileData returns a face as an OpenType font file (FilePath) and its
  220. // extension
  221. func (l *Library) FileData(key string) ([]byte, string, error) {
  222. file, ext, err := l.FilePath(key)
  223. if err != nil {
  224. return nil, "", err
  225. }
  226. data, err := os.ReadFile(file)
  227. if err != nil {
  228. return nil, "", err
  229. }
  230. return data, ext, nil
  231. }
  232. // ServeFile answers a request for a whole font, named "<key>.ttf" or
  233. // "<key>.otf" as Sources lists it
  234. func (l *Library) ServeFile(w http.ResponseWriter, r *http.Request, name string) {
  235. key, ext, ok := strings.Cut(name, ".")
  236. face := l.embeddedFace(key)
  237. if !ok || face == nil || "."+ext != fileExt(face) {
  238. http.NotFound(w, r)
  239. return
  240. }
  241. file, _, err := l.FilePath(key)
  242. if err != nil {
  243. http.NotFound(w, r)
  244. return
  245. }
  246. f, err := os.Open(file)
  247. if err != nil {
  248. http.NotFound(w, r)
  249. return
  250. }
  251. defer f.Close()
  252. st, err := f.Stat()
  253. if err != nil {
  254. http.NotFound(w, r)
  255. return
  256. }
  257. // the key changes with the font
  258. w.Header().Set("Cache-Control", "private, max-age=31536000, immutable")
  259. w.Header().Set("Content-Type", "font/"+ext)
  260. http.ServeContent(w, r, name, st.ModTime(), f)
  261. }