layout

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: Apache-2.0, MIT Imports: 13 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 layout turns the neutral math IR into a deterministic display list.

It deliberately knows nothing about TeX, Typst, font file formats, or UI toolkits. Font data enters through the narrow ports in source.go. All intermediate geometry is fixed-point in ems; only flatten.go converts to the public float32 display contract.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidInput reports malformed layout input.
	ErrInvalidInput = errors.New("layout: invalid input")
	// ErrMissingGlyph reports a glyph source miss.
	ErrMissingGlyph = errors.New("layout: missing glyph")
	// ErrUnsupported reports a construct owned by a later work package.
	ErrUnsupported = errors.New("layout: unsupported construct")
	// ErrInsufficientStretch reports a required delimiter or accent that the
	// configured font ports could not extend to its target.
	ErrInsufficientStretch = errors.New("layout: insufficient stretch")
	// ErrLimit reports a configured resource limit.
	ErrLimit = errors.New("layout: limit exceeded")
)
View Source
var (
	// ThinSpace is the neutral TeX/OpenType thin math space (3/18 em).
	ThinSpace geometry.Em = 10_923
	// MediumSpace is the neutral medium math space (4/18 em).
	MediumSpace geometry.Em = 14_564
	// ThickSpace is the neutral thick math space (5/18 em).
	ThickSpace geometry.Em = 18_204
)

Functions

func MathSpacing

func MathSpacing(left, right ir.MathClass, style Style) geometry.Em

MathSpacing returns the automatic neutral inter-atom space in local ems. Cramped affects constructions, not inter-atom spacing.

func NormalizeClass

func NormalizeClass(previous *ir.MathClass, current ir.MathClass) ir.MathClass

NormalizeClass resolves context-sensitive atom classes the way TeX does: a varying operator becomes binary after an operand, while a binary operator in an operator position becomes ordinary.

Types

type Axis

type Axis uint8

Axis is a glyph stretch axis.

const (
	// Horizontal stretches a glyph or assembly to the right.
	Horizontal Axis = iota
	// Vertical stretches a glyph or assembly up and down.
	Vertical
)

type Fonts

type Fonts struct {
	Glyphs    GlyphSource
	Metrics   StyleFont
	Stretch   GlyphStretcher
	Text      TextSource
	Operators OperatorSource
}

Fonts are the ports required by the layout engine.

type Fragment

type Fragment struct {
	Metrics
	Class        ir.MathClass
	Size         MathSize
	Scale        geometry.Em
	Italic       geometry.Em
	BaseAscent   geometry.Em
	BaseDescent  geometry.Em
	AccentTop    geometry.Em
	AccentBottom geometry.Em
	InkBottom    geometry.Em
	HasInkBottom bool

	TextLike bool
	// StretchableHorizontal mirrors the base glyph's MATH construction.
	StretchableHorizontal bool
	// contains filtered or unexported fields
}

Fragment is the internal, immutable-after-construction layout tree. Items are stored in deterministic back-to-front order and positioned relative to the fragment's baseline origin.

func NewFragment

func NewFragment(metrics Metrics, class ir.MathClass, size MathSize, scale geometry.Em) (*Fragment, error)

NewFragment constructs an empty fragment for an extension port. Callers can add measured child groups, rules, or paths before returning it.

func (*Fragment) AddGroup

func (f *Fragment) AddGroup(x, y geometry.Em, child *Fragment) error

AddGroup places child relative to the receiver's baseline origin.

func (*Fragment) AddPath

func (f *Fragment) AddPath(x, y geometry.Em, path Path, paint ir.Paint) error

AddPath places a fillable path. Multiple contours use opposite winding when a hole is intended, so hosts can use either nonzero or even-odd filling.

func (*Fragment) AddRule

func (f *Fragment) AddRule(x, y, width, thickness geometry.Em, paint ir.Paint, vertical bool) error

AddRule places a horizontal or vertical filled rule.

type Glyph

type Glyph struct {
	ID      uint16
	FontID  string
	Text    string
	Advance geometry.Em
	Ascent  geometry.Em
	Descent geometry.Em
	Italic  geometry.Em
	// OriginY is the glyph origin's signed offset from the fragment baseline.
	// It is non-zero when a vertical MATH construction is centered on the
	// math axis while its outline stays at the font's original baseline.
	OriginY               geometry.Em
	AdvanceIncludesItalic bool
	TopAccent             geometry.Em
	HasTopAccent          bool
	BottomAccent          geometry.Em
	HasBottomAccent       bool
	// InkBottom is the signed y coordinate of the outline's lower edge relative
	// to the baseline. It may be negative for accents whose ink sits above the
	// baseline. Fill Outline or set HasInkBottom to preserve exact placement.
	InkBottom    geometry.Em
	HasInkBottom bool
	Kerns        MathKernInfo
	// StretchableHorizontal reports a MATH horizontal construction. Script
	// layout uses it to select the stretch-stack limit constants.
	StretchableHorizontal bool
	// ExactGlyphRef reports that ID, FontID, Advance, ascent, and descent
	// describe the complete drawn glyph, so hosts may cache and draw it by ID.
	ExactGlyphRef bool
	TextLike      bool
	Outline       Path
	// Parts carries the individual glyphs of a MATH assembly. Positions are
	// baseline-relative local ems. Outline is empty for a part-backed glyph.
	Parts []PositionedGlyph
}

