manage.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package fonts
  2. /*
  3. manage.go
  4. Installing and removing fonts, and the description of the library the
  5. System Fonts page shows.
  6. */
  7. import (
  8. "errors"
  9. "fmt"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "regexp"
  14. "sort"
  15. "strings"
  16. )
  17. var unsafeName = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
  18. // FaceView describes one font file for the settings page
  19. type FaceView struct {
  20. ID string `json:"id"`
  21. Family string `json:"family"`
  22. File string `json:"file"`
  23. Style string `json:"style"`
  24. WeightMin int `json:"weightMin"`
  25. WeightMax int `json:"weightMax"`
  26. Italic bool `json:"italic"`
  27. Variable bool `json:"variable"`
  28. Format string `json:"format"`
  29. Size int64 `json:"size"`
  30. Glyphs int `json:"glyphs"`
  31. Codepoints int `json:"codepoints"`
  32. Sliced bool `json:"sliced"`
  33. }
  34. // FamilyView describes one family for the settings page
  35. type FamilyView struct {
  36. Name string `json:"name"`
  37. Preview string `json:"preview"`
  38. Faces []FaceView `json:"faces"`
  39. WeightMin int `json:"weightMin"`
  40. WeightMax int `json:"weightMax"`
  41. Italic bool `json:"italic"`
  42. Variable bool `json:"variable"`
  43. Scripts []string `json:"scripts"`
  44. Languages []string `json:"languages"`
  45. Size int64 `json:"size"`
  46. Designer string `json:"designer"`
  47. License string `json:"license"`
  48. LicenseURL string `json:"licenseURL"`
  49. Version string `json:"version"`
  50. }
  51. func faceView(f *Face) FaceView {
  52. return FaceView{
  53. ID: f.ID, Family: f.Info.Family, File: path.Base(f.ID), Style: f.Info.Style,
  54. WeightMin: f.Info.WeightMin, WeightMax: f.Info.WeightMax,
  55. Italic: f.Info.Italic, Variable: f.Info.Variable, Format: f.Format, Size: f.Size,
  56. Glyphs: f.Info.Glyphs, Codepoints: f.Info.Codepoints, Sliced: f.sliced,
  57. }
  58. }
  59. // Families describes every installed family; langs are the languages to
  60. // test support for
  61. func (l *Library) Families(langs []string) []FamilyView {
  62. l.mu.RLock()
  63. fams := make([]*Family, 0, len(l.families))
  64. for _, f := range l.families {
  65. fams = append(fams, f)
  66. }
  67. l.mu.RUnlock()
  68. sort.Slice(fams, func(i, j int) bool { return strings.ToLower(fams[i].Name) < strings.ToLower(fams[j].Name) })
  69. out := make([]FamilyView, 0, len(fams))
  70. for _, fam := range fams {
  71. v := FamilyView{Name: fam.Name, Preview: PreviewName(fam.Name), WeightMin: 1000, Scripts: []string{}, Languages: []string{}}
  72. scripts := map[string]bool{}
  73. for _, f := range fam.Faces {
  74. v.Faces = append(v.Faces, faceView(f))
  75. v.Size += f.Size
  76. v.WeightMin = min(v.WeightMin, f.Info.WeightMin)
  77. v.WeightMax = max(v.WeightMax, f.Info.WeightMax)
  78. v.Italic = v.Italic || f.Info.Italic
  79. v.Variable = v.Variable || f.Info.Variable
  80. v.Designer = firstOf(v.Designer, f.Info.Designer)
  81. v.License = firstOf(v.License, f.Info.License)
  82. v.LicenseURL = firstOf(v.LicenseURL, f.Info.LicenseURL)
  83. v.Version = firstOf(v.Version, f.Info.Version)
  84. for _, s := range f.Info.Scripts {
  85. scripts[s] = true
  86. }
  87. }
  88. for _, s := range scriptRanges {
  89. if scripts[s.id] {
  90. v.Scripts = append(v.Scripts, s.id)
  91. }
  92. }
  93. for _, lang := range langs {
  94. if l.coverage(fam, strings.ToLower(lang)) >= 0.9 {
  95. v.Languages = append(v.Languages, strings.ToLower(lang))
  96. }
  97. }
  98. out = append(out, v)
  99. }
  100. return out
  101. }
  102. // dirName turns a family name into a folder name
  103. func dirName(family string) string {
  104. name := strings.Trim(unsafeName.ReplaceAllString(strings.ReplaceAll(family, " ", "_"), ""), "._-")
  105. if name == "" {
  106. name = fmt.Sprintf("Font_%x", []byte(family))
  107. if len(name) > 40 {
  108. name = name[:40]
  109. }
  110. }
  111. return name
  112. }
  113. // Install checks an uploaded font and adds it to the library. WOFF files
  114. // are unpacked to TTF / OTF so they can be sliced.
  115. func (l *Library) Install(filename string, data []byte) (FaceView, error) {
  116. if len(data) > MaxFontSize {
  117. return FaceView{}, fmt.Errorf("the font is larger than %d MB", MaxFontSize>>20)
  118. }
  119. font, container, err := Decode(data)
  120. if err != nil {
  121. return FaceView{}, err
  122. }
  123. info, _, err := Inspect(font)
  124. if err != nil {
  125. return FaceView{}, err
  126. }
  127. ext := ".ttf"
  128. if font.IsCFF() {
  129. ext = ".otf"
  130. }
  131. switch container {
  132. case "woff":
  133. tables := map[string][]byte{}
  134. for tag, t := range font.Tables {
  135. tables[tag] = t
  136. }
  137. if data, err = AssembleSFNT(font.Flavor, tables); err != nil {
  138. return FaceView{}, err
  139. }
  140. case "woff2":
  141. ext = ".woff2"
  142. }
  143. if fam := l.family(info.Family); fam != nil {
  144. for _, f := range fam.Faces {
  145. if f.Info.Italic == info.Italic && f.Info.Variable == info.Variable &&
  146. f.Info.WeightMin == info.WeightMin && f.Info.WeightMax == info.WeightMax {
  147. return FaceView{}, fmt.Errorf("%s %s is already installed", fam.Name, f.Info.Style)
  148. }
  149. }
  150. }
  151. l.mu.Lock()
  152. defer l.mu.Unlock()
  153. dir := dirName(info.Family)
  154. if fam := l.families[strings.ToLower(info.Family)]; fam != nil && fam.Dir != "" {
  155. dir = fam.Dir
  156. }
  157. base := strings.TrimSuffix(filepath.Base(filepath.ToSlash(filename)), filepath.Ext(filename))
  158. base = strings.Trim(unsafeName.ReplaceAllString(base, "_"), "._-")
  159. if base == "" {
  160. base = dirName(info.Family + " " + info.Style)
  161. }
  162. if err := os.MkdirAll(filepath.Join(l.opts.Root, dir), 0755); err != nil {
  163. return FaceView{}, err
  164. }
  165. id := path.Join(dir, base+ext)
  166. for n := 2; ; n++ {
  167. if _, err := os.Stat(filepath.Join(l.opts.Root, filepath.FromSlash(id))); os.IsNotExist(err) {
  168. break
  169. }
  170. id = path.Join(dir, fmt.Sprintf("%s-%d%s", base, n, ext))
  171. }
  172. target := filepath.Join(l.opts.Root, filepath.FromSlash(id))
  173. if err := os.WriteFile(target+".tmp", data, 0644); err != nil {
  174. return FaceView{}, err
  175. }
  176. if err := os.Rename(target+".tmp", target); err != nil {
  177. os.Remove(target + ".tmp")
  178. return FaceView{}, err
  179. }
  180. face, err := l.readFace(id)
  181. if err != nil {
  182. os.Remove(target)
  183. return FaceView{}, err
  184. }
  185. key := strings.ToLower(face.Info.Family)
  186. fam := l.families[key]
  187. if fam == nil {
  188. fam = &Family{Name: face.Info.Family, Dir: dir}
  189. l.families[key] = fam
  190. }
  191. fam.Faces = append(fam.Faces, face)
  192. sortFaces(fam.Faces)
  193. l.faces[face.Key] = face
  194. return faceView(face), nil
  195. }
  196. // Delete removes a family: its font files, its folder when nothing else
  197. // is left in it, and its generated slices
  198. func (l *Library) Delete(family string) error {
  199. l.mu.Lock()
  200. defer l.mu.Unlock()
  201. key := strings.ToLower(family)
  202. fam := l.families[key]
  203. if fam == nil {
  204. return ErrNotFound
  205. }
  206. root, err := filepath.Abs(l.opts.Root)
  207. if err != nil {
  208. return err
  209. }
  210. for _, face := range fam.Faces {
  211. full, err := filepath.Abs(face.path)
  212. if err != nil || !strings.HasPrefix(full, root+string(filepath.Separator)) {
  213. return errors.New("refusing to delete a file outside the font folder")
  214. }
  215. if err := os.Remove(full); err != nil && !os.IsNotExist(err) {
  216. return err
  217. }
  218. os.RemoveAll(filepath.Join(l.opts.CacheDir, face.Key))
  219. delete(l.faces, face.Key)
  220. }
  221. delete(l.families, key)
  222. if fam.Dir != "" {
  223. dir := filepath.Join(root, fam.Dir)
  224. left := false
  225. if entries, err := os.ReadDir(dir); err == nil {
  226. for _, e := range entries {
  227. if fontExts[strings.ToLower(filepath.Ext(e.Name()))] {
  228. left = true // another family shares the folder
  229. }
  230. }
  231. }
  232. if !left {
  233. os.RemoveAll(dir)
  234. }
  235. }
  236. return nil
  237. }