font

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0, MIT Imports: 25 Imported by: ? 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.

README

font package

font is Untie's immutable OpenType substrate. It accepts host-owned SFNT or TTC bytes and exposes design-unit metrics, cubic/quadratic outlines, MATH constants and constructions, Unicode variation mapping, and the ssty/dtls GSUB features needed by math layout.

Integration

set, err := font.LoadFontSet(font.FontSetConfig{
    Math: font.FontFace{
        Bytes: newCMMathBytes,
        Index: 0,
        ID:    "newcm-math-book-v4",
    },
})
if err != nil {
    // No partial FontSet is returned.
}

g, ok := set.MapRune(font.MathFace, '\U0001D465') // mathematical italic x
metrics, ok := set.GlyphMetrics(g)                // design units
outline, ok := set.Outline(g)                     // y-down design units
scaled, ok := set.ShapeMath(font.MathFace, []font.GlyphID{g.ID},
    font.ScriptVariant, false)

shaped, err := set.ShapeText(font.TextShapeRequest{
    Context: ctx,
    Text:    "a\u0301 सालाम 👩‍💻",
    Faces:   []font.FaceRef{font.TextFace, font.MathFace},
    MaxGlyphs: 4096,
})

FontSet is safe for concurrent readers. Outline returns a defensive copy; the internal cache is immutable. KeySHA256 is the collision-resistant font set identity. Key is the first 64 bits for host maps.

FontFace.Variations accepts arbitrary OpenType fvar axes in design-space units. Values are validated against the selected face; they are never clamped or interpolated by Untie. Omitted axes use fvar defaults and VariationCoordinates returns the complete effective position.

text := font.FontFace{
    Bytes: variableTextBytes,
    Variations: []font.Variation{{Tag: "wght", Value: 650}},
}

The substrate applies coordinates to TrueType/CFF2 outlines, HVAR/VVAR advances, MVAR metrics, GPOS deltas, and GSUB FeatureVariations. OpenType MATH constants, construction recipes, italic corrections, top accents, and cut-in kerns are static table data; constructions that reference glyphs still use varied glyph metrics and outlines. head font bounds remain static. These limits are part of the API contract rather than approximation rules.

Coordinates and advances are whole font design units. CFF 16.16 operands are quantized once to this integer grid by truncating toward zero. They are never rounded through a host or canvas pixel size. Sub-design-unit outline coordinates are intentionally not exposed by this API. Bounds are control bounds in y-down design units.

Intentional boundaries

  • The host supplies bytes and optional IDs. There is no system font lookup, family matching, or environment-dependent fallback.
  • Variable configuration is per face. Unknown axes, out-of-range values, duplicate axes, non-finite values, and coordinates on static faces are rejected at load.
  • Empty IDs are derived from role, metadata, selected index, and bytes. Explicit IDs must be nonblank and unique across the math, text, and fallback faces.
  • The primary math face must contain OpenType MATH constants.
  • ssty and dtls are parsed locally because ssty requires alternate-feature values. Lookup flags on those math features are rejected at load rather than silently ignored.
  • Public feature tags are exact, case-sensitive four-byte OpenType tags. Disabled and unsupported values are ignored. Shape preserves caller order; ShapeMath always applies dtls before ssty.
  • MathConstruction exposes variants and the complete assembly recipe: assembly italic correction, minimum connector overlap, ordered parts, part glyph IDs, connector lengths, full advances, and extender flags. Variant selection remains a layout policy and is not implemented in font.
  • Ordinary text runs use the pure-Go HarfBuzz shaper from go-text/typesetting after Unicode bidi and script segmentation. Fallback is resolved once per extended grapheme cluster, and shaped clusters retain byte and rune ranges for editor hit testing. ShapedCluster.RTL records the shaping run's direction so caret affinity is not inferred from source order.
  • When one face covers a complete bidi/script run, it is preferred for the whole run so joining and reordering stay intact. For non-Latin, non-Greek, and non-Cyrillic scripts, a supplied text or fallback face is preferred over the MATH face when both have nominal coverage.
  • Math symbols, stretchy constructions, and named operators remain on the dedicated cmap/MATH/GSUB path. General text ligatures and kerning do not leak into formula-symbol layout.
  • Font parsing and shaping support are pure Go and require no cgo toolchain.

Compatibility

The package is validated against a pinned New Computer Modern Math Book reference covering all 8,598 glyph advances, control bounds, italic corrections, accent attachments, extended-shape membership, kerns, variants, assemblies, cmap entries, variation sequences, and ssty/dtls shaping.