Glyph is a shaped glyph in local ems. Advance is the final layout advance. AdvanceIncludesItalic reports that Italic has already been incorporated into Advance. Outline may be empty when the source only exposes a host glyph reference.

type GlyphFragment

type GlyphFragment struct {
	Glyph Glyph
	Scale geometry.Em
	Paint ir.Paint
}

GlyphFragment is one placed glyph in root ems. It is the internal bridge between a GlyphSource result and the flattening stage.

type GlyphRequest

type GlyphRequest struct {
	Context  context.Context
	Text     string
	Style    Style
	Variant  ir.Variant
	Font     ir.FontRole
	Features []string
}

GlyphRequest identifies one glyph lookup or shaping operation.

type GlyphSource

type GlyphSource interface {
	Glyph(req GlyphRequest) (Glyph, error)
}

GlyphSource is the only glyph-facing dependency of layout.

type GlyphStretcher

type GlyphStretcher interface {
	Stretch(req StretchRequest) (Glyph, error)
}

GlyphStretcher is an optional extension port for OpenType MATH variants and assemblies. Without it, an ordinary glyph is used only if it meets the target; otherwise layout returns ErrInsufficientStretch.

type KernCorner

type KernCorner uint8

KernCorner identifies one of the four corners in an OpenType MATH MathKernInfo table.

const (
	KernTopLeft KernCorner = iota
	KernTopRight
	KernBottomRight
	KernBottomLeft
)

type LayoutOptions added in v0.4.0

type LayoutOptions struct {
	RecoverVisible bool
}

LayoutOptions controls recoverable behavior for one layout call.

type MathKern

type MathKern struct {
	Heights []geometry.Em
	Kerns   []geometry.Em
}

MathKern is one corner's MathKernInfo table. Heights are strictly increasing and Kerns has exactly one more element.

type MathKernInfo

type MathKernInfo struct {
	TopLeft     *MathKern
	TopRight    *MathKern
	BottomRight *MathKern
	BottomLeft  *MathKern
}

MathKernInfo groups the optional kern tables attached to a glyph.

type MathMetrics

type MathMetrics struct {
	ScriptPercentScaleDown       int16
	ScriptScriptPercentScaleDown int16

	SpaceWidth geometry.Em
	XHeight    geometry.Em
	// CapHeight drives the minimum inline equation ascent.
	CapHeight geometry.Em
	// AccentBaseHeight and FlattenedAccentBaseHeight come from the font's
	// typographic metrics. Zero uses the New Computer Modern-compatible
	// fallbacks in normalized.
	AccentBaseHeight          geometry.Em
	FlattenedAccentBaseHeight geometry.Em
	// DisplayOperatorMinHeight is the minimum vertical extent for large
	// operators in display style.
	DisplayOperatorMinHeight geometry.Em

	AxisHeight geometry.Em

	SuperscriptShiftUp            geometry.Em
	SuperscriptShiftUpCramped     geometry.Em
	SuperscriptBottomMin          geometry.Em
	SuperscriptBaselineDropMax    geometry.Em
	SubscriptShiftDown            geometry.Em
	SubscriptTopMax               geometry.Em
	SubscriptBaselineDropMin      geometry.Em
	SubSuperscriptGapMin          geometry.Em
	SuperscriptBottomMaxWithSub   geometry.Em
	SpaceAfterScript              geometry.Em
	UpperLimitGapMin              geometry.Em
	UpperLimitBaselineRiseMin     geometry.Em
	LowerLimitGapMin              geometry.Em
	LowerLimitBaselineDropMin     geometry.Em
	StretchStackTopShiftUp        geometry.Em
	StretchStackBottomShiftDown   geometry.Em
	StretchStackGapAboveMin       geometry.Em
	StretchStackGapBelowMin       geometry.Em
	StackTopShiftUp               geometry.Em
	StackTopDisplayStyleShiftUp   geometry.Em
	StackBottomShiftDown          geometry.Em
	StackBottomDisplayShiftDown   geometry.Em
	StackGapMin                   geometry.Em
	StackDisplayStyleGapMin       geometry.Em
	FractionNumeratorShiftUp      geometry.Em
	FractionNumeratorDisplayUp    geometry.Em
	FractionDenominatorShiftDown  geometry.Em
	FractionDenominatorDisplayDn  geometry.Em
	FractionNumeratorGapMin       geometry.Em
	FractionNumeratorDisplayGap   geometry.Em
	FractionRuleThickness         geometry.Em
	FractionDenominatorGapMin     geometry.Em
	FractionDenominatorDisplayGap geometry.Em
	SkewedFractionVerticalGap     geometry.Em
	SkewedFractionHorizontalGap   geometry.Em
	OverbarVerticalGap            geometry.Em
	OverbarRuleThickness          geometry.Em
	OverbarExtraAscender          geometry.Em
	UnderbarVerticalGap           geometry.Em
	UnderbarRuleThickness         geometry.Em
	UnderbarExtraDescender        geometry.Em
	RadicalVerticalGap            geometry.Em
	RadicalDisplayStyleGap        geometry.Em
	RadicalRuleThickness          geometry.Em
	RadicalExtraAscender          geometry.Em
	RadicalKernBeforeDegree       geometry.Em
	RadicalKernAfterDegree        geometry.Em
	RadicalDegreeBottomRaisePct   int16
}

