github.com/utopiagio/gio@v0.0.8/font/gofont/gofont.go (about)

     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/utopiagio/gio/font"
    28  	"github.com/utopiagio/gio/font/opentype"
    29  )
    30  
    31  var (
    32  	regOnce    sync.Once
    33  	reg        []font.FontFace
    34  	once       sync.Once
    35  	collection []font.FontFace
    36  )
    37  
    38  func loadRegular() {
    39  	regOnce.Do(func() {
    40  		faces, err := opentype.ParseCollection(goregular.TTF)
    41  		if err != nil {
    42  			panic(fmt.Errorf("failed to parse font: %v", err))
    43  		}
    44  		reg = faces
    45  		collection = append(collection, reg[0])
    46  	})
    47  }
    48  
    49  // Regular returns a collection of only the Go regular font face.
    50  func Regular() []font.FontFace {
    51  	loadRegular()
    52  	return reg
    53  }
    54  
    55  // Regular returns a collection of all available Go font faces.
    56  func Collection() []font.FontFace {
    57  	loadRegular()
    58  	once.Do(func() {
    59  		register(goitalic.TTF)
    60  		register(gobold.TTF)
    61  		register(gobolditalic.TTF)
    62  		register(gomedium.TTF)
    63  		register(gomediumitalic.TTF)
    64  		register(gomono.TTF)
    65  		register(gomonobold.TTF)
    66  		register(gomonobolditalic.TTF)
    67  		register(gomonoitalic.TTF)
    68  		register(gosmallcaps.TTF)
    69  		register(gosmallcapsitalic.TTF)
    70  		// Ensure that any outside appends will not reuse the backing store.
    71  		n := len(collection)
    72  		collection = collection[:n:n]
    73  	})
    74  	return collection
    75  }
    76  
    77  func register(ttf []byte) {
    78  	faces, err := opentype.ParseCollection(ttf)
    79  	if err != nil {
    80  		panic(fmt.Errorf("failed to parse font: %v", err))
    81  	}
    82  	collection = append(collection, faces[0])
    83  }