Four variation-sequence glyphs (8465, 8480, 8481, and 8483) differ by one design unit because ttf-parser composes their legacy CFF endchar-seac components while Untie's outline parser does not. U+FFFF maps to .notdef and public rune lookup reports it as unmapped. Untie also retains the one spec-defined left-corner kern omitted by the reference data for prescript layout.

Documentation

Overview

Package font defines host-supplied font inputs and parsed font sets.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidText reports a malformed text-shaping request.
	ErrInvalidText = errors.New("font: invalid text shaping request")
	// ErrTextLimit reports that shaped output exceeded the caller's budget.
	ErrTextLimit = errors.New("font: text glyph limit exceeded")
)

Functions

This section is empty.

Types

type Assembly

type Assembly struct {
	ItalicCorrection    int32
	MinConnectorOverlap int32
	Parts               []AssemblyPart
}

Assembly is the complete recipe for constructing a stretchy glyph. Parts retain OpenType order, and the first and last parts are the endpoint glyphs.

type AssemblyPart

type AssemblyPart struct {
	Glyph          GlyphID
	StartConnector int32
	EndConnector   int32
	FullAdvance    int32
	Extender       bool
}

AssemblyPart is one component of a stretchy-glyph assembly.

type Bounds

type Bounds struct {
	XMin int32
	YMin int32
	XMax int32
	YMax int32
}

Bounds is a design-unit control bounding box in the same y-down coordinate space as Outline. It includes Bezier control points, matching OpenType MATH/font tooling bounds. YMin is the top edge and YMax is the bottom edge.

func (Bounds) Empty

func (b Bounds) Empty() bool

Empty reports whether the bounds contain no ink.

func (Bounds) Height

func (b Bounds) Height() int32

Height returns the vertical extent.

func (Bounds) Width

func (b Bounds) Width() int32

Width returns the horizontal extent.

type FaceInfo

type FaceInfo struct {
	ID             string
	Index          int
	PostScriptName string
	UnitsPerEm     uint16
	GlyphCount     int
	HasMath        bool
	Variable       bool
}

FaceInfo is immutable metadata for one loaded face.

type FaceRef

type FaceRef uint8

FaceRef identifies a face in a loaded FontSet. Fallback faces are numbered from fallbackFaceBase in their input order.

const (
	// MathFace is the primary math face supplied in FontSetConfig.Math.
	MathFace FaceRef = iota
	// TextFace is the optional text face supplied in FontSetConfig.Text.
	TextFace
)

func FallbackFace

func FallbackFace(i int) (FaceRef, bool)

FallbackFace returns the FaceRef for fallback index i.

type Feature

type Feature struct {
	Tag   string
	Value uint16
}

Feature is one GSUB feature request. Value follows OpenType alternate-feature numbering: ssty=1 selects the first alternate and ssty=2 the second.

type FontFace

type FontFace struct {
	ID         string
	Bytes      []byte
	Index      int
	Variations []Variation
}

FontFace is one face from a host-provided SFNT or TTC file.

ID is optional when the face is passed to LoadFontSet, LoadMathFont, or another high-level source helper. Empty IDs are derived deterministically.

type FontOption

type FontOption func(*FontFace)

FontOption configures one face passed to LoadMathFont.

func WithFontID

func WithFontID(id string) FontOption

WithFontID sets an explicit stable face ID. A blank ID is treated like an omitted ID and is derived by LoadMathFont.

func WithFontIndex

func WithFontIndex(index int) FontOption

WithFontIndex selects a face in a TrueType/OpenType collection.

func WithFontVariations added in v0.4.0

func WithFontVariations(variations ...Variation) FontOption

WithFontVariations sets OpenType design-variation coordinates for one face. Omitted axes use the defaults declared in the font's fvar table.

type FontSet

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

FontSet is an immutable parsed font collection with a concurrency-safe glyph outline cache.

func LoadFontSet

func LoadFontSet(config FontSetConfig) (*FontSet, error)

LoadFontSet validates and prepares host fonts. It accepts SFNT and TTC data. Empty face IDs are derived deterministically. Explicit IDs must be nonblank and unique. All font bytes are copied before parsing.

func LoadMathFont

func LoadMathFont(data []byte, opts ...FontOption) (*FontSet, error)

LoadMathFont prepares one math face. The face ID is derived when opts do not provide one. The face must contain OpenType MATH constants.

func (*FontSet) Config

func (f *FontSet) Config() FontSetConfig