MathMetrics contains the font constants used by this layout layer. All values are base ems, independent of the math style. Layout applies the style scale exactly once; adapters must not pre-scale values by style.

This is intentionally a data port, not a font representation. A FontSet adapter extracts these constants from the OpenType MATH table once.

type MathSize

type MathSize uint8

MathSize is the typographic size component of a math style.

const (
	// Display is the size used for standalone equations.
	Display MathSize = iota
	// Text is the size used inside running text.
	Text
	// Script is the size used for first-level scripts.
	Script
	// ScriptScript is the smallest supported size.
	ScriptScript
)

type Metrics

type Metrics struct {
	Width   geometry.Em
	Ascent  geometry.Em
	Descent geometry.Em
}

Metrics are baseline-relative dimensions in root ems.

func (Metrics) Height

func (m Metrics) Height() (geometry.Em, error)

Height returns ascent+descent, reporting overflow.

type OperatorRequest

type OperatorRequest struct {
	Context  context.Context
	Text     string
	Style    Style
	Variant  ir.Variant
	Features []string
}

OperatorRequest identifies one named operator run. Operator text is set as a single upright run so scripts and limits attach to the complete name.

type OperatorSource

type OperatorSource interface {
	ShapeOperator(req OperatorRequest) (TextRun, error)
}

OperatorSource is an optional extension port for named operator runs.

type Options

type Options struct {
	Limits source.Limits
}

Options configures a Renderer. Zero limits use source.DefaultLimits.

type Path

type Path []Segment

Path is a glyph outline in local ems, y down, relative to the font glyph origin. Glyph.OriginY places that origin relative to the fragment baseline.

type Point

type Point struct {
	X geometry.Em
	Y geometry.Em
}

Point is a fixed-point point in local ems.

type PositionedGlyph

type PositionedGlyph struct {
	Glyph Glyph
	At    Point
	// Cluster is the zero-based index into TextRun.Clusters.
	Cluster int
	// Missing marks one synthetic glyph substituting for an unavailable text
	// cluster. Layout paints it with the error role.
	Missing bool
}

PositionedGlyph is one glyph in a shaped text run, in local ems relative to the run baseline. Cluster indexes TextRun.Clusters and is meaningful only when that slice is non-empty.

type Renderer

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

Renderer is an immutable layout engine. It is safe for concurrent use if its supplied font ports are safe for concurrent use.

func New

func New(fonts Fonts, options Options) (*Renderer, error)

New validates the required font ports and constructs a renderer.

func (*Renderer) Layout

func (r *Renderer) Layout(root ir.Node, mode ir.Mode, style display.Style) (*display.Box, error)

Layout lays out root with mode and display style.

func (*Renderer) LayoutContext

func (r *Renderer) LayoutContext(ctx context.Context, root ir.Node, mode ir.Mode, style display.Style) (*display.Box, error)

LayoutContext lays out root with cancellation and deterministic resource limits.

func (*Renderer) LayoutFormulaContext

func (r *Renderer) LayoutFormulaContext(ctx context.Context, formula *ir.Formula, mode ir.Mode, style display.Style) (*display.Box, error)

LayoutFormulaContext lays out a complete formula with cancellation and deterministic resource limits.

func (*Renderer) LayoutFormulaContextOptions added in v0.4.0

func (r *Renderer) LayoutFormulaContextOptions(
	ctx context.Context,
	formula *ir.Formula,
	mode ir.Mode,
	style display.Style,
	options LayoutOptions,
) (*display.Box, error)

