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
- Variables
- func BaseFamily(name string) string
- func BidiLevels(rs []rune, baseRTL bool) []uint8
- func DecodeWOFF(data []byte, lim Limits) (sfnt []byte, err error)
- func DecodeWOFF2(data []byte, lim Limits) (out []byte, err error)
- func Demand(fams []string, st Style, r rune)
- func DemandFamily(family string, st Style, r rune) (pending bool)
- func FTSize(size float64) float64
- func Families() []string
- func FamilyKey(s string) string
- func HasScoped(fams []string) bool
- func IsRTLRune(r rune) bool
- func OpenSets() int
- func RegisterWeb(family string, st Style, data []byte) error
- func ReorderVisual(levels []uint8) []int
- func ShapeArabic(rs []rune) []rune
- func ShapeArabicKeep(rs []rune) []rune
- func WebGen() uint64
- type BidiRun
- type Face
- func (f *Face) Advance(r rune, size float64) float64
- func (f *Face) AdvanceF(r rune, size float64) float64
- func (f *Face) AdvanceGID(gid int, size float64) float64
- func (f *Face) AdvanceGIDUnits(gid int) float64
- func (f *Face) AdvanceUnits(r rune) float64
- func (f *Face) BBoxWidth() float64
- func (f *Face) Data() []byte
- func (f *Face) GID(r rune) int
- func (f *Face) HasGlyph(r rune) bool
- func (f *Face) HasLigatures() bool
- func (f *Face) Kern(a, b rune, size float64) float64
- func (f *Face) KernF(a, b rune, size float64) float64
- func (f *Face) KernGIDs(a, b int, size float64) float64
- func (f *Face) LigMax() int
- func (f *Face) Ligature(rs []rune) (gid, n int)
- func (f *Face) Metrics(size float64) Metrics
- func (f *Face) Outline(r rune, size float64) []Segment
- func (f *Face) OutlineGID(gid int, size float64) []Segment
- func (f *Face) RawMetrics() (ascent, descent, lineGap, avgChar, maxAdvance float64)
- func (f *Face) ShapeRun(rs []rune, size float64, o ShapeOptions) []ShapedGlyph
- func (f *Face) TypoMetrics(size float64) (asc, desc float64, ok bool)
- func (f *Face) UnitsPerEm() int
- func (f *Face) Varied() bool
- type FaceDesc
- type FontKind
- type Limits
- type LoadState
- type Metrics
- type Segment
- type ShapeOptions
- type ShapedGlyph
- type Source
- type Style
- type URange
- type WebFace
- func (f *WebFace) BeginLoad() bool
- func (f *WebFace) Err() error
- func (f *WebFace) Face(weight int) *Face
- func (f *WebFace) FaceAt(weight int, opsz float64) *Face
- func (f *WebFace) Redescribe(d FaceDesc) bool
- func (f *WebFace) Retry()
- func (f *WebFace) Set() *WebSet
- func (f *WebFace) SetData(sfnt []byte) error
- func (f *WebFace) SetFailed(err error)
- func (f *WebFace) State() LoadState
- type WebSet
- func (s *WebSet) Add(f *WebFace)
- func (s *WebSet) Clear()
- func (s *WebSet) Close()
- func (s *WebSet) DeclGen() uint64
- func (s *WebSet) Declares(family string) bool
- func (s *WebSet) Delete(f *WebFace) bool
- func (s *WebSet) DemandText(family string, st Style, text string) []*WebFace
- func (s *WebSet) Faces() []*WebFace
- func (s *WebSet) Gen() uint64
- func (s *WebSet) ID() int
- func (s *WebSet) Match(family string, st Style) []*WebFace
- func (s *WebSet) Pending() int
- func (s *WebSet) Scope(family string) (string, bool)
- func (s *WebSet) SetSheetFaces(descs []FaceDesc) bool
Constants ¶
const ( OvrAscent = 1 << iota OvrDescent OvrLineGap )
Overrides bits.
const ( StyleNormal = 0 StyleItalic = 1 StyleOblique = 2 )
Style values of FaceDesc.
Variables ¶
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).
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 ¶
BaseFamily strips the scope of a scoped family name.
func BidiLevels ¶
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 ¶
DecodeWOFF converts a WOFF 1.0 file to a plain sfnt.
func DecodeWOFF2 ¶
DecodeWOFF2 converts a WOFF 2.0 file to a plain sfnt.
func Demand ¶
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 ¶
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 ¶
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 IsRTLRune ¶
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 ¶
RegisterWeb adds an @font-face font that takes priority over system fonts.
func ReorderVisual ¶
ReorderVisual returns the logical index shown at each visual position for per-element embedding levels (rule L2).
func ShapeArabic ¶
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 ¶
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.
Types ¶
type BidiRun ¶
BidiRun is a span of runes [Start, End) in one direction. For an RTL run the characters are displayed in reverse logical order.
type Face ¶
func Local ¶
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 LookupAll ¶
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 (*Face) AdvanceF ¶
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 ¶
AdvanceGID is the advance of glyph gid at size px (FreeType-quantized).
func (*Face) AdvanceGIDUnits ¶
AdvanceGIDUnits is the advance of glyph gid in font units.
func (*Face) AdvanceUnits ¶
AdvanceUnits is the horizontal advance of r in font units, or -1 when the face has no glyph for r.
func (*Face) BBoxWidth ¶
BBoxWidth is the width of the font's global bounding box (head xMax-xMin) in font units.
func (*Face) Data ¶
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) HasLigatures ¶
HasLigatures reports whether the face has GSUB standard ligature lookups.
func (*Face) LigMax ¶
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 ¶
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 ¶
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) OutlineGID ¶
OutlineGID is Outline for a glyph id.
func (*Face) RawMetrics ¶
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 ¶
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.
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).
type FontKind ¶
type FontKind string
FontKind says what container a font file was.
func Decode ¶
Decode turns a font file (WOFF2, WOFF, TrueType or OpenType; collections are not accepted) into a validated plain sfnt. It never panics.
func DetectKind ¶
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 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 ¶
NewWebFace makes a face that belongs to no set yet.
func (*WebFace) BeginLoad ¶
BeginLoad moves an Unloaded (or Failed, for a retry) face to Loading and reports whether the caller should fetch it.
func (*WebFace) 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 ¶
FaceAt is Face with the optical size (CSS px) for a variable font's opsz axis.
func (*WebFace) Redescribe ¶
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) SetData ¶
SetData installs decoded font data (a validated sfnt, see Decode). On failure the face becomes Failed.
type WebSet ¶
type WebSet struct {
// contains filtered or unexported fields
}
WebSet is the web fonts of one document.
func NewWebSet ¶
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) Close ¶
func (s *WebSet) Close()
Close drops the set: its scoped names stop resolving. Safe to call twice.
func (*WebSet) DeclGen ¶
DeclGen changes when the set of declared families or faces changes (not when a face merely loads). Style caches key on it.
func (*WebSet) DemandText ¶
DemandText demands every character of text for the family (document.fonts.load).
func (*WebSet) Match ¶
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) SetSheetFaces ¶
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.
Source Files
¶
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. |