Config returns an independent copy of the input font configuration.

func (*FontSet) Face

func (f *FontSet) Face(ref FaceRef) (FaceInfo, bool)

Face returns immutable metadata for ref.

func (*FontSet) FaceCount

func (f *FontSet) FaceCount() int

FaceCount returns the number of loaded faces.

func (*FontSet) Features

func (f *FontSet) Features(ref FaceRef) ([]string, bool)

Features returns the supported math GSUB feature tags in lexical order.

func (*FontSet) GlyphAdvance

func (f *FontSet) GlyphAdvance(g Glyph) (int32, bool)

GlyphAdvance returns the design-unit advance width of one glyph.

func (*FontSet) GlyphMetrics

func (f *FontSet) GlyphMetrics(g Glyph) (GlyphMetrics, bool)

GlyphMetrics returns design-unit metrics for one glyph.

func (*FontSet) HasFeature

func (f *FontSet) HasFeature(ref FaceRef, tag string) bool

HasFeature reports whether ref has a supported ssty or dtls rule.

func (*FontSet) IsExtendedShape

func (f *FontSet) IsExtendedShape(g Glyph) (bool, bool)

IsExtendedShape reports whether a glyph is in MATH ExtendedShapeCoverage.

func (*FontSet) ItalicCorrection

func (f *FontSet) ItalicCorrection(g Glyph) (int32, bool)

ItalicCorrection returns the MATH italic correction in design units.

func (*FontSet) Key

func (f *FontSet) Key() uint64

Key returns a stable 64-bit cache key. Use KeySHA256 when collision-resistant identity is required.

func (*FontSet) KeySHA256

func (f *FontSet) KeySHA256() [32]byte

KeySHA256 returns the canonical SHA-256 identity of the font set.

func (*FontSet) MapRune

func (f *FontSet) MapRune(ref FaceRef, r rune) (Glyph, bool)

MapRune maps r through ref's cmap.

func (*FontSet) MapVariation

func (f *FontSet) MapVariation(ref FaceRef, r, selector rune) (Glyph, bool)

MapVariation maps a base rune and Unicode variation selector.

func (*FontSet) MathConstant

func (f *FontSet) MathConstant(ref FaceRef, c MathConstant) (int32, bool)

MathConstant returns one design-unit MATH constant. Percentage constants are returned as literal percentages. OpenType MATH constants are static table data; variable-axis coordinates do not change these values.

func (*FontSet) MathConstruction

func (f *FontSet) MathConstruction(g Glyph, axis MathAxis) (MathConstruction, bool)

MathConstruction returns size variants and an optional assembly recipe. The recipe and variant advances come from the static MATH table; variable coordinates apply to the metrics and outlines of referenced glyphs.

func (*FontSet) MathKern

func (f *FontSet) MathKern(g Glyph, corner MathKernCorner, correctionHeight int32) int32

MathKern evaluates a glyph's MATH cut-in kern at correctionHeight design units.

func (*FontSet) MathKernCurve

func (f *FontSet) MathKernCurve(g Glyph, corner MathKernCorner) (KernCurve, bool)

MathKernCurve returns a defensive copy of a glyph's MATH cut-in kern curve.

func (*FontSet) Outline

func (f *FontSet) Outline(g Glyph) (Outline, bool)

Outline returns a defensive copy of a glyph's unhinted y-down outline.

func (*FontSet) Shape

func (f *FontSet) Shape(ref FaceRef, glyphs []GlyphID, features ...Feature) ([]GlyphID, bool)

Shape applies one-to-one math GSUB features in request order and returns a new glyph slice. Tags must be exact, case-sensitive four-byte OpenType tags. Disabled (zero-valued) and unsupported features are ignored.

func (*FontSet) ShapeMath

func (f *FontSet) ShapeMath(ref FaceRef, glyphs []GlyphID, style MathScriptStyle, flatten bool) ([]GlyphID, bool)

ShapeMath applies the standard math substitutions in Typst's canonical order: optional dtls first, then the style-appropriate ssty alternate.

func (*FontSet) ShapeText added in v0.4.0

func (f *FontSet) ShapeText(req TextShapeRequest) (ShapedText, error)

ShapeText shapes one text run using the supplied ordered face list.

func (*FontSet) TopAccentAttachment

func (f *FontSet) TopAccentAttachment(g Glyph) (int32, bool)

TopAccentAttachment returns the MATH top-accent attachment point in design units from the glyph origin.

func (*FontSet) VariationAxes added in v0.4.0