LayoutFormulaContextOptions lays out a formula with per-call recovery behavior.

func (*Renderer) LayoutParsedFormulaContext

func (r *Renderer) LayoutParsedFormulaContext(ctx context.Context, formula *ir.Formula, stats ir.Stats, mode ir.Mode, style display.Style) (*display.Box, error)

LayoutParsedFormulaContext lays out a formula that was structurally validated and frozen by the parser boundary. Engine-configured limits and final output invariants are still enforced.

func (*Renderer) LayoutParsedFormulaContextOptions added in v0.4.0

func (r *Renderer) LayoutParsedFormulaContextOptions(
	ctx context.Context,
	formula *ir.Formula,
	stats ir.Stats,
	mode ir.Mode,
	style display.Style,
	options LayoutOptions,
) (*display.Box, error)

LayoutParsedFormulaContextOptions lays out parser-validated formula IR with per-call recovery behavior.

type Segment

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

Segment is one outline command in local ems. The Op field uses the public path operation vocabulary so flattening does not invent a second one.

type StretchRequest

type StretchRequest struct {
	GlyphRequest
	Axis      Axis
	Target    geometry.Em
	ShortFall geometry.Em
}

StretchRequest asks for a MATH size variant or assembly in local ems.

type Style

type Style struct {
	Size    MathSize
	Cramped bool
	// SizeScale is an absolute font-size multiplier relative to the root em.
	// Zero means the default multiplier (one). It is multiplied by the
	// display/text/script/script-script style scale at layout time.
	SizeScale geometry.Em
}

Style is one of the eight OpenType math styles: four sizes, each normal or cramped.

func (Style) Denominator

func (s Style) Denominator() Style

Denominator returns the style for a vertical fraction denominator.

func (Style) Numerator

func (s Style) Numerator() Style

Numerator returns the style for a vertical fraction numerator.

func (Style) String

func (s Style) String() string

String returns a stable diagnostic name.

func (Style) Subscript

func (s Style) Subscript() Style

Subscript returns the style for a subscript.

func (Style) Superscript

func (s Style) Superscript() Style

Superscript returns the style for a superscript. Display and text move to script; both script sizes move to script-script. Cramping is inherited.

func (Style) Validate

func (s Style) Validate() error

Validate checks that the style is one of the eight supported states.

func (Style) WithCramped

func (s Style) WithCramped(cramped bool) Style

WithCramped replaces the cramped flag.

func (Style) WithSize

func (s Style) WithSize(size MathSize) Style

WithSize replaces the size while preserving cramping.

type StyleFont

type StyleFont interface {
	MathMetrics(style Style, variant ir.Variant) MathMetrics
}

StyleFont supplies metrics for a math style and alphabet variant.

type TableLine

type TableLine struct {
	Position  int
	Count     int
	Dashed    bool
	Thickness geometry.Em
}

TableLine is a resolved table boundary used by the built-in table grid.

type TextCluster added in v0.4.0

type TextCluster struct {
	RuneStart int
	RuneEnd   int
	Source    source.Range
	FaceID    string
	Fallback  bool
	Missing   bool
	// RTL reports that this cluster was shaped in a right-to-left run. X still
	// describes its left edge in visual order.
	RTL bool
	// X and Advance are the cluster's horizontal extent in local ems relative
	// to the run origin. They are independent of per-glyph positioning offsets.
	X       geometry.Em
	Advance geometry.Em
}

TextCluster preserves the source extent of one shaping cluster. Byte offsets are relative to the text passed in TextRequest or OperatorRequest, not to the complete document source.

type TextRequest

type TextRequest struct {
	Context  context.Context
	Text     string
	Clusters []ir.TextClusterSource
	Style    Style
	Variant  ir.Variant
	Font     ir.FontRole
	// Tracking is unscaled base ems, independent of Style.Size. Shaping
	// produces base-em glyph positions; layout applies the style scale once.
	Tracking geometry.Em
	Features []string
}

TextRequest identifies a shaped text run.

type TextRun

type TextRun struct {
	Width   geometry.Em
	Ascent  geometry.Em
	Descent geometry.Em
	Italic  geometry.Em
	// Clusters is in visual glyph order and preserves source extents for editor
	// hit testing. It may be empty for non-text providers and synthetic runs.
	Clusters []TextCluster
	Glyphs   []PositionedGlyph
	// MissingFaces is the ordered face ID list attempted for this run. It is
	// populated only when at least one cluster is missing.
	MissingFaces []string
}

TextRun is a shaped one-line text run in local ems.

type TextSource

type TextSource interface {
	ShapeText(req TextRequest) (TextRun, error)
}

TextSource is an optional extension port for deterministic text shaping.

Jump to

Keyboard shortcuts

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