Files
beatglow/ui/font/font.go
T
2026-10-29 17:29:41 +01:00

293 lines
6.3 KiB
Go

package font
import (
"bytes"
"image"
"image/color"
"math"
"os"
"strings"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
"github.com/BeatGlow/display/draw"
_ "embed" // Embed binary files
)
// Fonts contained
var (
MairyBlackItalic = Must(NewFromBytes(mairyBlackItalicTTF))
MicroGrotesk = Must(NewFromBytes(microgroteskTTF))
Monaco = Must(NewFromBytes(monacoRegularTTF))
Montserrat = Must(NewFromBytes(montserratTTF))
MontserratItalic = Must(NewFromBytes(montserratItalicTTF))
SmoochSans = Must(NewFromBytes(smoochSansTTF))
)
func Must(font *Font, err error) *Font {
if err != nil {
panic(err)
}
return font
}
// Font contains a TrueType or OpenType font face.
type Font struct {
ttf *truetype.Font
otf *opentype.Font
face font.Face
attr FontAttr
fg, bg image.Image
scaleX, scaleY float64
changed bool
}
type FontAttr struct {
PointSize float64 // Point size of the font
DPI float64 // Resolution of the font in dots per inch
LineSpacing float64 // Spacing between lines (in terms of font height)
Hinting font.Hinting // Font hinting
}
// Hinting is a type alias.
type Hinting = font.Hinting
const (
HintingNone = font.HintingNone
HintingVertical = font.HintingVertical
HintingFull = font.HintingFull
)
func (a *FontAttr) newTTOptions(scaleX, scaleY float64) *truetype.Options {
dpi := a.DPI
if scaleX*scaleY != 0 {
dpi *= math.Sqrt(scaleX * scaleY)
}
return &truetype.Options{
Size: a.PointSize,
DPI: dpi,
Hinting: a.Hinting,
}
}
func (a *FontAttr) newOTOptions(scaleX, scaleY float64) *opentype.FaceOptions {
dpi := a.DPI
if scaleX*scaleY != 0 {
dpi *= math.Sqrt(scaleX * scaleY)
}
return &opentype.FaceOptions{
Size: a.PointSize,
DPI: dpi,
Hinting: a.Hinting,
}
}
func New(name string) (*Font, error) {
b, err := os.ReadFile(name)
if err != nil {
return nil, err
}
return NewFromBytes(b)
}
func NewFromBytes(b []byte) (*Font, error) {
var (
attr = FontAttr{
PointSize: 12,
DPI: 72,
LineSpacing: 1,
Hinting: font.HintingFull,
}
ttf *truetype.Font
otf *opentype.Font
face font.Face
err error
)
switch {
case bytes.HasPrefix(b, []byte("OTTO")):
if otf, err = opentype.Parse(b); err != nil {
return nil, err
}
face, _ = opentype.NewFace(otf, attr.newOTOptions(0, 0))
default:
if ttf, err = truetype.Parse(b); err != nil {
return nil, err
}
face = truetype.NewFace(ttf, attr.newTTOptions(0, 0))
}
return &Font{
ttf: ttf,
otf: otf,
face: face,
attr: attr,
}, nil
}
func (f Font) Attr() FontAttr {
return f.attr
}
// SetPointSize sets the point size of the font.
func (f *Font) SetPointSize(size float64) {
if size == f.attr.PointSize {
return
}
f.attr.PointSize = size
f.changed = true
}
// WithPointSize returns a new font instance with new point size settings.
func (f *Font) WithPointSize(size float64) *Font {
v := new(Font)
*v = *f
v.SetPointSize(size)
return v
}
// SetDPI sets the resolution of the font in dots per inches (DPI).
func (f *Font) SetDPI(dpi float64) {
if dpi == f.attr.DPI {
return
}
f.attr.DPI = dpi
f.changed = true
}
// WithDPI returns a new font instance with new DPI settings.
func (f *Font) WithDPI(dpi float64) *Font {
v := new(Font)
*v = *f
v.SetDPI(dpi)
return v
}
// SetLineSpacing sets the amount of spacing between lines (in terms of font height).
func (f *Font) SetLineSpacing(spacing float64) {
if spacing == f.attr.LineSpacing {
return
}
f.attr.LineSpacing = spacing
f.changed = true
}
// SetHinting sets the hinting type.
func (f *Font) SetHinting(hinting Hinting) {
if hinting == f.attr.Hinting {
return
}
f.attr.Hinting = hinting
f.changed = true
}
// SetScale sets the ratio of actual pixel/GL point.
func (f *Font) SetScaleXY(x, y float64) {
if x == f.scaleX && y == f.scaleY {
return
}
f.scaleX = x
f.scaleY = y
f.changed = true
}
// updateFace updates the font face if parameters have changed.
func (f *Font) updateFace() {
if f.changed {
switch {
case f.ttf != nil:
f.face = truetype.NewFace(f.ttf, f.attr.newTTOptions(f.scaleX, f.scaleY))
case f.otf != nil:
f.face, _ = opentype.NewFace(f.otf, f.attr.newOTOptions(f.scaleX, f.scaleY))
}
f.changed = false
}
}
// MeasureText returns the minimum width and height in pixels necessary for an image to contain
// the specified text. The supplied text string can contain line break escape sequences (\n).
func (f *Font) MeasureText(text string) (width, height int) {
f.updateFace()
var (
metrics = f.face.Metrics()
lineHeight = (metrics.Ascent + metrics.Descent).Ceil()
lineGap = int((f.attr.LineSpacing - float64(1)) * float64(lineHeight))
lines = strings.Split(text, "\n")
drawer = &font.Drawer{
Dst: nil,
Src: image.NewUniform(color.Black),
Face: f.face,
}
)
for i, line := range lines {
drawer.Dot = fixed.P(0, height)
lineWidth := drawer.MeasureString(line).Ceil()
if lineWidth > width {
width = lineWidth
}
height += lineHeight
if i > 1 {
height += lineGap
}
}
return width, height
}
// Metrics returns the font metrics.
func (f *Font) Metrics() font.Metrics {
f.updateFace()
return f.face.Metrics()
}
// Draw text onto an image using this font.
func (f *Font) Draw(dst draw.Image, p image.Point, fg image.Image, text string) {
f.updateFace()
var (
metrics = f.face.Metrics()
py = p.Y + metrics.Ascent.Round()
lineHeight = (metrics.Ascent + metrics.Descent).Ceil()
lineGap = int((f.attr.LineSpacing - float64(1)) * float64(lineHeight))
lines = strings.Split(text, "\n")
drawer = &font.Drawer{
Dst: dst,
Src: fg,
Face: f.face,
}
)
for i, line := range lines {
drawer.Dot = fixed.P(p.X, py)
drawer.DrawString(line)
py += lineHeight
if i > 1 {
py += lineGap
}
}
}
var (
//go:embed asset/Mairy-BlackItalic.ttf
mairyBlackItalicTTF []byte
//go:embed asset/MicroGrotesk.ttf
microgroteskTTF []byte
//go:embed asset/Monaco.ttf
monacoRegularTTF []byte
//go:embed asset/Montserrat.ttf
montserratTTF []byte
//go:embed asset/Montserrat-Italic.ttf
montserratItalicTTF []byte
//go:embed asset/SmoochSans-Regular.ttf
smoochSansTTF []byte
)