gofont.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // SPDX-License-Identifier: Unlicense OR MIT
  2. // Package gofont exports the Go fonts as a text.Collection.
  3. //
  4. // See https://blog.golang.org/go-fonts for a description of the
  5. // fonts, and the golang.org/x/image/font/gofont packages for the
  6. // font data.
  7. package gofont
  8. import (
  9. "fmt"
  10. "sync"
  11. "golang.org/x/image/font/gofont/gobold"
  12. "golang.org/x/image/font/gofont/gobolditalic"
  13. "golang.org/x/image/font/gofont/goitalic"
  14. "golang.org/x/image/font/gofont/gomedium"
  15. "golang.org/x/image/font/gofont/gomediumitalic"
  16. "golang.org/x/image/font/gofont/gomono"
  17. "golang.org/x/image/font/gofont/gomonobold"
  18. "golang.org/x/image/font/gofont/gomonobolditalic"
  19. "golang.org/x/image/font/gofont/gomonoitalic"
  20. "golang.org/x/image/font/gofont/goregular"
  21. "golang.org/x/image/font/gofont/gosmallcaps"
  22. "golang.org/x/image/font/gofont/gosmallcapsitalic"
  23. "gioui.org/font"
  24. "gioui.org/font/opentype"
  25. )
  26. var (
  27. regOnce sync.Once
  28. reg []font.FontFace
  29. once sync.Once
  30. collection []font.FontFace
  31. )
  32. func loadRegular() {
  33. regOnce.Do(func() {
  34. faces, err := opentype.ParseCollection(goregular.TTF)
  35. if err != nil {
  36. panic(fmt.Errorf("failed to parse font: %v", err))
  37. }
  38. reg = faces
  39. collection = append(collection, reg[0])
  40. })
  41. }
  42. // Regular returns a collection of only the Go regular font face.
  43. func Regular() []font.FontFace {
  44. loadRegular()
  45. return reg
  46. }
  47. // Regular returns a collection of all available Go font faces.
  48. func Collection() []font.FontFace {
  49. loadRegular()
  50. once.Do(func() {
  51. register(goitalic.TTF)
  52. register(gobold.TTF)
  53. register(gobolditalic.TTF)
  54. register(gomedium.TTF)
  55. register(gomediumitalic.TTF)
  56. register(gomono.TTF)
  57. register(gomonobold.TTF)
  58. register(gomonobolditalic.TTF)
  59. register(gomonoitalic.TTF)
  60. register(gosmallcaps.TTF)
  61. register(gosmallcapsitalic.TTF)
  62. // Ensure that any outside appends will not reuse the backing store.
  63. n := len(collection)
  64. collection = collection[:n:n]
  65. })
  66. return collection
  67. }
  68. func register(ttf []byte) {
  69. faces, err := opentype.ParseCollection(ttf)
  70. if err != nil {
  71. panic(fmt.Errorf("failed to parse font: %v", err))
  72. }
  73. collection = append(collection, faces[0])
  74. }