func (f *FontSet) VariationAxes(ref FaceRef) ([]VariationAxis, bool)

VariationAxes returns an independent copy of ref's OpenType fvar axes. The second result is false when ref is not present. A present static face returns an empty slice and true.

func (*FontSet) VariationCoordinates added in v0.4.0

func (f *FontSet) VariationCoordinates(ref FaceRef) ([]Variation, bool)

VariationCoordinates returns the complete resolved design-space position for ref, including defaults for axes not explicitly configured. Axes are returned in fvar order.

func (*FontSet) VerticalMetrics

func (f *FontSet) VerticalMetrics(ref FaceRef) (VerticalMetrics, bool)

VerticalMetrics returns design-unit vertical metrics for ref.

type FontSetConfig

type FontSetConfig struct {
	Math      FontFace
	Text      *FontFace
	Fallbacks []FontFace
}

FontSetConfig configures a validated font collection. Math must contain OpenType MATH constants. Fallback order is deterministic.

type Glyph

type Glyph struct {
	Face FaceRef
	ID   GlyphID
}

Glyph identifies a glyph and the face that owns it.

type GlyphID

type GlyphID uint16

GlyphID is an OpenType glyph index.

type GlyphMetrics

type GlyphMetrics struct {
	Advance    int32
	Bounds     Bounds
	HasOutline bool
}

GlyphMetrics contains unhinted design-unit metrics for one glyph.

type KernCurve

type KernCurve struct {
	Heights []int32
	Kerns   []int32
}

KernCurve is a MATH cut-in kerning step function. Heights contains n values in ascending order and Kerns contains n+1 values.

func (KernCurve) At

func (k KernCurve) At(h int32) int32

At returns the kern value for correction height h.

type MathAxis

type MathAxis uint8

MathAxis selects a glyph construction axis.

const (
	VerticalAxis MathAxis = iota
	HorizontalAxis
)

type MathConstant

type MathConstant uint8

MathConstant identifies a value from the OpenType MATH constants table. Lengths are returned in design units. The three percentage constants are returned as their literal percentage value.

const (
	ScriptPercentScaleDown MathConstant = iota
	ScriptScriptPercentScaleDown
	DelimitedSubFormulaMinHeight
	DisplayOperatorMinHeight
	MathLeading
	AxisHeight
	AccentBaseHeight
	FlattenedAccentBaseHeight
	SubscriptShiftDown
	SubscriptTopMax
	SubscriptBaselineDropMin
	SuperscriptShiftUp
	SuperscriptShiftUpCramped
	SuperscriptBottomMin
	SuperscriptBaselineDropMax
	SubSuperscriptGapMin
	SuperscriptBottomMaxWithSubscript
	SpaceAfterScript
	UpperLimitGapMin
	UpperLimitBaselineRiseMin
	LowerLimitGapMin
	LowerLimitBaselineDropMin
	StackTopShiftUp
	StackTopDisplayStyleShiftUp
	StackBottomShiftDown
	StackBottomDisplayStyleShiftDown
	StackGapMin
	StackDisplayStyleGapMin
	StretchStackTopShiftUp
	StretchStackBottomShiftDown
	StretchStackGapAboveMin
	StretchStackGapBelowMin
	FractionNumeratorShiftUp
	FractionNumeratorDisplayStyleShiftUp
	FractionDenominatorShiftDown
	FractionDenominatorDisplayStyleShiftDown
	FractionNumeratorGapMin
	FractionNumDisplayStyleGapMin
	FractionRuleThickness
	FractionDenominatorGapMin
	FractionDenomDisplayStyleGapMin
	SkewedFractionHorizontalGap
	SkewedFractionVerticalGap
	OverbarVerticalGap
	OverbarRuleThickness
	OverbarExtraAscender
	UnderbarVerticalGap
	UnderbarRuleThickness
	UnderbarExtraDescender
	RadicalVerticalGap
	RadicalDisplayStyleVerticalGap
	RadicalRuleThickness
	RadicalExtraAscender
	RadicalKernBeforeDegree
	RadicalKernAfterDegree
	RadicalDegreeBottomRaisePercent

	// MathConstantCount is the number of MATH constants, not a constant.
	MathConstantCount
)

func (MathConstant) String

func (c MathConstant) String() string

String returns the OpenType name for c.

type MathConstruction

type MathConstruction struct {
	Variants []SizeVariant
	Assembly *Assembly
}

MathConstruction contains the pre-drawn variants and optional assembly for a glyph along one axis.

type MathKernCorner

type MathKernCorner uint8

MathKernCorner identifies one of the four corners in a MATH cut-in kerning record.

const (
	MathKernTopRight MathKernCorner = iota
	MathKernTopLeft
	MathKernBottomRight
	MathKernBottomLeft
)

type MathScriptStyle

type MathScriptStyle uint8

MathScriptStyle selects the ssty alternate used by ShapeMath.

const (
	NoScriptVariant MathScriptStyle = iota
	ScriptVariant
	ScriptScriptVariant
)

type Outline

type Outline struct {
	Glyph    Glyph
	Bounds   Bounds
	Segments []Segment
}

Outline is an immutable snapshot of a glyph's unhinted outline. Coordinates are whole design units; sub-design-unit CFF precision is not represented by this API. The returned value owns its Segments slice, so mutation cannot affect the font cache.

type Point

type Point struct {
	X int32
	Y int32
}

Point is a whole design-unit outline coordinate. Fractional CFF coordinates are truncated toward zero once when the font is loaded, matching the pinned Typst/ttf-parser oracle.

type Segment

type Segment struct {
	Op     geometry.SegOp
	Points [3]Point
}

Segment is one command in a glyph outline. Coordinates are font design units in y-down orientation with the baseline at y=0. MoveTo and LineTo use Points[0], QuadTo uses Points[0:2], CubeTo uses all three points, and Close uses none.

type ShapedCluster added in v0.4.0

type ShapedCluster struct {
	RuneStart int
	RuneEnd   int
	ByteStart int
	ByteEnd   int
	Face      FaceRef
	// RTL reports that the cluster was shaped in a right-to-left run. Clusters
	// remain stored in visual order; this flag lets source maps recover caret
	// affinity within a cluster.
	RTL bool
	// Missing reports that the selected face does not cover every significant
	// rune in the cluster, or that OpenType shaping produced .notdef.
	Missing bool
}

ShapedCluster identifies the source runes represented by a shaping cluster. Rune and byte offsets are relative to TextShapeRequest.Text.

type ShapedGlyph added in v0.4.0

type ShapedGlyph struct {
	Glyph     Glyph
	Advance   int32
	XOffset   int32
	YOffset   int32
	Cluster   int
	Invisible bool
}

ShapedGlyph is one positioned glyph in font design units. Cluster indexes ShapedText.Clusters. Invisible records carry advances for default-ignorable characters but have no drawable glyph.

type ShapedText added in v0.4.0

type ShapedText struct {
	Clusters []ShapedCluster
	Glyphs   []ShapedGlyph
}

ShapedText is a visually ordered, one-line text run.

type SizeVariant

type SizeVariant struct {
	Glyph   GlyphID
	Advance int32
}

SizeVariant is one pre-drawn size of a stretchy glyph.

type TextDirection added in v0.4.0

type TextDirection uint8

TextDirection selects the paragraph direction used by bidi reordering.

const (
	TextDirectionLTR TextDirection = iota
	TextDirectionRTL
)

type TextShapeRequest added in v0.4.0

type TextShapeRequest struct {
	Context   context.Context
	Text      string
	Faces     []FaceRef
	Features  []Feature
	Direction TextDirection
	Language  string
	MaxGlyphs int
}

TextShapeRequest describes one bidirectional, fallback-aware text run.

Faces are tried in order. Fallback is selected per extended grapheme cluster, so combining marks and emoji ZWJ sequences are never split merely to change fonts. MaxGlyphs bounds the total number of output glyph records; zero leaves the request unbounded and is intended only for trusted callers.

type Variation added in v0.4.0

type Variation struct {
	Tag   string
	Value float32
}

Variation selects a value on one OpenType design-variation axis.

Values are expressed in the font's design coordinate space, not normalized CSS coordinates. Tag must be an exact four-byte OpenType axis tag such as "wght" or "wdth".

type VariationAxis added in v0.4.0

type VariationAxis struct {
	Tag     string
	Minimum float32
	Default float32
	Maximum float32
}

VariationAxis describes one axis declared by a face's OpenType fvar table.

type VerticalMetrics

type VerticalMetrics struct {
	Ascender  int32
	Descender int32
	LineGap   int32
	CapHeight int32
	XHeight   int32
	// FontBounds is the static head-table bounding box. It is not recomputed
	// from variable glyph outlines.
	FontBounds Bounds
}

VerticalMetrics are design-unit font metrics.

Jump to

Keyboard shortcuts

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