gofont.go raw

   1  // SPDX-License-Identifier: Unlicense OR MIT
   2  
   3  // Package gofont exports the Go fonts as a text.Collection.
   4  //
   5  // See https://blog.golang.org/go-fonts for a description of the
   6  // fonts, and the golang.org/x/image/font/gofont packages for the
   7  // font data.
   8  package gofont
   9  
  10  import (
  11  	"fmt"
  12  	"sync"
  13  
  14  	"golang.org/x/image/font/gofont/gobold"
  15  	"golang.org/x/image/font/gofont/gobolditalic"
  16  	"golang.org/x/image/font/gofont/goitalic"
  17  	"golang.org/x/image/font/gofont/gomedium"
  18  	"golang.org/x/image/font/gofont/gomediumitalic"
  19  	"golang.org/x/image/font/gofont/gomono"
  20  	"golang.org/x/image/font/gofont/gomonobold"
  21  	"golang.org/x/image/font/gofont/gomonobolditalic"
  22  	"golang.org/x/image/font/gofont/gomonoitalic"
  23  	"golang.org/x/image/font/gofont/goregular"
  24  	"golang.org/x/image/font/gofont/gosmallcaps"
  25  	"golang.org/x/image/font/gofont/gosmallcapsitalic"
  26  
  27  	"github.com/p9c/p9/pkg/gel/gio/font/opentype"
  28  	"github.com/p9c/p9/pkg/gel/gio/text"
  29  )
  30  
  31  var (
  32  	once       sync.Once
  33  	collection []text.FontFace
  34  )
  35  
  36  func Collection() []text.FontFace {
  37  	once.Do(func() {
  38  		register(text.Font{}, goregular.TTF)
  39  		register(text.Font{Style: text.Italic}, goitalic.TTF)
  40  		register(text.Font{Weight: text.Bold}, gobold.TTF)
  41  		register(text.Font{Style: text.Italic, Weight: text.Bold}, gobolditalic.TTF)
  42  		register(text.Font{Weight: text.Medium}, gomedium.TTF)
  43  		register(text.Font{Weight: text.Medium, Style: text.Italic}, gomediumitalic.TTF)
  44  		register(text.Font{Variant: "Mono"}, gomono.TTF)
  45  		register(text.Font{Variant: "Mono", Weight: text.Bold}, gomonobold.TTF)
  46  		register(text.Font{Variant: "Mono", Weight: text.Bold, Style: text.Italic}, gomonobolditalic.TTF)
  47  		register(text.Font{Variant: "Mono", Style: text.Italic}, gomonoitalic.TTF)
  48  		register(text.Font{Variant: "Smallcaps"}, gosmallcaps.TTF)
  49  		register(text.Font{Variant: "Smallcaps", Style: text.Italic}, gosmallcapsitalic.TTF)
  50  		// Ensure that any outside appends will not reuse the backing store.
  51  		n := len(collection)
  52  		collection = collection[:n:n]
  53  	})
  54  	return collection
  55  }
  56  
  57  func register(fnt text.Font, ttf []byte) {
  58  	face, err := opentype.Parse(ttf)
  59  	if err != nil {
  60  		panic(fmt.Errorf("failed to parse font: %v", err))
  61  	}
  62  	fnt.Typeface = "Go"
  63  	collection = append(collection, text.FontFace{Font: fnt, Face: face})
  64  }
  65