font

package
v0.1.0-alpha.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package font loads fonts, resolves CSS font-family lists and provides the metrics and glyph outlines that layout (advance widths, line boxes) and rasterization (outlines) both need, from one source so they agree.

Resolution order for a family name: an explicitly registered web font, then system fonts found on disk (the same files a browser on this machine would pick), then embedded Go fonts as a last resort so rendering never fails and is reproducible when SWEEF_FONTS=embedded is set.

Index

Constants

View Source
const (
	OvrAscent = 1 << iota
	OvrDescent
	OvrLineGap
)

Overrides bits.

View Source
const (
	StyleNormal  = 0
	StyleItalic  = 1
	StyleOblique = 2
)

Style values of FaceDesc.

Variables

View Source
var DefaultLimits = Limits{MaxSfnt: 32 << 20, MaxTables: 128}

DefaultLimits are what the browser uses: real web fonts are far smaller (a full CJK font is about 16 MB; Google Fonts subsets are 10-100 KB).

View Source
var ErrBadFont = errors.New("font: invalid or unsupported font data")

ErrBadFont is wrapped by every error the decoders and the sanitiser return for input that is not a usable font. Callers fall back to another face.

Functions

func BaseFamily

func BaseFamily(name string) string

BaseFamily strips the scope of a scoped family name.

func BidiLevels

func BidiLevels(rs []rune, baseRTL bool) []uint8

BidiLevels computes the embedding level of every rune of one paragraph (UAX #9 rules X1-X8, W1-W7, N0-N2, I1-I2 and L1).

func DecodeWOFF

func DecodeWOFF(data []byte, lim Limits) (sfnt []byte, err error)

DecodeWOFF converts a WOFF 1.0 file to a plain sfnt.

func DecodeWOFF2

func DecodeWOFF2(data []byte, lim Limits) (out []byte, err error)

DecodeWOFF2 converts a WOFF 2.0 file to a plain sfnt.

func Demand

func Demand(fams []string, st Style, r rune)

Demand tells the fonts that the text needs a glyph for r. For the first scoped family of the list that has a face covering r (by unicode-range) that is not loaded yet, the load starts; later families are only considered when that face cannot provide the glyph (it failed, or it loaded without it).

func DemandFamily

func DemandFamily(family string, st Style, r rune) (pending bool)

DemandFamily is Demand for one family of a font-family list. It reports whether the family has a face for r that is loading (started now or before): the caller then shows r in a later family for the moment and does not ask the families after this one to load.

func FTSize

func FTSize(size float64) float64

FTSize is the font size as FreeType (and so Skia and Chromium) sees it: requested in 26.6 fixed point with truncation, e.g. 21.6px is 21.59375px. Advances and kerning are linear in this size, so layout and painting that want to agree with Chromium to a fraction of a pixel over a long line must use it.

func Families

func Families() []string

Families lists installed family names (for diagnostics).

func FamilyKey

func FamilyKey(s string) string

FamilyKey is the lower-case form family names are compared in.

func HasScoped

func HasScoped(fams []string) bool

HasScoped reports whether any name of the list is scoped to a web set.

func IsRTLRune

func IsRTLRune(r rune) bool

IsRTLRune reports whether r is a strong right-to-left character (Hebrew, Arabic and friends) or a bidi control; text without any can skip bidi.

func OpenSets

func OpenSets() int

OpenSets is the number of web font sets that have not been closed (diagnostics and leak tests).

func RegisterWeb

func RegisterWeb(family string, st Style, data []byte) error

RegisterWeb adds an @font-face font that takes priority over system fonts.

func ReorderVisual

func ReorderVisual(levels []uint8) []int

ReorderVisual returns the logical index shown at each visual position for per-element embedding levels (rule L2).

func ShapeArabic

func ShapeArabic(rs []rune) []rune

ShapeArabic maps Arabic letters in logical order to their contextual presentation forms (isolated, initial, medial, final) and combines lam-alef into the mandatory ligature. The result is still in logical order and may be shorter than the input; non-Arabic runes pass through.

func ShapeArabicKeep

func ShapeArabicKeep(rs []rune) []rune

ShapeArabicKeep is ShapeArabic that preserves the rune count: a lam-alef ligature takes the lam's place and the alef position becomes 0 (a rune the caller skips), so indexes into the input stay valid.

func WebGen

func WebGen() uint64

WebGen changes whenever the faces available to any set change. Caches of resolved faces key on it.

Types

type BidiRun

type BidiRun struct {
	Start, End int
	RTL        bool
}

BidiRun is a span of runes [Start, End) in one direction. For an RTL run the characters are displayed in reverse logical order.

func BidiRuns

func BidiRuns(text []rune, baseRTL bool) []BidiRun

BidiRuns resolves one line of text with the Unicode Bidirectional Algorithm and returns its runs in visual (left to right) order. baseRTL selects the paragraph direction (CSS direction: rtl).

type Face

type Face struct {
	Family string
	Style  Style
	Mono   bool
	// contains filtered or unexported fields
}

func Fallback

func Fallback(r rune, families []string, st Style) *Face

Fallback finds a face that has a glyph for r, preferring the given list.

func Local

func Local(name string, st Style) *Face

Local finds an installed font by the name a CSS local() source gives: its full name or PostScript name, as browsers do, or (a convenience browsers lack but fontconfig makes natural) a family name, in which case the face closest to st is used. nil when no such font is installed.

func Lookup

func Lookup(family string, st Style) *Face

Lookup resolves a single family name (or generic keyword) and style.

func LookupAll

func LookupAll(family string, st Style) []*Face

LookupAll resolves one family of a font-family list to the loaded faces of the matched group, in priority order. For a plain family name it is the single face Lookup returns. A scoped name whose faces are not loaded yet yields nil: the caller moves on to the next family.

func Parse

func Parse(family string, st Style, data []byte) (*Face, error)

Parse loads a font from raw TTF/OTF bytes (used for @font-face).

func Resolve

func Resolve(families []string, st Style) *Face

Resolve picks the first available face from a CSS font-family list.

func (*Face) Advance

func (f *Face) Advance(r rune, size float64) float64

Advance is the horizontal advance of r at size (px), unrounded.

func (*Face) AdvanceF

func (f *Face) AdvanceF(r rune, size float64) float64

AdvanceF is the exact (unrounded) advance of r at size px, or -1. The size is quantized like FreeType's (see FTSize).

func (*Face) AdvanceGID

func (f *Face) AdvanceGID(gid int, size float64) float64

AdvanceGID is the advance of glyph gid at size px (FreeType-quantized).

func (*Face) AdvanceGIDUnits

func (f *Face) AdvanceGIDUnits(gid int) float64

AdvanceGIDUnits is the advance of glyph gid in font units.

func (*Face) AdvanceUnits

func (f *Face) AdvanceUnits(r rune) float64

AdvanceUnits is the horizontal advance of r in font units, or -1 when the face has no glyph for r.

func (*Face) BBoxWidth

func (f *Face) BBoxWidth() float64

BBoxWidth is the width of the font's global bounding box (head xMax-xMin) in font units.

func (*Face) Data

func (f *Face) Data() []byte

Face is one loaded font file. Data returns the raw sfnt bytes this face reads glyph tables from. The slice is shared; callers must not modify it.

func (*Face) GID

func (f *Face) GID(r rune) int

GID is the glyph id of r in the face (0 when absent).

func (*Face) HasGlyph

func (f *Face) HasGlyph(r rune) bool

HasGlyph reports whether the face defines r.

func (*Face) HasLigatures

func (f *Face) HasLigatures() bool

HasLigatures reports whether the face has GSUB standard ligature lookups.

func (*Face) Kern

func (f *Face) Kern(a, b rune, size float64) float64

Kern returns the kerning adjustment between two runes in px.

func (*Face) KernF

func (f *Face) KernF(a, b rune, size float64) float64

KernF is the exact kerning adjustment between a and b at size px.

func (*Face) KernGIDs

func (f *Face) KernGIDs(a, b int, size float64) float64

KernGIDs is the pair adjustment between two glyph ids at size px.

func (*Face) LigMax

func (f *Face) LigMax() int

LigMax is the number of runes of the longest standard ligature of the face (0 when it has none): how far text has to be scanned for one.

func (*Face) Ligature

func (f *Face) Ligature(rs []rune) (gid, n int)

Ligature looks for a standard ligature (liga, clig, rlig) at the start of rs, which must all be in this face. It returns the ligature glyph id and the number of runes it replaces (0 when there is none). rs may be longer than the ligature; at most LigMax runes are examined.

func (*Face) Metrics

func (f *Face) Metrics(size float64) Metrics

Metrics returns vertical metrics scaled to size (px), computed exactly from font units (not from 26.6 fixed-point values) so rounding matches browsers.

func (*Face) Outline

func (f *Face) Outline(r rune, size float64) []Segment

Outline returns the glyph outline for r at size, or nil when undefined.

func (*Face) OutlineGID

func (f *Face) OutlineGID(gid int, size float64) []Segment

OutlineGID is Outline for a glyph id.

func (*Face) RawMetrics

func (f *Face) RawMetrics() (ascent, descent, lineGap, avgChar, maxAdvance float64)

RawMetrics returns unscaled hhea ascent/descent/lineGap and OS/2 values in font units.

func (*Face) ShapeRun

func (f *Face) ShapeRun(rs []rune, size float64, o ShapeOptions) []ShapedGlyph

ShapeRun shapes rs (one script, one face) at size px the way HarfBuzz does for Latin: standard ligatures first, then pair kerning, advances linear in the FreeType-quantized size (see FTSize). Runes the face lacks yield glyph 0 with a zero advance; callers handle fallback before shaping.

func (*Face) TypoMetrics

func (f *Face) TypoMetrics(size float64) (asc, desc float64, ok bool)

TypoMetrics returns the OS/2 typographic ascender and descender (the descender as a positive distance below the baseline) scaled to size px, unrounded; ok is false when the face has no usable OS/2 table. Chromium derives the canvas "top", "middle" and "bottom" text baselines from them.

func (*Face) UnitsPerEm

func (f *Face) UnitsPerEm() int

UnitsPerEm of the face.

func (*Face) Varied

func (f *Face) Varied() bool

Varied reports whether f is a variable font instance away from the default (its outlines and advances differ from the raw glyf and hmtx tables).

type FaceDesc

type FaceDesc struct {
	Family     string
	WMin, WMax int // font-weight range, 1..1000
	Style      uint8
	SMin, SMax float64 // font-stretch range in percent
	Ranges     []URange
	Src        []Source
	Display    string
	Base       string // URL of the stylesheet that declared it (informational)
	Features   string // font-feature-settings descriptor, raw
	Variations string // font-variation-settings descriptor, raw
	// SizeAdjust, AscentOverride, DescentOverride and LineGapOverride are the
	// metric descriptors (fractions: 1.0 = 100%); a size-adjust of 0 means 1.
	// Overrides is the set of overrides that were given (OvrAscent|OvrDescent|OvrLineGap).
	SizeAdjust                                       float64
	AscentOverride, DescentOverride, LineGapOverride float64
	Overrides                                        uint8
}

FaceDesc is a parsed @font-face rule (or the arguments of new FontFace).

func (*FaceDesc) Covers

func (d *FaceDesc) Covers(r rune) bool

Covers reports whether the unicode-range includes r.

func (FaceDesc) Key

func (d FaceDesc) Key() string

Key identifies a declaration: two equal keys are the same font.

func (*FaceDesc) Normalize

func (d *FaceDesc) Normalize()

Normalize fills defaults.

type FontKind

type FontKind string

FontKind says what container a font file was.

const (
	KindTTF   FontKind = "truetype"
	KindOTF   FontKind = "opentype"
	KindWOFF  FontKind = "woff"
	KindWOFF2 FontKind = "woff2"
)

func Decode

func Decode(data []byte, lim Limits) (sfnt []byte, kind FontKind, err error)

Decode turns a font file (WOFF2, WOFF, TrueType or OpenType; collections are not accepted) into a validated plain sfnt. It never panics.

func DetectKind

func DetectKind(data []byte) (FontKind, bool)

DetectKind recognises the container from the first bytes.

type Limits

type Limits struct {
	// MaxSfnt caps the size of the decoded sfnt (and so of any decompressed
	// table stream: a zip bomb is stopped here).
	MaxSfnt int
	// MaxTables caps the number of tables a file may declare.
	MaxTables int
}

Limits applied while decoding untrusted font files.

type LoadState

type LoadState uint8

LoadState of a web face.

const (
	Unloaded LoadState = iota
	Loading
	Loaded
	Failed
)

func (LoadState) String

func (s LoadState) String() string

type Metrics

type Metrics struct {
	Ascent, Descent, LineGap float64
	XHeight, CapHeight       float64
	UnitsPerEm               int
}

Metrics are in pixels at the requested size.

type Segment

type Segment struct {
	Op     byte // 'M' move, 'L' line, 'Q' quad, 'C' cubic
	X0, Y0 float64
	X1, Y1 float64
	X2, Y2 float64
}

Segment is one outline command in pixel space, y down, origin at the baseline-left of the glyph.

type ShapeOptions

type ShapeOptions struct {
	Kern bool // apply GPOS (or legacy kern table) pair kerning
	Liga bool // apply standard GSUB ligatures (liga, clig, rlig)
}

Options for ShapeRun.

type ShapedGlyph

type ShapedGlyph struct {
	GID     int     // glyph id in the face; 0 when the face lacks the character
	Cluster int     // index of the first rune of the cluster in the input
	NRunes  int     // runes consumed (2 or 3 for a ligature)
	X       float64 // pen position of the glyph in px, kerning included
	Adv     float64 // advance in px
}

ShapedGlyph is one glyph of a run shaped with ShapeRun.

type Source

type Source struct {
	URL    string   // absolute URL, "" for local()
	Local  string   // local() name
	Format string   // format() hint, lower case ("" none)
	Tech   []string // tech() hints, lower case
}

Source is one entry of an @font-face src descriptor.

type Style

type Style struct {
	Weight int // 100..900; 400 normal, 700 bold
	Italic bool
	// OpticalSize is the font size in CSS px for a variable font's opsz axis
	// (font-optical-sizing: auto). 0 leaves the axis at the font's default.
	OpticalSize float64
}

Style selects a face within a family.

type URange

type URange struct{ Lo, Hi rune }

URange is an inclusive code point range of a unicode-range descriptor.

type WebFace

type WebFace struct {
	Desc  FaceDesc
	Order int // declaration order within the set
	// Data is free for the loader (the engine keeps its request state here).
	Data any
	// Trigger is the first character that made the face necessary (set when
	// a load starts; zero for an explicit load).
	Trigger rune
	// contains filtered or unexported fields
}

WebFace is one declared font. The engine fetches its bytes and reports them with SetData or SetFailed; the set only decides when a load is needed.

func NewWebFace

func NewWebFace(d FaceDesc) *WebFace

NewWebFace makes a face that belongs to no set yet.

func (*WebFace) BeginLoad

func (f *WebFace) BeginLoad() bool

BeginLoad moves an Unloaded (or Failed, for a retry) face to Loading and reports whether the caller should fetch it.

func (*WebFace) Err

func (f *WebFace) Err() error

Err is the failure reason of a Failed face.

func (*WebFace) Face

func (f *WebFace) Face(weight int) *Face

Face returns the font to draw with at the requested weight: a variable font is instantiated at the weight (clamped to the declared range), a static one is returned as is. nil until the face is Loaded.

func (*WebFace) FaceAt

func (f *WebFace) FaceAt(weight int, opsz float64) *Face

FaceAt is Face with the optical size (CSS px) for a variable font's opsz axis.

func (*WebFace) Redescribe

func (f *WebFace) Redescribe(d FaceDesc) bool

Redescribe replaces the descriptors of a face that has not started loading (FontFace attribute setters). It reports whether the change was applied.

func (*WebFace) Retry

func (f *WebFace) Retry()

Retry puts a face whose load could not be attempted (the tab was in the background) back to Unloaded, so that the next layout asks for it again.

func (*WebFace) Set

func (f *WebFace) Set() *WebSet

Set returns the set the face belongs to (nil before Add).

func (*WebFace) SetData

func (f *WebFace) SetData(sfnt []byte) error

SetData installs decoded font data (a validated sfnt, see Decode). On failure the face becomes Failed.

func (*WebFace) SetFailed

func (f *WebFace) SetFailed(err error)

SetFailed marks the face as failed.

func (*WebFace) State

func (f *WebFace) State() LoadState

State reports the load state.

type WebSet

type WebSet struct {
	// contains filtered or unexported fields
}

WebSet is the web fonts of one document.

func NewWebSet

func NewWebSet(loader func(*WebFace), onChange func()) *WebSet

NewWebSet creates a set. loader is called (never with the set's lock held, and it must not block) once for every face that becomes necessary; the loader reports the outcome with SetData or SetFailed. onChange is called when the set of usable faces changed (a face loaded, the declarations changed) so that the document can be laid out again.

func (*WebSet) Add

func (s *WebSet) Add(f *WebFace)

Add puts a script created face (new FontFace(...)) into the set.

func (*WebSet) Clear

func (s *WebSet) Clear()

Clear removes every script created face.

func (*WebSet) Close

func (s *WebSet) Close()

Close drops the set: its scoped names stop resolving. Safe to call twice.

func (*WebSet) DeclGen

func (s *WebSet) DeclGen() uint64

DeclGen changes when the set of declared families or faces changes (not when a face merely loads). Style caches key on it.

func (*WebSet) Declares

func (s *WebSet) Declares(family string) bool

Declares reports whether any face is declared for family.

func (*WebSet) Delete

func (s *WebSet) Delete(f *WebFace) bool

Delete removes a script created face.

func (*WebSet) DemandText

func (s *WebSet) DemandText(family string, st Style, text string) []*WebFace

DemandText demands every character of text for the family (document.fonts.load).

func (*WebSet) Faces

func (s *WebSet) Faces() []*WebFace

Faces lists every face, stylesheet faces first.

func (*WebSet) Gen

func (s *WebSet) Gen() uint64

Gen changes whenever DeclGen does and whenever a face loads.

func (*WebSet) ID

func (s *WebSet) ID() int

ID identifies the set in scoped names.

func (*WebSet) Match

func (s *WebSet) Match(family string, st Style) []*WebFace

Match returns the faces CSS font matching selects for family at the style, in priority order (any load state). It is how document.fonts.load/check find what to wait for.

func (*WebSet) Pending

func (s *WebSet) Pending() int

Pending counts faces whose load is in progress.

func (*WebSet) Scope

func (s *WebSet) Scope(family string) (string, bool)

Scope returns the scoped form of family when the set declares it.

func (*WebSet) SetSheetFaces

func (s *WebSet) SetSheetFaces(descs []FaceDesc) bool

SetSheetFaces replaces the faces declared by stylesheets. Faces whose declaration is unchanged keep their state (a loaded font stays loaded when the page re-lays out). It reports whether anything changed.

Directories

Path Synopsis
Package fonttest builds small fonts for tests: a TrueType writer (so no licensed font binary has to be committed), WOFF and WOFF2 encoders and a few ready-made fonts whose glyphs are plain boxes with distinct widths and heights, which makes rendered text easy to recognise and compare.
Package fonttest builds small fonts for tests: a TrueType writer (so no licensed font binary has to be committed), WOFF and WOFF2 encoders and a few ready-made fonts whose glyphs are plain boxes with distinct widths and heights, which makes rendered text easy to recognise and compare.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL