onefont

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0, MIT Imports: 23 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.

README

onefont for Go

Pure-Go font parsing, OpenType text shaping, bidi, text segmentation and font fallback. Written from scratch for Go, with no cgo, no unsafe and nothing outside the standard library.

go get recursiveai.org/go/onefont

Requires Go 1.24 or newer. The import path is recursiveai.org/go/onefont and the package is onefont.

Quick start

Fonts come in as byte slices; the library opens no files and finds no system fonts. Errors are values you match with errors.Is.

Load a font and shape a string

data, _ := os.ReadFile("NotoSans-Regular.ttf")
face, err := onefont.Parse(data)
if err != nil {
	log.Fatal(err)
}
run, err := onefont.Shape("Hello", face)
if err != nil {
	log.Fatal(err)
}
for i, g := range run.All() {
	fmt.Println(i, g.Glyph, g.Cluster, g.AdvanceX)
}

Glyph IDs, clusters (byte offsets into the text), advances and offsets come back in font units, in the visual order hb-shape prints them. Script and direction are taken from the text; options (WithDirection, WithScript, WithLanguage, WithFeatures) override them.

Mixed-direction text with font fallback

chain := onefont.NewFallbackChain(latin, hebrew, emoji) // *Face or *Instance values
for sr, err := range onefont.ShapeText("abc אבג 123", chain) {
	if err != nil {
		log.Fatal(err)
	}
	// sr.Start and sr.End are byte offsets in the text, sr.Font indexes the
	// chain, sr.Level is the bidi level, sr.Run holds the glyphs.
	// Runs arrive in visual order, left to right.
	draw(sr)
}

ShapeText resolves bidi (UAX #9), picks a font per grapheme cluster, shapes every piece with its own font in its own direction and yields the pieces as they are displayed. See ExampleShaper_ShapeText.

Break lines

for b := range onefont.LineBreaks(text) {
	fmt.Println(b.Pos, b.Mandatory) // a line may end before byte b.Pos
}
for line, forced := range onefont.Lines(text) {
	fmt.Printf("%q %v\n", line, forced)
}

See ExampleLineBreaks and ExampleLines. Graphemes, words and sentences work the same way (Graphemes, Words, Sentences and the …Breaks forms).

Glyph outlines

path, err := face.GlyphPath(face.GlyphIndex('A'))
if err != nil {
	log.Fatal(err)
}
// Outlines are y up. Scale to 16 px per em and flip for a y-down canvas:
path.Transform(onefont.Scale(16/float32(face.UnitsPerEm()), -16/float32(face.UnitsPerEm())))
for seg := range path.All() {
	fmt.Println(seg.Kind, seg.Pts) // PathMove, PathLine, PathQuad, PathCubic, PathClose
}

See ExampleFace_GlyphPath, ExampleFace_Outline and ExampleScale.

Two layers

The happy path is built from the low-level API and uses nothing you cannot reach yourself. The low layer gives full access: Parse a Face, read its tables (Face.Table), look up glyphs, draw outlines into your own PathSink, make an Instance of a variable font, fill a reusable Run with a Shaper, resolve a Bidi, cut text with a Segmenter, split it over a FallbackChain. Keep a Shaper and a Run and shaping allocates nothing once their buffers have grown. The package documentation (go doc onefont) has the map of the API, the units and offsets rules and the concurrency table.

Features

  • Fonts: TrueType (glyf), OpenType CFF and CFF2, TrueType Collections; cmap (formats 0, 4, 6, 10, 12, 13 and 14 variation selectors), head, hhea, hmtx, OS/2, name, post, kern, GDEF, GSUB, GPOS; metrics, names, outlines into a small path sink (move, line, quad, cubic), bounds and affine transforms.
  • Variable fonts: fvar, avar, gvar, HVAR, MVAR, CFF2 blends and item variation stores; named instances; feature variations.
  • Shaping: GSUB lookups 1 to 8 and GPOS lookups 1 to 9 with every lookup flag, mark filtering sets, contextual and chained lookups and extension lookups; features and BCP 47 languages mapped to OpenType language systems; script itemisation. Shapers for Arabic (with Syriac and N'Ko), the Indic scripts, Khmer, Myanmar, Tibetan, the Universal Shaping Engine scripts, Thai and Lao, and Hangul.
  • Bidi: UAX #9 at Unicode 17.0.0: paragraph and explicit levels, isolates, brackets, line reordering (rules L1 and L2) and mirroring lookup.
  • Segmentation: UAX #14 line breaks (with the mandatory flag) and UAX #29 grapheme, word and sentence boundaries, default rules, Unicode 17.0.0. Line breaking also finds word boundaries in Thai, Lao, Khmer and Burmese text with built-in word lists (Segmenter.NoDictionary turns that off).
  • Fallback: a font per grapheme cluster over a chain of faces you supply, each run shaped with its own font's tables.
  • Unicode data: generated from the Unicode Character Database by tools/ucdgen (cd tools && go run ./ucdgen -check verifies the checked-in tables against the pinned source files); Unicode 17.0.0.

Limits and untrusted input

Fonts and text are treated as hostile. Nothing a font or a text contains makes a function panic or run without bound: every offset and count is checked against its table, outline and charstring interpreters bound their stack and nesting, composite glyphs detect cycles, variation data bounds its region and tuple counts, and shaping keeps work, nesting and growth budgets. A lookup that would exceed a budget stops being applied and the result is a valid run; a request whose result would outgrow the absolute growth limit, or a text over 1 GiB, returns an error that wraps ErrLimit. Other errors wrap ErrInvalidFont, ErrUnsupportedFormat, ErrFaceIndex, ErrGlyphID, ErrInvalidArgument or ErrNotFound. Library code opens no files, uses no network and runs no programs.

What it does not do

Rasterizing glyphs, running a hinting program, COLR painting, vertical layout and paragraph layout belong to the programs built on top. GlyphDescription and Hinting give a hinting interpreter the points, instructions and tables it needs. Parse reads plain fonts only; UnwrapWebFont unpacks WOFF and WOFF2 files first.

Conformance

onefont is tested against the Unicode conformance files and against the onefont conformance kit, a language-neutral suite of cases whose expectations come from the specifications and from HarfBuzz's output, shared by the onefont libraries for other languages.

Suite Cases Pass Not matched
Bidi (UAX #9: BidiTest, BidiCharacterTest) 582,553 582,553 0
Segmentation (UAX #14, #29 conformance files and kit cases) 25,063 25,052 11: dictionary line-breaking cases whose word lists differ from the reference's
Unicode properties 4,837 4,837 0
Parse 922 922 0
Fallback 86 86 0
Shape 3,037 3,034 3: Tai Tham, which differ from the reference shaper

The Unicode conformance files are not stored here. To run them, set ONEFONT_CONFORMANCE_DIR to a directory holding BidiTest.txt, BidiCharacterTest.txt, GraphemeBreakTest.txt, WordBreakTest.txt, SentenceBreakTest.txt and LineBreakTest.txt from https://www.unicode.org/Public/17.0.0/ucd/; without it those tests are skipped. Fuzz targets cover the parsers, the shaper and the bidi, segmentation and fallback code (go test -fuzz).

Performance

Measured with bench/run.sh (method, inputs and fonts in bench/README.md) on an AMD Ryzen 9 7950X3D (32 threads), Linux, Go 1.26.8, GOMAXPROCS=1, alone on the machine (load average 1.0 to 1.4 for the whole run), 10 runs per row, medians. Before any row is timed, the libraries' outputs are checked to agree (glyphs, clusters, advances and offsets; outlines; runs; boundaries). The ratio is the other library's time divided by onefont's, so above 1 means onefont is faster. onefont allocates nothing per call in every steady-state row.

Row onefont golang.org/x/image/font/sfnt github.com/go-text/typesetting
Parse a TrueType face 365 ns 9.2× 828×
Parse a CFF face 369 ns 20× 211×
Parse, then cmap, advance and one outline (TrueType / CFF) 2.7 / 5.3 µs 1.5× / 1.8× 114× / 15×
cmap lookups of a text (TrueType / CFF) 1.2 / 0.8 µs 3.6× / 2.6× 1.1× / 1.3×
Advances (TrueType / CFF) 1.4 / 0.9 µs 2.5× / 2.5× 1.9× / 1.9×
Glyph outlines (TrueType / CFF) 128 / 147 µs 2.0× / 1.8× 2.1× / 4.5×
Shaping a paragraph onefont github.com/go-text/typesetting/shaping
Latin 109 µs 1.12×
Arabic 111 µs 1.23×
Devanagari 456 µs 1.02×
Thai 90 µs 1.48×
CJK 32 µs 1.88×
Mixed scripts 87 µs 1.44×
Text onefont golang.org/x/text/unicode/bidi github.com/rivo/uniseg
Bidi (English / mixed / CJK) 22 / 12 / 19 µs 1.6× / 1.9× / 1.6×
Graphemes (4 texts) 4.3–8.3 µs 1.1×–3.1×
Line breaks (4 texts) 8.3–18.5 µs 1.3×–2.5×
Words (4 texts) 5.3–10.3 µs 1.5×–1.7×
Sentences (4 texts) 3.1–6.0 µs 2.8×–3.0×

Versions compared: golang.org/x/image v0.48.0, golang.org/x/text v0.44.0, github.com/go-text/typesetting v0.3.5, github.com/rivo/uniseg v0.4.7.

Licence

Licensed under either of the MIT licence (LICENSE-MIT) or the Apache License 2.0 (LICENSE-APACHE), at your option. Copyright Recursive AI, LLC.

The Unicode Character Database tables generated into this module are covered by the Unicode License v3. The word lists behind dictionary line breaking come from the ICU project's data files; their notices are in THIRD-PARTY-NOTICES.md.

The Brotli decoder's static dictionary (internal/brotli/dictionary.bin) is the one published in Appendix A of RFC 7932, generated by tools/brotligen. The Brotli format and dictionary are by Google and are published under the MIT licence (Copyright 2013 Google Inc.).

Documentation

Overview

Package onefont parses fonts and shapes text in pure Go: sfnt, TrueType and CFF fonts, OpenType shaping with the Arabic, Indic, USE, Thai/Lao and Hangul shapers, Unicode bidi (UAX #9), line and text segmentation (UAX #14, UAX #29) and font fallback. It uses only the standard library and reads no files: fonts come in as byte slices.

Two layers

The low layer gives full access: Parse a Face, read its tables, look up glyphs, draw outlines into a PathSink, make an Instance of a variable face, fill a Run with a reusable Shaper, resolve a Bidi, cut text with a Segmenter, split it over a FallbackChain. The happy path is built from those pieces and needs one call each:

face, err := onefont.Parse(data)                     // see [Parse]
run, err := onefont.Shape("Hello", face)             // see [Shape]
for sr, err := range onefont.ShapeText(text, chain)  // see [ShapeText]
for b := range onefont.LineBreaks(text)              // see [LineBreaks]
path, err := face.GlyphPath(face.GlyphIndex('A'))    // see [Face.GlyphPath]

Fonts

Parse reads the table directory and keeps the caller's bytes; tables are read when asked for, every offset and count is checked, and a damaged font gives an error that wraps ErrInvalidFont (or ErrUnsupportedFormat, ErrFaceIndex, ErrGlyphID), never a panic. The caller must not change the bytes while the Face is in use. TrueType, CFF, CFF2 and TrueType Collections are read; WOFF and WOFF2 files are unpacked first with UnwrapWebFont. Font is implemented by *Face and *Instance, and is what shaping, fallback and kerning take.

Shaping

Shape and Shaper.Shape take UTF-8 text and a Font and return the glyphs in the visual order hb-shape prints them: glyph IDs, clusters, advances and offsets. A Shaper keeps its buffers and lookup plans, so shaping into a reused Run allocates nothing once they have grown. Options set the direction, script, language and features. Shaping applies GSUB and GPOS with all lookup types and flags, and the script's own shaper. Hostile fonts and texts are bounded: work, nesting and growth budgets stop a lookup that would exceed them, and the result is then a valid run that a well-formed font would not have given.

Bidi and fallback

Shaper.ShapeText shapes text of any mix of directions and fonts: it resolves bidi per paragraph, picks a font per grapheme cluster from a FallbackChain, shapes every piece in its own font and direction and yields the pieces in display order. Bidi and FallbackChain can also be used on their own.

Segmentation

Segmenter and the iterator functions (LineBreaks, Lines, GraphemeBreaks, Graphemes, WordBreaks, Words, SentenceBreaks, Sentences) implement the default rules of UAX #14 and UAX #29 for Unicode 17.0.0. Every list of boundaries holds the boundaries after offset 0, up to and including len(text).

Outlines

Face.Outline and Instance.Outline draw into a PathSink; Path records them and Path.Transform moves them with an Affine. Outlines are in font units, y up. TrueType outlines use quadratic curves and CFF outlines cubic ones; neither is converted.

Units and offsets

Positions in text are byte offsets into the UTF-8 string, everywhere: clusters, break lists, run ranges, bidi paragraph and run bounds. The one exception is Bidi.Levels and Bidi.LineLevels, which have one entry per rune. Invalid UTF-8 is read as one U+FFFD per invalid byte.

Font-space quantities follow one rule. Integer quantities in font design units (advances, bearings, metrics, kerning, glyph offsets in a Run) are int32. Fractional quantities (outline points, bounds, variation axis values) are float32. Counts and indices are int. A variable font's advances and metrics are rounded to whole font units, halves up, at the instance, and shaping rounds each glyph's advance, so a run's width is the sum of the rounded advances, as hb-shape reports it. The script of a shaping call is an ISO 15924 code ("Latn", "Arab"), and OpenType tags are Tag values.

Concurrency

A Face and an Instance are immutable and safe for concurrent use. A Shaper, Bidi, Segmenter and FallbackChain keep scratch buffers and are not safe for concurrent use; use one per goroutine. They are meant to be reused. A Run filled by a Shaper, and the slices a Bidi returns, belong to the caller until the next call that fills them. The package-level functions (Shape, ShapeText, LineBreaks and the like) use their own state and are safe for concurrent use; Shaper.ShapeText only reads the chain it is given, so a chain may be shared.

Errors and limits

Errors are values to match with errors.Is: the font classes above, ErrInvalidArgument for a nil font or an empty chain, ErrLimit for a text longer than 1 GiB, ErrNotFound for a name that matches nothing. No input makes a function in this package panic or run without bound; a limit that a call reaches either returns an error or, inside shaping, shortens the work as described at Shape.

Example (DictionaryLineBreaks)
text := "สวัสดีครับ"
var s Segmenter
prev := 0
for _, b := range s.AppendLineBreaks(nil, text) {
	fmt.Println(text[prev:b.Pos])
	prev = b.Pos
}
// With the dictionary off, UAX #14 alone treats the run as one word.
s.NoDictionary = true
fmt.Println(len(s.AppendLineBreaks(nil, text)))
Output:
สวัสดี
ครับ
1

Index

Examples

Constants

View Source
const (
	PlatformUnicode   = 0
	PlatformMacintosh = 1
	PlatformWindows   = 3
)

Platform IDs of name records (OpenType name table, platformID), as in NameRecord.Platform.

Variables

View Source
var (
	// ErrInvalidFont reports bytes that are not a font the specification
	// allows: truncated data, a table outside the file, a field outside its
	// range, or an outline that cannot be decoded.
	ErrInvalidFont = errors.New("onefont: invalid font")

	// ErrUnsupportedFormat reports a well-formed font in a form this package
	// does not read: a WOFF or WOFF2 file (unpack it with [UnwrapWebFont]), a Type 1 sfnt wrapper, or a font
	// with no outline table at all.
	ErrUnsupportedFormat = errors.New("onefont: unsupported font format")

	// ErrFaceIndex reports a face index that the file does not contain. A
	// plain font has face 0 only; a collection has one face per listed font.
	ErrFaceIndex = errors.New("onefont: face index out of range")

	// ErrGlyphID reports a glyph ID at or past the font's glyph count.
	ErrGlyphID = errors.New("onefont: glyph id out of range")
)

The four classes of failure a font can cause. Every error returned while reading a font wraps exactly one of them, so callers branch with errors.Is.

View Source
var (
	// ErrLimit reports work that exceeds a fixed limit of the package: a
	// text longer than Shape takes (1 GiB), or a request whose result would
	// outgrow the size limits. Shorter input or fewer glyphs would succeed.
	ErrLimit = errors.New("onefont: limit exceeded")

	// ErrInvalidArgument reports an argument the call cannot use, such as a
	// nil font where a font is needed.
	ErrInvalidArgument = errors.New("onefont: invalid argument")

	// ErrNotFound reports a name that matches nothing, such as a named
	// instance the font does not list.
	ErrNotFound = errors.New("onefont: not found")
)

Errors that are not about the font's bytes. Each is wrapped with detail where it is returned; match them with errors.Is.

Functions

func BidiMirror

func BidiMirror(r rune) (rune, bool)

BidiMirror returns the mirrored counterpart of r (UAX #9 rule L4, Bidi_Mirroring_Glyph): the character to display for r inside a right-to-left run, such as ")" for "(". It reports false when r has none.

Example

Mirrored characters are drawn as their counterpart in right-to-left runs.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	m, ok := onefont.BidiMirror('(')
	fmt.Printf("%c %v\n", m, ok)
	_, ok = onefont.BidiMirror('a')
	fmt.Println(ok)
}
Output:
) true
false

func FontRuns

func FontRuns(text string, fonts ...Font) iter.Seq[FontRun]

FontRuns splits text over fonts with a new chain; see FallbackChain for the rule. Offsets are bytes.

Example

Each cluster takes the first font that has its first code point; the text is cut into runs of one font.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	latin, _ := onefont.Parse(fonttest.Cover("ab"))
	symbols, _ := onefont.Parse(fonttest.Cover("XY"))
	text := "abXYab"
	for r := range onefont.FontRuns(text, latin, symbols) {
		fmt.Printf("%q font %d\n", text[r.Start:r.End], r.Font)
	}
}
Output:
"ab" font 0
"XY" font 1
"ab" font 0

func GraphemeBreaks

func GraphemeBreaks(text string) iter.Seq[int]

GraphemeBreaks yields the extended grapheme cluster boundaries of text as byte offsets, as Segmenter.AppendGraphemeBreaks finds them: after offset 0, ending with len(text). Empty text has none. The breaks are found for the whole text before the first is yielded.

Example

Offsets are bytes of the string, so a boundary never splits a character.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for b := range onefont.GraphemeBreaks("e\u0301a🇩🇪") {
		fmt.Print(b, " ")
	}
	fmt.Println()
}
Output:
3 4 12

func Graphemes

func Graphemes(text string) iter.Seq[string]

Graphemes yields the extended grapheme clusters of text.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for g := range onefont.Graphemes("👨‍👩‍👧x") {
		fmt.Printf("%d runes\n", len([]rune(g)))
	}
}
Output:
5 runes
1 runes

func IsEastAsianWide

func IsEastAsianWide(r rune) bool

IsEastAsianWide reports whether r's East_Asian_Width is Fullwidth (F), Wide (W) or Halfwidth (H) in Unicode 17.0.0: the characters a layout engine sets as a full em or as a narrow cell next to them, as East Asian text does. Ambiguous (A), Neutral (N) and Narrow (Na) characters are not wide.

func IsSyllableScript

func IsSyllableScript(r rune) bool

IsSyllableScript reports whether r belongs to a script that is shaped in reordering syllables, in which vowel signs, medials or subscripts move, stack or change form around a base letter. The scripts are Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam, Sinhala, Khmer, Myanmar, Tibetan, Balinese and Javanese, by each character's Script property in Unicode 17.0.0. Thai and Lao, which only move a leading vowel, and every other script are not, and neither are common and inherited characters: a mark shared between scripts has no script of its own to ask.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	fmt.Println(onefont.IsSyllableScript('क'), onefont.IsSyllableScript('ก'), onefont.IsEastAsianWide('あ'))
}
Output:
true false true

func IsWebFont added in v1.1.0

func IsWebFont(data []byte) bool

IsWebFont reports whether data starts with the signature of a WOFF or WOFF2 file. It looks at four bytes and says nothing about whether the rest is valid; UnwrapWebFont does that.

func LineBreaks

func LineBreaks(text string) iter.Seq[LineBreak]

LineBreaks yields the line break opportunities of text as byte offsets, as Segmenter.AppendLineBreaks finds them.

Example

A line break opportunity says where a line may end; a mandatory one says where it must.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for b := range onefont.LineBreaks("A long-ish line.\nNext") {
		fmt.Printf("%d mandatory=%v\n", b.Pos, b.Mandatory)
	}
}
Output:
2 mandatory=false
7 mandatory=false
11 mandatory=false
17 mandatory=true
21 mandatory=false

func Lines

func Lines(text string) iter.Seq2[string, bool]

Lines yields the pieces of text between line break opportunities, each with the trailing spaces that stay on its line, and whether the line it ends is a forced break.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for line, forced := range onefont.Lines("one two\nthree") {
		fmt.Printf("%q %v\n", line, forced)
	}
}
Output:
"one " false
"two\n" true
"three" false

func NumFaces

func NumFaces(data []byte) (int, error)

NumFaces returns how many faces data holds: the font count of a TrueType Collection, or 1 for a single font. It reads only the file header.

func SentenceBreaks

func SentenceBreaks(text string) iter.Seq[int]

SentenceBreaks yields the sentence boundaries of text as byte offsets, as Segmenter.AppendSentenceBreaks finds them.

func Sentences

func Sentences(text string) iter.Seq[string]

Sentences yields the sentences of text, each with its closing punctuation and trailing white space.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for s := range onefont.Sentences("Hello there. How are you? Fine!") {
		fmt.Printf("%q\n", s)
	}
}
Output:
"Hello there. "
"How are you? "
"Fine!"

func ShapeText

func ShapeText(text string, chain *FallbackChain, opts ...ShapeOption) iter.Seq2[ShapedRun, error]

ShapeText is Shaper.ShapeText on a pooled Shaper: it shapes text over chain with bidi and per-cluster fallback and yields the runs in visual order. To shape many texts without allocating, keep a Shaper and call its method.

Example

The package-level ShapeText does the same on a pooled Shaper.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	latin, _ := onefont.Parse(fonttest.Cover("ab"))
	chain := onefont.NewFallbackChain(latin)
	for sr, err := range onefont.ShapeText("ab", chain) {
		fmt.Println(sr.Start, sr.End, sr.Level, sr.Run.Glyphs, err)
	}
}
Output:
0 2 0 [1 2] <nil>

func UnwrapWebFont added in v1.1.0

func UnwrapWebFont(data []byte, opts ...WebFontOption) ([]byte, error)

UnwrapWebFont unpacks a WOFF 1.0 or WOFF 2.0 file (W3C Recommendations) to the sfnt font it holds, ready for Parse: a plain font, or a TrueType collection for a WOFF2 file of a collection. The result is a new slice; the input is not kept. WOFF tables are inflated and checked against their stated lengths, and a WOFF2 file's Brotli stream is decoded and its glyf, loca and hmtx transforms reversed, so the glyph data of the result can differ in encoding (never in meaning) from the font the file was made from; table checksums and the head table's checkSumAdjustment are recomputed. The metadata and private data blocks are skipped.

Data that is not a web font at all (no signature) gives an error wrapping ErrUnsupportedFormat; use IsWebFont to tell plain fonts from web fonts first. A damaged file gives an error wrapping ErrInvalidFont, and one that would unpack past the limit (WithMaxFontSize) an error wrapping ErrLimit. It never panics and never allocates much more than the limit.

Example

A web font is unpacked to a plain font before it is parsed. The limit stops a small file from asking for a very large amount of memory.

package main

import (
	"fmt"
	"os"
	"path/filepath"

	"recursiveai.org/go/onefont"
)

func main() {
	data, err := os.ReadFile(filepath.Join("testdata", "webfont", "NotoSans-Subset-Regular.woff2"))
	if err != nil {
		fmt.Println(err)
		return
	}
	if onefont.IsWebFont(data) {
		data, err = onefont.UnwrapWebFont(data, onefont.WithMaxFontSize(8<<20))
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	face, err := onefont.Parse(data)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(face.Family(), face.NumGlyphs(), face.GlyphIndex('A') != 0)
}
Output:
Noto Sans 520 true

func WordBreaks

func WordBreaks(text string) iter.Seq[int]

WordBreaks yields the word boundaries of text as byte offsets, as Segmenter.AppendWordBreaks finds them.

func Words

func Words(text string) iter.Seq[string]

Words yields the segments between word boundaries of text, which include the spaces and punctuation between words.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for w := range onefont.Words("Can't stop, 3.5 times!") {
		fmt.Printf("%q ", w)
	}
	fmt.Println()
}
Output:
"Can't" " " "stop" "," " " "3.5" " " "times" "!"

Types

type Affine

type Affine struct {
	A, B, C, D, E, F float32
}

Affine is a two-dimensional affine map. It takes the point (x, y) to (A*x + C*y + E, B*x + D*y + F), the column-vector form: A and D scale, B and C shear or rotate, E and F translate. The zero Affine collapses every point to the origin; IdentityAffine leaves points where they are.

func IdentityAffine

func IdentityAffine() Affine

IdentityAffine returns the Affine that moves nothing.

func Scale

func Scale(sx, sy float32) Affine

Scale returns the Affine that multiplies x by sx and y by sy. Outlines are y up; the y-flip a y-down canvas needs, at scale s, is Scale(s, -s).

Example

Outlines are y up. A y-down canvas wants the outline scaled and flipped, which is Scale(s, -s); Mul composes maps, applying the right one first.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	var p onefont.Path
	p.MoveTo(0, 0)
	p.LineTo(100, 700)
	p.Close()
	// Scale to 10 pixels per 1000 units, flip, then move the baseline to y=8.
	p.Transform(onefont.Translate(0, 8).Mul(onefont.Scale(0.01, -0.01)))
	for s := range p.All() {
		fmt.Println(s.Kind, s.Pts[0])
	}
}
Output:
move {0 8}
line {1 1}
close {0 0}

func Translate

func Translate(x, y float32) Affine

Translate returns the Affine that moves every point by (x, y).

func (Affine) Apply

func (m Affine) Apply(x, y float32) (float32, float32)

Apply returns the image of the point (x, y).

func (Affine) Mul

func (m Affine) Mul(n Affine) Affine

Mul returns the composition of m and n: the Affine that applies n first and then m, so m.Mul(n).Apply(x, y) equals m.Apply(n.Apply(x, y)). Scaling a path by s and then moving it by (dx, dy) is Translate(dx, dy).Mul(Scale(s, s)).

type Axis

type Axis struct {
	Tag     Tag
	Min     float32
	Default float32 // within [Min, Max]
	Max     float32
	Hidden  bool   // fvar axis flag HIDDEN_AXIS: not for direct display to users
	NameID  NameID // name table ID of the axis label
	Name    string // the label, chosen as Face.Name chooses; "" when the font has none
}

Axis is one variation axis of a variable font (OpenType fvar, "Variation axis record"). Min, Default and Max are user-space values: the scale the font designer chose, such as 100 to 900 for weight.

type Bidi

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

Bidi resolves the Unicode Bidirectional Algorithm (UAX #9, Unicode 17.0.0) for a text: embedding levels, and the visual order of a line. It implements rules P2 to I2 for the paragraphs of the text, and L1 and L2 for the lines you ask about; rules L3 and L4 (combining marks, mirroring) are left to the caller, see BidiMirror.

A Bidi keeps its buffers between calls, so one Bidi reused for many texts allocates only while its buffers grow. The zero value is ready to use. A Bidi is not safe for concurrent use; the slices it returns are valid until its next method call that resolves or returns levels, paragraphs or order.

Positions that go in and come out of a Bidi (the start and end of a line, run and paragraph bounds, the entries of VisualOrder) are byte offsets in the resolved string. A line bound that falls inside a character moves to the end of that character, and bounds outside the text are clamped. Levels are the exception: there is one per rune, in text order, because every byte of a character has the character's level; Bidi.NumRunes counts them. Invalid UTF-8 decodes to one U+FFFD per invalid byte, as Go's range loop does. At most 2³¹−1 runes of a text are processed.

Example

Resolve a paragraph that mixes English and Hebrew and read its levels and the order its characters are displayed in.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	const text = "abc אבג def"
	var b onefont.Bidi
	b.Resolve(text, onefont.DirectionAuto)
	fmt.Println("paragraph level:", b.ParagraphLevel())
	fmt.Println("levels (one per rune):", b.Levels())
	fmt.Println("visual order (byte offsets):", b.VisualOrder(nil, 0, len(text)))
}
Output:
paragraph level: 0
levels (one per rune): [0 0 0 0 1 1 1 0 0 0 0]
visual order (byte offsets): [0 1 2 3 8 6 4 10 11 12 13]

func ResolveBidi

func ResolveBidi(text string, dir Direction) *Bidi

ResolveBidi resolves text with a new Bidi. For repeated use, reuse one Bidi and call Bidi.Resolve.

func (*Bidi) Levels

func (b *Bidi) Levels() []BidiLevel

Levels returns the level of every rune, in text order, with the text taken as a single line: rule L1 applies, so trailing white space and isolate controls, and anything before a separator, sit at their paragraph's level. Characters that rule X9 removes have the level BidiRemoved. The slice is valid until the next call to Levels or LineLevels.

func (*Bidi) LineLevels

func (b *Bidi) LineLevels(dst []BidiLevel, start, end int) []BidiLevel

LineLevels returns the levels of the runes of the line text[start:end] after rule L1, one per rune, appended to dst[:0]. A line should lie within one paragraph.

func (*Bidi) NumRunes

func (b *Bidi) NumRunes() int

NumRunes returns the number of runes of the resolved text, which is the length of Bidi.Levels.

func (*Bidi) ParagraphLevel

func (b *Bidi) ParagraphLevel() BidiLevel

ParagraphLevel returns the level of the first paragraph, or 0 for an empty text.

func (*Bidi) Paragraphs

func (b *Bidi) Paragraphs() []BidiParagraph

Paragraphs returns the paragraphs of the text in order, with byte ranges. The result is valid until the next call to Resolve or Paragraphs.

func (*Bidi) Resolve

func (b *Bidi) Resolve(text string, dir Direction)

Resolve resolves text, replacing any earlier result. dir is the base direction of every paragraph: DirectionLTR makes each one level 0, DirectionRTL level 1, and DirectionAuto takes each paragraph's direction from its first strong character (UAX #9 rules P2 and P3), left to right when it has none. An empty text has no paragraphs.

Example (Direction)

A right-to-left base direction puts the whole line at level 1 or above.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	const text = "abc 12 אב"
	var b onefont.Bidi
	b.Resolve(text, onefont.DirectionRTL)
	fmt.Println(b.Levels())
	fmt.Println(b.VisualOrder(nil, 0, len(text)))
}
Output:
[2 2 2 2 2 2 1 1 1]
[9 7 6 0 1 2 3 4 5]

func (*Bidi) Runs

func (b *Bidi) Runs(start, end int) iter.Seq[BidiRun]

Runs yields the runs of the line text[start:end] in visual order, left to right. Each run lies at one level, and its characters are contiguous in the text (apart from removed characters); a right-to-left run is displayed backwards. The bounds are as for Bidi.LineLevels. The Bidi is used while the iteration runs.

Example

Runs groups the visual order into pieces of one direction, which is what a renderer shapes and draws.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	text := "abc אבג def"
	b := onefont.ResolveBidi(text, onefont.DirectionAuto)
	for run := range b.Runs(0, len(text)) {
		fmt.Printf("%q rtl=%v\n", text[run.Start:run.End], run.RTL())
	}
}
Output:
"abc " rtl=false
"אבג" rtl=true
" def" rtl=false

func (*Bidi) VisualOrder

func (b *Bidi) VisualOrder(dst []int, start, end int) []int

VisualOrder returns the byte offsets of the runes of the line text[start:end] in visual order, left to right, after rules L1 and L2, appended to dst[:0]. Characters that rule X9 removes are left out.

type BidiLevel

type BidiLevel uint8

BidiLevel is an embedding level: even levels run left to right, odd levels right to left. Resolved levels run from 0 to 126; BidiRemoved marks a character that has none.

const BidiRemoved BidiLevel = 0xFF

BidiRemoved is the level of a character that UAX #9 rule X9 removes: the embedding and override controls (LRE, RLE, LRO, RLO, PDF) and the boundary neutrals (BN, which include ZWJ and ZWNJ). Such a character has no level and takes no part in reordering. It is not the level of a neighbour.

func (BidiLevel) RTL

func (l BidiLevel) RTL() bool

RTL reports whether the level is odd: text at it reads right to left. BidiRemoved is not a level and reports false.

type BidiParagraph

type BidiParagraph struct {
	Start, End int
	Level      BidiLevel
}

BidiParagraph is the byte range [Start, End) of one paragraph of the resolved text and its resolved paragraph level. A paragraph ends after a paragraph separator, which belongs to it.

type BidiRun

type BidiRun struct {
	Start, End int
	Level      BidiLevel
}

BidiRun is a run of characters of one level that are contiguous in the text: the byte range [Start, End) at Level. The range may contain characters that rule X9 removes.

func (BidiRun) RTL

func (r BidiRun) RTL() bool

RTL reports whether the run reads right to left.

type ComponentFlags added in v1.1.0

type ComponentFlags uint16

ComponentFlags are the flags of one component of a composite glyph (OpenType glyf, "Composite glyph description").

const (
	// ComponentArgsAreXY says Arg1 and Arg2 are an x and y offset; without
	// it they are the point numbers to match (Arg1 in the glyph built so far,
	// Arg2 in this component).
	ComponentArgsAreXY ComponentFlags = 0x0002
	// ComponentRoundXYToGrid asks that the offset be rounded to the pixel
	// grid when the glyph is hinted.
	ComponentRoundXYToGrid ComponentFlags = 0x0004
	// ComponentUseMyMetrics asks that the composite take this component's
	// advance and side bearing.
	ComponentUseMyMetrics ComponentFlags = 0x0200
	// ComponentOverlapCompound says the components overlap.
	ComponentOverlapCompound ComponentFlags = 0x0400
	// ComponentScaledOffset says the offset is scaled by the component's
	// transform.
	ComponentScaledOffset ComponentFlags = 0x0800
	// ComponentUnscaledOffset says the offset is not scaled (the default
	// when neither this nor ComponentScaledOffset is set).
	ComponentUnscaledOffset ComponentFlags = 0x1000
)

Component flags a hinting program or a glyph assembler reads. The flags that say how the record is laid out (argument size, transform kind, more components) are left out: GlyphComponent already holds what they decode to.

type Direction

type Direction uint8

Direction is the direction a run of text is shaped in.

const (
	// DirectionAuto takes the direction of the first strong character of the
	// text (UAX #9 rules P2 and P3), left to right when there is none.
	DirectionAuto Direction = iota
	// DirectionLTR is left to right (a bidi level of 0).
	DirectionLTR
	// DirectionRTL is right to left (a bidi level of 1).
	DirectionRTL
)

Directions for WithDirection, TextRun and Bidi.Resolve.

func (Direction) String

func (d Direction) String() string

String names the direction: "auto", "ltr" or "rtl".

type Face

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

Face is one font of a file: a view over the caller's bytes. Table data is never copied; the caller must not modify the bytes while the Face is in use. A Face is immutable after Parse, so any number of goroutines may call its methods at once.

func Parse

func Parse(data []byte, opts ...Option) (*Face, error)

Parse reads one face from font data: a TrueType or OpenType font (TrueType or CFF outlines), or a TrueType Collection when WithFace picks a member.

Parse reads the table directory and the small header tables (head, maxp, hhea, cmap's subtable index) and checks that every table lies inside data. Everything else is read when asked for. The Face keeps data; it does not copy it.

Errors wrap ErrInvalidFont, ErrUnsupportedFormat (a WOFF or WOFF2 file: see UnwrapWebFont) or ErrFaceIndex. Parse never panics on any input.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, err := onefont.Parse(fonttest.TrueType())
	if err != nil {
		panic(err)
	}
	m := face.Metrics()
	fmt.Println(face.FullName(), face.UnitsPerEm(), face.NumGlyphs(), face.OutlineFormat())
	fmt.Println(m.Ascender, m.Descender, m.LineGap)
}
Output:
Test Family Regular 1000 7 truetype
800 -200 90
Example (Errors)
package main

import (
	"errors"
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	_, err := onefont.Parse([]byte("not a font, but long enough to have a header"))
	fmt.Println(err)
	fmt.Println(errors.Is(err, onefont.ErrInvalidFont))
}
Output:
onefont: invalid font: sfnt: unknown sfnt version
true

func (*Face) Advance

func (f *Face) Advance(g GlyphID) int32

Advance returns the glyph's horizontal advance in font units.

func (*Face) Axes

func (f *Face) Axes() []Axis

Axes returns the face's variation axes in fvar order, or nil for a font without fvar or with a damaged one (Instance reports the damage).

func (*Face) ContourPoint

func (f *Face) ContourPoint(g GlyphID, n int) (x, y int32, ok bool)

ContourPoint returns the position of point n of glyph g's outline, in font units, counting the points of a composite glyph after its components are placed. GPOS anchors of format 2 name glyph points this way. ok is false for a face without TrueType outlines, an invalid glyph, or a point the glyph does not have.

func (*Face) Family

func (f *Face) Family() string

Family returns the typographic family (name ID 16), else the family (ID 1).

func (*Face) FullName

func (f *Face) FullName() string

FullName returns name ID 4.

func (*Face) GlyphBounds

func (f *Face) GlyphBounds(g GlyphID) (tight, control Rect, err error)

GlyphBounds returns the tight and control boxes of glyph g's outline (see Path.Bounds) in font units. A glyph without an outline has two zero boxes. Errors are those of Face.Outline.

func (*Face) GlyphDescription added in v1.1.0

func (f *Face) GlyphDescription(g GlyphID) (*GlyphDescription, error)

GlyphDescription returns glyph g's points, contours, phantom points and instructions. It fails with an error wrapping ErrUnsupportedFormat for a face whose outlines are not TrueType, ErrGlyphID for a glyph the font does not have, and ErrInvalidFont for damaged glyph data. A glyph with no outline (a space) has no points and no instructions, and its phantom points still follow its advance.

Example

A hinting engine starts from the glyph's points, its phantom points and its program, and from the font's programs and control values.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, err := onefont.Parse(fonttest.TrueType())
	if err != nil {
		fmt.Println(err)
		return
	}
	d, err := face.GlyphDescription(4) // a composite of two components
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("points:", len(d.Points), "contours:", d.Ends)
	for _, c := range d.Components {
		fmt.Println("component glyph", c.Glyph, "points", c.FirstPoint, "to", c.FirstPoint+c.NumPoints-1)
	}
	fmt.Println("instructions:", len(d.Instructions), "bytes; control values:", len(face.Hinting().ControlValues))
}
Output:
points: 7 contours: [3 6]
component glyph 1 points 0 to 3
component glyph 2 points 4 to 6
instructions: 0 bytes; control values: 0

func (*Face) GlyphIndex

func (f *Face) GlyphIndex(r rune) GlyphID

GlyphIndex maps a code point to a glyph using the face's best Unicode subtable (see Parse for the preference). It returns 0, the .notdef glyph, when the font maps nothing for r, including negative and out-of-range values and supplementary-plane code points when only a BMP subtable exists.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	fmt.Println(face.GlyphIndex('A'), face.GlyphIndex('B'), face.GlyphIndex('z'))
}
Output:
1 2 0

func (*Face) GlyphIndexVariation

func (f *Face) GlyphIndexVariation(r, selector rune) (g GlyphID, ok bool)

GlyphIndexVariation maps a base character followed by a variation selector (U+FE00 to U+FE0F, U+E0100 to U+E01EF) through the format 14 subtable. ok is false when the font has no such sequence. For a default sequence the glyph is the one GlyphIndex gives the base; a non-default sequence gives its own glyph.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	_, ok := face.GlyphIndexVariation('A', 0xFE00)
	fmt.Println(ok)
}
Output:
false

func (*Face) GlyphPath

func (f *Face) GlyphPath(g GlyphID) (Path, error)

GlyphPath returns glyph g's outline as a Path.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	path, _ := face.GlyphPath(face.GlyphIndex('B'))
	for s := range path.All() {
		fmt.Println(s.Kind, s.Pts)
	}
}
Output:
move [{0 0} {0 0} {0 0}]
quad [{250 500} {500 0} {0 0}]
close [{0 0} {0 0} {0 0}]

func (*Face) HMetrics

func (f *Face) HMetrics(g GlyphID) (advance, lsb int32)

HMetrics returns a glyph's advance width and left side bearing from hmtx. Glyphs at or after hhea.numberOfHMetrics share the last advance and read their bearing from the trailing array (OpenType hmtx). A glyph the table does not reach, or a font without hmtx, gives 0 for what is missing.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	adv, lsb := face.HMetrics(1)
	fmt.Println(adv, lsb)
}
Output:
600 10

func (*Face) HasTable

func (f *Face) HasTable(t Tag) bool

HasTable reports whether the table directory lists t.

func (*Face) Hinting added in v1.1.0

func (f *Face) Hinting() HintingTables

Hinting returns the tables TrueType instructions run on. Tables a font lacks are empty, so a font without hinting gives the zero value, and damaged tables are read as far as they go.

func (*Face) Instance

func (f *Face) Instance(vars ...Variation) (*Instance, error)

Instance returns the face at the design vars name (see Normalize for how values are read). A face without fvar gives an instance equal to the face. Errors wrap ErrInvalidFont when fvar, avar, gvar, HVAR or MVAR is damaged.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.VariableTrueType(true))
	for _, ax := range face.Axes() {
		fmt.Println(ax.Tag, ax.Name, ax.Min, ax.Default, ax.Max)
	}
	bold, err := face.Instance(onefont.Variation{Tag: onefont.MakeTag("wght"), Value: 900})
	if err != nil {
		panic(err)
	}
	fmt.Println(face.Advance(1), bold.Advance(1))
	path, _ := bold.GlyphPath(1)
	fmt.Println(path.Segments[0].Pts[0], path.Segments[2].Pts[0])
	fmt.Println(bold.Coords())
}
Output:
wght Weight 100 400 900
600 700
{-10 0} {560 800}
[16384]

func (*Face) InstanceAt

func (f *Face) InstanceAt(coords []int16) (*Instance, error)

InstanceAt returns the face at normalised coordinates, one F2DOT14 value per axis in fvar order; missing trailing values are 0 and extra ones are ignored. Values outside [-16384, 16384] are clamped.

func (*Face) InstanceNamed

func (f *Face) InstanceNamed(name string) (*Instance, error)

InstanceNamed returns the face at the named instance whose name equals name ignoring ASCII case; of several with one name the first in fvar order wins. It returns an error wrapping ErrNotFound when the font has no instance of that name (including a face without fvar). Other errors are those of Face.Instance.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, err := onefont.Parse(fonttest.VariableTrueType(true))
	if err != nil {
		panic(err)
	}
	in, err := face.InstanceNamed("bold") // case is ignored
	if err != nil {
		panic(err)
	}
	for _, v := range in.Variations() {
		fmt.Println(v.Tag, v.Value)
	}
}
Output:
wght 700

func (*Face) IsVariable

func (f *Face) IsVariable() bool

IsVariable reports whether the face has an fvar table.

func (*Face) Kerning

func (f *Face) Kerning(left, right GlyphID) int32

Kerning returns the pair adjustment the font defines for the glyph pair (left, right): the x-advance adjustment of the first glyph in the pair positioning of the font's GPOS "kern" feature (Latin script, default language), or, for a font whose GPOS has no kern feature, the pair's value in its legacy kern table (see Face.LegacyKern). It is in font units, at the instance's design for an *Instance. Negative values tighten the pair. A pair the font does not adjust gives 0, as does a glyph ID the font does not have.

This is the value the font states, not what shaping makes of it: shaping a font with only a legacy kern table splits the value between the two glyphs, so the first glyph's advance changes by about half of it. Substitution is not applied: the glyphs are taken as they are, so ask about the glyphs the characters map to, not about a ligature's parts.

Kerning uses a pooled Shaper; a caller measuring many pairs of one font can call Shaper.Kerning on a Shaper of its own, which keeps the lookup plan between calls.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, err := onefont.Parse(fonttest.TrueType())
	if err != nil {
		panic(err)
	}
	// The test font kerns glyphs 1 and 2 by -30 in its legacy kern table, and
	// that is the pair's value.
	fmt.Println(face.Kerning(1, 2), face.Kerning(2, 1))
}
Output:
-30 0

func (*Face) LegacyKern

func (f *Face) LegacyKern(left, right GlyphID) int32

LegacyKern returns the horizontal kerning adjustment in font units between a left and right glyph from the legacy kern table only: the sum over format 0 subtables, where an override subtable replaces what came before. It is 0 for fonts without a kern table. GPOS kerning is not consulted; Face.Kerning gives the adjustment the shaper applies, from GPOS or this table.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	fmt.Println(face.LegacyKern(1, 2), face.LegacyKern(2, 1))
}
Output:
-30 0

func (*Face) Metrics

func (f *Face) Metrics() Metrics

Metrics reads the metric fields from head, hhea, OS/2 and post. It is cheap and does not cache; call it once and keep the value.

func (*Face) Name

func (f *Face) Name(id NameID) string

Name returns the string for id, or "" when the font has none. It prefers the Windows record in US English (language 0x409), then the Macintosh Roman English record, then any Windows record, any Unicode-platform record and any Macintosh record, taking the first in table order within a class.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	fmt.Println(face.Name(onefont.NameFamily), "|", face.Family(), "|", face.PostScriptName())
}
Output:
Test Family | Test Typographic | TestFamily-Regular

func (*Face) NameRecords

func (f *Face) NameRecords() iter.Seq[NameRecord]

NameRecords yields every readable name record in table order. Records whose platform and encoding have no decoder here (anything but Unicode, Windows Unicode and Macintosh Roman) are skipped. Strings that are invalid UTF-16 decode with U+FFFD in place of the bad unit.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	for r := range face.NameRecords() {
		if r.Platform == onefont.PlatformMacintosh {
			fmt.Println(r.ID, r.Value)
		}
	}
}
Output:
1 Mac Family
4 Café

func (*Face) NamedInstances

func (f *Face) NamedInstances() []NamedInstance

NamedInstances returns the designs the font names, in fvar order.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.VariableTrueType(false))
	for _, ni := range face.NamedInstances() {
		fmt.Println(ni.Name, ni.Coords)
	}
}
Output:
Bold [700]

func (*Face) Normalize

func (f *Face) Normalize(vars ...Variation) ([]int16, error)

Normalize converts user-space axis values to normalised coordinates, one F2DOT14 value per axis in fvar order. An axis that vars does not name keeps its default (0); a tag the font has no axis for is ignored; of repeated tags the last wins. The steps are the ones fvar and avar give: clamp to [Min, Max], scale to [-1, 1] around the default, map through the avar segment map, then round to the nearest 1/16384. A NaN value leaves its axis at the default.

A face without fvar returns nil.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.VariableTrueType(false))
	// 650 is halfway from the default to the maximum; the font's avar map
	// moves 0.5 to 0.75. Out-of-range values clamp.
	for _, w := range []float32{400, 650, 1500} {
		c, _ := face.Normalize(onefont.Variation{Tag: onefont.MakeTag("wght"), Value: w})
		fmt.Println(c)
	}
}
Output:
[0]
[12288]
[16384]

func (*Face) NumGlyphs

func (f *Face) NumGlyphs() int

NumGlyphs returns maxp.numGlyphs.

func (*Face) Outline

func (f *Face) Outline(g GlyphID, sink PathSink) error

Outline draws glyph g into sink in font units. A glyph without an outline (a space) draws nothing and returns nil. TrueType composite glyphs are resolved with their transforms applied. On error the sink may already hold part of the glyph; draw into a Path and discard it.

Errors wrap ErrGlyphID (g is not below NumGlyphs), ErrInvalidFont (damaged glyph data, or a limit exceeded: composite depth 32, 4096 components, a charstring of more than 256 thousand operators or deeper than 16 subroutines) or ErrUnsupportedFormat (a face with no outlines).

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

type printer struct{}

func (printer) MoveTo(x, y float32)         { fmt.Println("M", x, y) }
func (printer) LineTo(x, y float32)         { fmt.Println("L", x, y) }
func (printer) QuadTo(cx, cy, x, y float32) { fmt.Println("Q", cx, cy, x, y) }
func (printer) CubicTo(a, b, c, d, x, y float32) {
	fmt.Println("C", a, b, c, d, x, y)
}
func (printer) Close() { fmt.Println("Z") }

func main() {
	face, _ := onefont.Parse(fonttest.CFF())
	if err := face.Outline(face.GlyphIndex('B'), printer{}); err != nil {
		panic(err)
	}
}
Output:
M 0 0
C 100 200 200 200 300 0
L 0 0
Z

func (*Face) OutlineFormat

func (f *Face) OutlineFormat() OutlineFormat

OutlineFormat reports whether the face has TrueType, CFF or CFF2 outlines.

func (*Face) PostScriptName

func (f *Face) PostScriptName() string

PostScriptName returns name ID 6.

func (*Face) Subfamily

func (f *Face) Subfamily() string

Subfamily returns the typographic subfamily (name ID 17), else ID 2.

func (*Face) Table

func (f *Face) Table(t Tag) []byte

Table returns the raw bytes of a table, or nil when the font has none. The slice aliases the font data; do not modify it. A table that is present but empty returns a non-nil empty slice.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	fmt.Println(face.HasTable(onefont.TagGSUB), len(face.Table(onefont.TagHead)))
	fmt.Println(face.Tags()[0], onefont.MakeTag("kern") == onefont.TagKern)
}
Output:
false 54
OS/2 true

func (*Face) Tags

func (f *Face) Tags() []Tag

Tags returns the face's table tags in ascending order.

func (*Face) UnitsPerEm

func (f *Face) UnitsPerEm() int32

UnitsPerEm returns head.unitsPerEm, between 16 and 16384.

type FallbackChain

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

FallbackChain chooses a font per grapheme cluster from an ordered list of fonts, so that text mixing scripts and symbols can be split into runs that each use one font.

The rule, for each extended grapheme cluster (UAX #29, Unicode 17.0.0):

  • a font covers the cluster when its cmap maps the cluster's first code point to a glyph other than 0; the rest of the cluster is not asked;
  • the first covering font wins; when none covers it, font 0 is used and draws its missing-glyph box;
  • an invisible cluster (one whose first code point is a control, soft hyphen, zero width or direction format character, line or paragraph separator, joiner, isolate or byte order mark) takes the font of the cluster before it, whatever the fonts cover; at the start of the text it is treated like any other cluster;
  • neighbouring clusters with the same font merge into one run.

A chain with no fonts, or a nil entry, is allowed: a nil font covers nothing, and a chain with no fonts yields no runs. Invalid UTF-8 decodes to one U+FFFD per invalid byte.

A FallbackChain keeps scratch buffers between calls and is not safe for concurrent use; the fonts themselves must be safe for the concurrency you use them with (a *Face and an *Instance are immutable). The runs say which font to use for which text; FallbackChain.ShapeRuns shapes them, and Shaper.ShapeText adds bidi.

func NewFallbackChain

func NewFallbackChain(fonts ...Font) *FallbackChain

NewFallbackChain returns a chain over fonts, in order of preference. The slice is copied.

Example

A chain mixes faces and instances of variable faces freely: both are Fonts.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	base, _ := onefont.Parse(fonttest.VariableTrueType(true))
	bold, _ := base.InstanceNamed("Bold")
	other, _ := onefont.Parse(fonttest.Cover("\u05d0\u05d1"))
	chain := onefont.NewFallbackChain(bold, other)
	fmt.Println(chain.Len(), chain.Font(0) == onefont.Font(bold))
}
Output:
2 true

func (*FallbackChain) AppendRuns

func (c *FallbackChain) AppendRuns(dst []FontRun, text string) []FontRun

AppendRuns appends to dst the runs of text, with byte offsets, and returns the extended slice. The runs tile the text in order and none is empty.

func (*FallbackChain) Font

func (c *FallbackChain) Font(i int) Font

Font returns font i of the chain, or nil when i is out of range.

func (*FallbackChain) Len

func (c *FallbackChain) Len() int

Len returns the number of fonts in the chain.

func (*FallbackChain) Runs

func (c *FallbackChain) Runs(text string) iter.Seq[FontRun]

Runs yields the runs of text with byte offsets. It uses a scratch chain state of its own, so it is safe to call from several goroutines on the same chain.

func (*FallbackChain) ShapeRuns

func (c *FallbackChain) ShapeRuns(s *Shaper, text string, opts ...ShapeOption) iter.Seq2[ShapedRun, error]

ShapeRuns shapes text with the chain: it splits the text into runs by font, as FallbackChain.Runs does, and shapes each run with its own font using s and opts, in text order. Every run is yielded with its glyphs. Clusters are byte offsets into text, not into the run, so the runs line up with the text; so are the origins when WithOrigins is given.

ShapeRuns resolves no bidi: the direction of a run comes from WithDirection or, by default, from the run's own first strong character, and the runs stay in text order. Shaper.ShapeText is the call for mixed-direction text. Script is worked out for each run from its own text unless WithScript fixes it; language and features apply to every run.

A run that cannot be shaped, because its chain entry is nil or the text is too long, is yielded with a nil Run and an error that wraps ErrInvalidArgument or ErrLimit, and the iteration ends. A non-empty text shaped over a chain with no fonts yields that error once.

The Run is reused between iterations, so copy what you keep. The chain's scratch buffers and s are used while the iteration runs, so neither may be used elsewhere at the same time.

Example

FallbackChain.ShapeRuns shapes each run with the font the chain chose for it, in text order and without bidi. Clusters are offsets into the whole text.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	latin, _ := onefont.Parse(fonttest.Cover("ab"))
	symbols, _ := onefont.Parse(fonttest.Cover("XY"))
	chain := onefont.NewFallbackChain(latin, symbols)
	for run, err := range chain.ShapeRuns(onefont.NewShaper(), "abXY") {
		if err != nil {
			panic(err)
		}
		fmt.Println(run.Start, run.End, run.Font, run.Run.Glyphs, run.Run.Clusters)
	}
}
Output:
0 2 0 [1 2] [0 1]
2 4 1 [1 2] [2 3]

func (*FallbackChain) WithEmojiPresentation added in v1.1.0

func (c *FallbackChain) WithEmojiPresentation() *FallbackChain

WithEmojiPresentation returns a copy of the chain that draws emoji the way a browser does. A cluster is an emoji sequence when it holds a variation selector 16 (U+FE0F), a combining enclosing keycap (U+20E3), a zero width joiner after a pictograph, an emoji modifier (U+1F3FB to U+1F3FF) or a pair of regional indicators (a flag). Such a cluster takes the first font that covers its first code point and has colour glyphs (a CBDT, COLR, sbix or SVG table), even when an earlier font covers the first code point too, as the digit of a keycap or the heart of an emoji-style heart does; when no colour font covers it the usual rule applies. Clusters that are not emoji sequences, and those with the text variation selector (U+FE0E), follow the usual rule. The default chain does not do this: its rule is the plain first covering font.

type Feature

type Feature struct {
	Tag   Tag
	Value uint32
}

Feature is an OpenType feature setting: the four-character tag and a value. Value 0 turns a feature off, 1 on; a larger value picks an alternate for features that have them (salt=2).

func ParseFeature

func ParseFeature(s string) (Feature, error)

ParseFeature reads a feature setting in the form hb-shape and CSS-like tools use: "liga" or "+liga" (on), "-liga" (off), "kern=0", "salt=2", with "on" and "off" accepted as values. Tags of fewer than four characters are padded with spaces. Ranges such as "liga[3:5]" are not supported and give an error.

Example

Feature settings use the notation of hb-shape: "liga" turns a feature on, "-kern" turns it off, "salt=2" picks the second alternate.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for _, s := range []string{"liga", "-kern", "salt=2"} {
		f, err := onefont.ParseFeature(s)
		fmt.Println(f.Tag, f.Value, err)
	}
}
Output:
liga 1 <nil>
kern 0 <nil>
salt 2 <nil>

func (Feature) String

func (f Feature) String() string

String formats the setting in the form ParseFeature reads: the tag alone ("liga") for value 1, "-liga" for 0 and "salt=2" for any other value. Spaces that pad the tag are left out.

type FeatureRange added in v1.1.0

type FeatureRange struct {
	Feature
	Start, End int
}

FeatureRange is a feature setting that applies only to the part of a text from byte offset Start up to End (exclusive), as CSS font-feature-settings do over part of a run. A glyph is in the range when its cluster, the byte offset of the first character it stands for, is: a ligature or syllable whose first character is in the range is in it whole, and one that starts before Start is not.

func ParseFeatureRange added in v1.1.0

func ParseFeatureRange(s string) (FeatureRange, error)

ParseFeatureRange reads a feature setting with an optional range in the form hb-shape uses: "liga[3:5]", "-kern[2:]", "smcp[:4]" or "salt[3]" (the one character at offset 3), where the numbers are byte offsets and a missing start or end is the start or end of the text. Without brackets the range is the whole text, from 0 to the largest int. The setting before the bracket is read as by ParseFeature.

type Font

type Font interface {
	// GlyphIndex returns the glyph for r, or 0 when the font has none.
	GlyphIndex(r rune) GlyphID
	// GlyphIndexVariation returns the glyph for r followed by the variation
	// selector, and false when the font has no entry for the pair.
	GlyphIndexVariation(r, selector rune) (g GlyphID, ok bool)
	// NumGlyphs returns the glyph count.
	NumGlyphs() int
	// UnitsPerEm returns the size of the em square in font units.
	UnitsPerEm() int32
	// Advance returns the horizontal advance of glyph g in font units.
	Advance(g GlyphID) int32
	// HMetrics returns the advance and left side bearing of glyph g.
	HMetrics(g GlyphID) (advance, lsb int32)
	// Metrics returns the font-wide metrics.
	Metrics() Metrics
	// Outline sends glyph g's outline to sink.
	Outline(g GlyphID, sink PathSink) error
	// GlyphPath returns glyph g's outline as a Path.
	GlyphPath(g GlyphID) (Path, error)
	// GlyphBounds returns the tight and control boxes of glyph g's outline.
	GlyphBounds(g GlyphID) (tight, control Rect, err error)
	// Kerning returns the pair adjustment of (left, right); see [Shaper.Kerning].
	Kerning(left, right GlyphID) int32
	// contains filtered or unexported methods
}

Font is a font a text can be shaped with, a glyph source for fallback and a source of metrics and outlines: a *Face at its default design, or an *Instance of a variable face at one location. Code that only needs glyphs and metrics takes a Font and accepts either.

The interface is sealed: it cannot be implemented outside this package, so the shaping engine can rely on its inputs. A type that embeds a Font to wrap it shapes as the wrapped font does. An *Instance answers GlyphIndex, GlyphIndexVariation, NumGlyphs and UnitsPerEm from its face; Advance, HMetrics, Metrics, outlines, bounds and kerning follow the instance's location.

type FontError

type FontError struct {
	Err    error  // ErrInvalidFont, ErrUnsupportedFormat, ErrFaceIndex or ErrGlyphID
	Table  string // table or structure being read, such as "glyf"; may be empty
	Detail string // what was wrong
}

FontError describes a failure with the table it happened in. It unwraps to one of the Err values above; use errors.As to read Table and Detail.

func (*FontError) Error

func (e *FontError) Error() string

Error implements error.

func (*FontError) Unwrap

func (e *FontError) Unwrap() error

Unwrap returns Err, the error class, so errors.Is(err, ErrInvalidFont) works.

type FontRun

type FontRun struct {
	Start, End int
	Font       int
}

FontRun is a stretch of text drawn with one font of a chain: the byte range [Start, End) and the index of the chosen font in the chain.

type GaspRange added in v1.1.0

type GaspRange struct {
	MaxPPEM uint16
	// Flags are the gasp behaviour flags: 1 grid-fit, 2 grayscale, 4 symmetric
	// grid-fit, 8 symmetric smoothing.
	Flags uint16
}

GaspRange is one row of the gasp table: it applies to sizes up to MaxPPEM pixels per em (0xFFFF ends the list) and Flags tell how to render them.

type GlyphComponent added in v1.1.0

type GlyphComponent struct {
	Glyph GlyphID
	Flags ComponentFlags
	// Arg1 and Arg2 are the component's offset, or the point numbers to
	// match; see [ComponentArgsAreXY].
	Arg1, Arg2 int32
	// XX, XY, YX and YY are the component's 2x2 transform: a point (x, y) of
	// the component becomes (XX*x + YX*y, XY*x + YY*y). The identity is
	// 1, 0, 0, 1.
	XX, XY, YX, YY float32
	// FirstPoint and NumPoints say which of the description's Points belong to
	// this component, after it has been transformed and placed.
	FirstPoint, NumPoints int
}

GlyphComponent is one component of a composite glyph.

type GlyphDescription added in v1.1.0

type GlyphDescription struct {
	// Points are the outline's points, those of a composite's components
	// placed in order, without the phantom points.
	Points []GlyphPoint
	// Ends holds, for each contour, the index in Points of its last point.
	Ends []int
	// Phantom are the four phantom points hinting moves with the glyph, in
	// the order the TrueType instruction set numbers them after the last
	// point: the origin (left side bearing point), the advance point, the top
	// and the bottom. The origin is at (xMin - left side bearing, 0) and the
	// advance point an advance width to its right. The top and bottom
	// are on the y axis at the font's hhea ascender and descender: the font's
	// vertical metrics, which this package does not read, are not used.
	Phantom [4]GlyphPoint
	// Instructions is the glyph's own program: that of a simple glyph, or the
	// one a composite runs after its components are placed. It is empty for a
	// glyph without instructions. It is a view into the font's bytes.
	Instructions []byte
	// Components lists a composite glyph's components in order; it is nil
	// for a simple glyph. A component's own instructions are in its own
	// description ([Face.GlyphDescription] of its Glyph).
	Components []GlyphComponent
}

GlyphDescription is a TrueType glyph the way a hinting program sees it: the points with their contours, the four phantom points, and the glyph's own instructions, all in unscaled font units. It is what the glyf table holds, with composites assembled; nothing is hinted or scaled.

func (*GlyphDescription) IsComposite added in v1.1.0

func (d *GlyphDescription) IsComposite() bool

IsComposite reports whether the glyph is built from components.

type GlyphID

type GlyphID uint16

GlyphID indexes a glyph in a face. Glyph 0 is the font's .notdef glyph.

type GlyphInfo

type GlyphInfo struct {
	Glyph GlyphID
	// Cluster is the byte offset in the text of the first character the glyph
	// stands for. See Run.
	Cluster int
	// AdvanceX and AdvanceY are the pen movement after the glyph, OffsetX and
	// OffsetY where the glyph is drawn relative to the pen, y up, all in font
	// units.
	AdvanceX, AdvanceY, OffsetX, OffsetY int32
}

GlyphInfo is one glyph of a Run.

type GlyphPoint added in v1.1.0

type GlyphPoint struct {
	X, Y    float32
	OnCurve bool // the point is on the outline; otherwise it is a quadratic control point
}

GlyphPoint is one point of a TrueType glyph in font units. A point's coordinates are whole numbers in the font's default design; at an instance of a variable font they are what gvar made of them, which can be fractional.

type HintingTables added in v1.1.0

type HintingTables struct {
	// FontProgram is the fpgm table: run once per font to define functions.
	FontProgram []byte
	// PrepProgram is the prep table: run for each size.
	PrepProgram []byte
	// ControlValues is the cvt table's values in font units. cvar is not
	// applied, so an instance of a variable font has the default values.
	ControlValues []int16
	// Gasp is the gasp table's ranges: how to render at which sizes.
	Gasp []GaspRange
	// MaxProfile holds the maxp limits for a program's storage.
	MaxProfile MaxProfile
}

HintingTables are the tables a TrueType hinting program runs on, read from a face. Slices are views into the font's bytes except ControlValues.

type Instance

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

Instance is a face at one design: the face plus normalised coordinates. It offers the face's outline, advance and metric methods with the variations applied. An Instance is immutable and safe for concurrent use.

Example (Shape)

A variable font is shaped at an instance, which gives the advances of its design.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.VariableTrueType(true))
	inst, err := face.Instance(onefont.Variation{Tag: onefont.MakeTag("wght"), Value: 900})
	if err != nil {
		panic(err)
	}
	run, err := onefont.Shape("A", inst)
	fmt.Println(run.Len(), err)
}
Output:
1 <nil>

func (*Instance) Advance

func (in *Instance) Advance(g GlyphID) int32

Advance returns the advance width at the instance (see HMetrics).

func (*Instance) ContourPoint

func (in *Instance) ContourPoint(g GlyphID, n int) (x, y int32, ok bool)

ContourPoint is Face.ContourPoint at the instance, so a variable glyph's points have moved with the design.

func (*Instance) Coords

func (in *Instance) Coords() []int16

Coords returns the normalised F2DOT14 coordinates, one per axis, or nil for a face without axes. Layout code feeds them to variation indices. The slice is the instance's own; do not modify it.

func (*Instance) Face

func (in *Instance) Face() *Face

Face returns the face the instance varies.

func (*Instance) GlyphBounds

func (in *Instance) GlyphBounds(g GlyphID) (tight, control Rect, err error)

GlyphBounds is Face.GlyphBounds at the instance.

func (*Instance) GlyphDescription added in v1.1.0

func (in *Instance) GlyphDescription(g GlyphID) (*GlyphDescription, error)

GlyphDescription is Face.GlyphDescription at the instance: the points are those gvar moved to the instance's design, and the phantom points use the instance's advance and side bearing. The instructions are the font's (cvar and the hinting of variable fonts are the caller's to apply).

func (*Instance) GlyphIndex

func (in *Instance) GlyphIndex(r rune) GlyphID

GlyphIndex returns the glyph for r, as Face.GlyphIndex does: the cmap does not vary.

func (*Instance) GlyphIndexVariation

func (in *Instance) GlyphIndexVariation(r, selector rune) (GlyphID, bool)

GlyphIndexVariation is Face.GlyphIndexVariation of the instance's face.

func (*Instance) GlyphPath

func (in *Instance) GlyphPath(g GlyphID) (Path, error)

GlyphPath returns glyph g's outline at the instance as a Path.

func (*Instance) HMetrics

func (in *Instance) HMetrics(g GlyphID) (advance, lsb int32)

HMetrics returns the glyph's advance width at the instance, rounded to whole font units, and its left side bearing. The advance follows HVAR when the font has it and otherwise the gvar phantom points. The bearing is, in order: the hmtx value changed by HVAR's side bearing mapping when the font has one; else, for a TrueType font with gvar, the left edge of the instance's outline (the default bearing for a glyph with no outline); else the default bearing.

func (*Instance) Kerning

func (in *Instance) Kerning(left, right GlyphID) int32

Kerning returns the pair adjustment at the instance: as Face.Kerning, in font units at the instance's design.

func (*Instance) Metrics

func (in *Instance) Metrics() Metrics

Metrics returns the face's metrics changed by MVAR at the instance. Fields MVAR has no record for, and the weight and width classes, are the face's.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.VariableTrueType(true))
	in, _ := face.InstanceAt([]int16{16384})
	fmt.Println(face.Metrics().Ascender, in.Metrics().Ascender)
}
Output:
800 830

func (*Instance) NumGlyphs

func (in *Instance) NumGlyphs() int

NumGlyphs returns the face's glyph count.

func (*Instance) Outline

func (in *Instance) Outline(g GlyphID, sink PathSink) error

Outline draws glyph g at the instance. See Face.Outline for errors and limits; gvar tuple, point and work limits add ErrInvalidFont failures.

func (*Instance) UnitsPerEm

func (in *Instance) UnitsPerEm() int32

UnitsPerEm returns the face's em size in font units.

func (*Instance) Variations

func (in *Instance) Variations() []Variation

Variations returns the instance's user-space value for every axis of the face, in fvar order: the values the instance was made with after clamping to each axis's range, the axis default for an axis the caller did not name. An instance made from normalised coordinates (Face.InstanceAt) reports the user-space values those coordinates stand for, which can differ from the ones that produced them by the 1/16384 grid. A face without axes gives nil.

type JoiningType

type JoiningType uint8

JoiningType is a character's Joining_Type, the Unicode property that says how a cursive script's letters connect to their neighbours (UAX #44, ArabicShaping.txt).

const (
	// JoiningNone (U, Non_Joining) joins to neither neighbour. It is the
	// value of every character no other value is listed for.
	JoiningNone JoiningType = iota
	// JoiningCauses (C, Join_Causing) forces a join without a form of its own,
	// like the tatweel or the zero width joiner.
	JoiningCauses
	// JoiningDual (D, Dual_Joining) joins to the letter before and to the
	// letter after.
	JoiningDual
	// JoiningLeft (L, Left_Joining) joins only to the letter after it in
	// logical order.
	JoiningLeft
	// JoiningRight (R, Right_Joining) joins only to the letter before it in
	// logical order.
	JoiningRight
	// JoiningTransparent (T) does not interrupt a join: combining marks and
	// format controls.
	JoiningTransparent
)

The Joining_Type values.

func JoiningTypeOf

func JoiningTypeOf(r rune) JoiningType

JoiningTypeOf returns the Joining_Type of r in Unicode 17.0.0. Code points that are not characters, and values outside the Unicode range, are JoiningNone.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	for _, r := range []rune{'\u0628', '\u0627', '\u064B', 'a'} {
		fmt.Printf("%U %v\n", r, onefont.JoiningTypeOf(r))
	}
}
Output:
U+0628 D
U+0627 R
U+064B T
U+0061 U

func (JoiningType) String

func (j JoiningType) String() string

String returns the Unicode short name of the value: "U", "C", "D", "L", "R" or "T".

type LineBreak

type LineBreak struct {
	// Pos is the byte offset of the boundary, after 0 and up to len(text).
	Pos int
	// Mandatory is true when the line must end here (a hard line break).
	Mandatory bool
}

LineBreak is a line break opportunity: the boundary at byte offset Pos, just before the character that starts there, or the end of the text.

type MaxProfile added in v1.1.0

type MaxProfile struct {
	MaxZones              int
	MaxTwilightPoints     int
	MaxStorage            int
	MaxFunctionDefs       int
	MaxInstructionDefs    int
	MaxStackElements      int
	MaxSizeOfInstructions int
}

MaxProfile holds the limits the version 1.0 maxp table gives a TrueType interpreter. A font with a version 0.5 maxp or no maxp has zeros.

type Metrics

type Metrics struct {
	UnitsPerEm int32 // head.unitsPerEm
	NumGlyphs  int   // maxp.numGlyphs

	Ascender  int32 // hhea.ascender
	Descender int32 // hhea.descender; negative below the baseline
	LineGap   int32 // hhea.lineGap

	Weight      int   // OS/2.usWeightClass
	Width       int   // OS/2.usWidthClass
	TypoAscent  int32 // OS/2.sTypoAscender
	TypoDescent int32 // OS/2.sTypoDescender
	TypoLineGap int32 // OS/2.sTypoLineGap
	WinAscent   int32 // OS/2.usWinAscent
	WinDescent  int32 // OS/2.usWinDescent
	XHeight     int32 // OS/2.sxHeight; 0 below OS/2 version 2
	CapHeight   int32 // OS/2.sCapHeight; 0 below OS/2 version 2

	StrikeoutPosition  int32   // OS/2.yStrikeoutPosition
	StrikeoutSize      int32   // OS/2.yStrikeoutSize
	SubscriptYOffset   int32   // OS/2.ySubscriptYOffset
	SuperscriptYOffset int32   // OS/2.ySuperscriptYOffset
	UnderlinePosition  int32   // post.underlinePosition
	UnderlineThickness int32   // post.underlineThickness
	ItalicAngle        float32 // post.italicAngle in degrees, counter-clockwise from the vertical
	IsFixedPitch       bool    // post.isFixedPitch is nonzero
	UseTypoMetrics     bool    // OS/2.fsSelection bit 7
	// IsBold is true when OS/2.fsSelection bit 5 or head.macStyle bit 0 is
	// set, or the font has an OS/2 table whose usWeightClass is 600 or more.
	// IsItalic is true when OS/2.fsSelection bit 0 (italic) or bit 9
	// (oblique) or head.macStyle bit 1 is set. They are the font's own
	// fields: an instance of a variable font is as bold as the font is.
	IsItalic, IsBold bool
}

Metrics holds the vertical and decoration metrics a font states, each in font units exactly as its table field stores it. A field whose table is missing or too short is 0.

type NameID

type NameID uint16

NameID identifies a name table string.

const (
	NameCopyright     NameID = 0
	NameFamily        NameID = 1
	NameSubfamily     NameID = 2
	NameUniqueID      NameID = 3
	NameFull          NameID = 4
	NameVersion       NameID = 5
	NamePostScript    NameID = 6
	NameTypoFamily    NameID = 16
	NameTypoSubfamily NameID = 17
	NameWWSFamily     NameID = 21
	NameWWSSubfamily  NameID = 22
)

Common name IDs (OpenType name table, "Name IDs").

type NameRecord

type NameRecord struct {
	Platform, Encoding, Language int
	ID                           NameID
	Value                        string
}

NameRecord is one entry of the name table with its string decoded to UTF-8.

type NamedInstance

type NamedInstance struct {
	Name             string // the subfamily name, chosen as Face.Name chooses
	SubfamilyNameID  NameID
	PostScriptNameID NameID    // 0xFFFF when the record has none
	PostScriptName   string    // the PostScript name, chosen as Face.Name chooses; "" when the record has none
	Coords           []float32 // user-space value per axis, in Axes order
}

NamedInstance is a design the font names, such as "Bold" (fvar, "InstanceRecord").

type Option

type Option func(*options)

Option configures Parse.

func WithFace

func WithFace(index int) Option

WithFace selects the face of a TrueType Collection by index. The default is 0. A plain font file has one face, index 0.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	ttc := fonttest.Collection(fonttest.TrueType(), fonttest.CFF())
	n, _ := onefont.NumFaces(ttc)
	for i := range n {
		face, err := onefont.Parse(ttc, onefont.WithFace(i))
		if err != nil {
			panic(err)
		}
		fmt.Println(i, face.OutlineFormat())
	}
	_, err := onefont.Parse(ttc, onefont.WithFace(n))
	fmt.Println(err)
}
Output:
0 truetype
1 cff
onefont: face index out of range: ttc: collection has fewer faces

type OutlineFormat

type OutlineFormat uint8

OutlineFormat says how a face stores glyph outlines.

const (
	OutlineNone     OutlineFormat = iota // no glyf, CFF or CFF2 table
	OutlineTrueType                      // glyf and loca: quadratic curves
	OutlineCFF                           // CFF table: cubic curves
	OutlineCFF2                          // CFF2 table: cubic curves, variable
)

Outline formats.

func (OutlineFormat) String

func (o OutlineFormat) String() string

String names the format as "none", "truetype", "cff" or "cff2".

type Path

type Path struct {
	Segments []PathSegment
}

Path records an outline. The zero value is an empty path ready to use, and *Path implements PathSink. Segments is exported so a caller can read it directly or append segments of its own, as long as every contour starts with PathMove; Reset keeps the backing array for reuse.

func (*Path) All

func (p *Path) All() iter.Seq[PathSegment]

All iterates over the path's segments in order.

func (*Path) Bounds

func (p *Path) Bounds() (tight, control Rect)

Bounds returns two boxes of the outline: tight, which fits the curves themselves (a curve that bulges past its end points is measured at its extremum, and a control point outside the curve does not widen it), and control, which fits every point including off-curve control points. A path with no points gives two zero boxes.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	var p onefont.Path
	p.MoveTo(0, 0)
	p.QuadTo(50, 100, 100, 0)
	p.Close()
	tight, control := p.Bounds()
	fmt.Println(tight, control)

	// Mirror the outline left to right and move it into positive x.
	p.Transform(onefont.Translate(100, 0).Mul(onefont.Scale(-1, 1)))
	tight, _ = p.Bounds()
	fmt.Println(tight)
}
Output:
{0 0 100 50} {0 0 100 100}
{0 0 100 50}

func (*Path) Close

func (p *Path) Close()

Close implements PathSink.

func (*Path) CubicTo

func (p *Path) CubicTo(c1x, c1y, c2x, c2y, x, y float32)

CubicTo implements PathSink.

func (*Path) LineTo

func (p *Path) LineTo(x, y float32)

LineTo implements PathSink.

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float32)

MoveTo implements PathSink.

func (*Path) QuadTo

func (p *Path) QuadTo(cx, cy, x, y float32)

QuadTo implements PathSink.

func (*Path) Reset

func (p *Path) Reset()

Reset empties the path, keeping its capacity.

func (*Path) Transform

func (p *Path) Transform(m Affine)

Transform maps every point of the path through m, in place. Control points move with the end points, so curves stay the same kind: a map with a negative determinant mirrors the outline and reverses its winding, and the segments keep their order.

type PathSegment

type PathSegment struct {
	Kind PathSegmentKind
	Pts  [3]Point
}

PathSegment is one path command. Pts holds the points the kind uses, in drawing order: PathMove and PathLine use Pts[0]; PathQuad uses control, end; PathCubic uses control 1, control 2, end; PathClose uses none.

type PathSegmentKind

type PathSegmentKind uint8

PathSegmentKind says what a PathSegment draws.

const (
	PathMove PathSegmentKind = iota
	PathLine
	PathQuad
	PathCubic
	PathClose
)

The kinds of PathSegment.

func (PathSegmentKind) String

func (k PathSegmentKind) String() string

String names the kind: "move", "line", "quad", "cubic" or "close".

type PathSink

type PathSink interface {
	MoveTo(x, y float32)
	LineTo(x, y float32)
	// QuadTo draws a quadratic curve with control point (cx, cy) to (x, y).
	QuadTo(cx, cy, x, y float32)
	// CubicTo draws a cubic curve with control points (c1x, c1y) and (c2x, c2y) to (x, y).
	CubicTo(c1x, c1y, c2x, c2y, x, y float32)
	// Close ends the contour with a line back to its start.
	Close()
}

PathSink receives an outline as a sequence of contours in font units, y up. Every contour is MoveTo, any number of segments, then Close. TrueType outlines produce only QuadTo curves and CFF outlines only CubicTo; neither is converted to the other.

type Point

type Point struct{ X, Y float32 }

Point is a position in font units.

type Rect

type Rect struct {
	MinX, MinY, MaxX, MaxY float32
}

Rect is an axis-aligned box in font units. The zero Rect is the box of an empty outline.

func (Rect) Empty

func (r Rect) Empty() bool

Empty reports whether the box has no area.

type Run

type Run struct {
	Glyphs   []GlyphID
	Clusters []int
	AdvanceX []int32
	AdvanceY []int32
	OffsetX  []int32
	OffsetY  []int32

	// Direction is the direction the run was shaped in, DirectionLTR or
	// DirectionRTL, never DirectionAuto.
	Direction Direction
	// Script is the ISO 15924 code of the script the run was shaped as. "Zyyy"
	// (Common) means the run had no script: none was given, no character of
	// the text has one, and no default script applied.
	Script string

	// Origins holds, for every glyph, the byte offset in the text of the
	// character it was made from, when the call had [WithOrigins]; otherwise
	// it is empty. A glyph that stands for one character has that character
	// (a vowel sign split in two has it twice), a ligature the first character
	// it replaced, and a glyph the shaper moved (a vowel sign drawn before its
	// consonant, a reph drawn after its base) the character it came from, not
	// the one whose cluster it joined. Clusters, by contrast, are the
	// grapheme-level values described above.
	Origins []int
}

Run is the result of shaping: the glyphs of a text in visual order, left to right, as hb-shape prints them. For a right-to-left run that is the reverse of logical order. A Run is reused by passing it to Shaper.Shape again, which keeps its storage.

Advances and offsets are whole font units: for an instance of a variable font each glyph's advance is the rounded value, so Width is the sum of the rounded advances.

Glyphs, Clusters, AdvanceX, AdvanceY, OffsetX and OffsetY always have equal length: Run.At, Run.All and Run.Width rely on it, and At panics when it is broken. A caller may reslice them, all together and by the same amount, or read and write the elements, but must not append to one of them alone. Origins is either empty or as long as the others. The shaper itself reinitialises every slice on each call, so a Run needs no reset.

Clusters follow HarfBuzz's default (monotone grapheme) level: a glyph's cluster is the byte offset of the first character it stands for; the glyphs one character splits into share its cluster; a ligature has the cluster of its first component; a combining mark, or a zero width joiner, has the cluster of the character before it, and so has the second letter of a flag (a pair of regional indicators). Clusters never increase from left to right in a right-to-left run and never decrease in a left-to-right run.

func Shape

func Shape(text string, font Font, opts ...ShapeOption) (*Run, error)

Shape shapes text with font and returns the glyphs. Script and direction are taken from the text unless WithScript and WithDirection say otherwise. It uses a pooled Shaper; to shape many texts without allocating, keep a Shaper and a Run and call Shaper.Shape.

Text is UTF-8; each invalid byte shapes as U+FFFD. The error is non-nil only when font is nil (ErrInvalidArgument), or when the text is longer than 1 GiB or the font's lookups would grow the run past the growth limit (ErrLimit).

A hostile font cannot make Shape run long or grow without bound. For a text of n characters, the lookups of each table together take at most about (n+8)*(64+4*L) steps for L lookups plus a fixed allowance; when that runs out the remaining lookups are skipped and the glyphs so far are returned. A run may not grow past 4*n glyphs (8192 at least), nor by more than 2^20 glyphs: a substitution that would pass that makes Shape return ErrLimit instead of a truncated run. Lookups applied from inside lookups nest at most 8 deep, and no lookup list, class table or extension chain is followed by recursion. Memory is proportional to the run's length, so it is bounded by the text's length plus the growth limit.

Example

Shape needs only a font and a text: the script and direction come from the text, and the glyphs come back left to right.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, err := onefont.Parse(fonttest.TrueType())
	if err != nil {
		panic(err)
	}
	run, err := onefont.Shape("AB", face)
	if err != nil {
		panic(err)
	}
	for _, g := range run.All() {
		fmt.Println("glyph", g.Glyph, "cluster", g.Cluster)
	}
	fmt.Println(run.Script, run.Direction == onefont.DirectionLTR)
}
Output:
glyph 1 cluster 0
glyph 2 cluster 1
Latn true

func (*Run) All

func (r *Run) All() iter.Seq2[int, GlyphInfo]

All yields the glyphs left to right.

func (*Run) At

func (r *Run) At(i int) GlyphInfo

At returns glyph i. It panics when i is out of range, like indexing.

func (*Run) Len

func (r *Run) Len() int

Len returns the number of glyphs.

func (*Run) Width

func (r *Run) Width() int32

Width returns the sum of the horizontal advances, in font units. The sum stops at the largest or smallest int32 rather than wrapping; a run that wide has no sensible width anyway.

type Segmenter

type Segmenter struct {
	// NoDictionary turns off dictionary line breaking. By default
	// AppendLineBreaks also allows a break between the words of a run of
	// Thai, Lao, Khmer or Burmese letters, found by matching word lists
	// built into the library, as browsers do; the rules of UAX #14 alone
	// (class SA, handled as alphabetic text) allow none inside the run. The
	// word lists do not cover every word: characters outside them stay
	// together up to the next word. The field is read at each call and
	// affects only line breaks.
	NoDictionary bool
	// contains filtered or unexported fields
}

Segmenter finds line break opportunities (UAX #14) and grapheme cluster, word and sentence boundaries (UAX #29) for Unicode 17.0.0, with the default rules and no tailoring: no locale rules and no abbreviation lists. The one addition is line breaking in Thai, Lao, Khmer and Burmese, which UAX #14 leaves to a dictionary: see Segmenter.NoDictionary.

The Append methods take a string and report byte offsets. Every kind reports the same thing, the boundaries after offset 0 up to len(text), so the last entry is always len(text) and text[prev:b] is the segment ending at b. A Segmenter keeps its buffers between calls, so one Segmenter reused for many texts allocates only while the buffers grow. The zero value is ready to use. A Segmenter is not safe for concurrent use.

Invalid UTF-8 decodes to one U+FFFD per invalid byte, as Go's range loop does, so every invalid byte is a rune of its own. At most 2³¹−1 runes of a text are processed.

Example

A Segmenter reused across texts allocates only while its buffers grow.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
)

func main() {
	var s onefont.Segmenter
	var breaks []int
	for _, text := range []string{"ab cd", "x y"} {
		breaks = s.AppendWordBreaks(breaks[:0], text)
		fmt.Println(breaks)
	}
}
Output:
[2 3 5]
[1 2 3]

func (*Segmenter) AppendGraphemeBreaks

func (s *Segmenter) AppendGraphemeBreaks(dst []int, text string) []int

AppendGraphemeBreaks appends to dst the extended grapheme cluster boundaries of text (UAX #29 rules GB1 to GB999) as byte offsets: the end of every cluster, ending with len(text). Offset 0 is not listed, so for a non-empty text the cluster i is text[prev:b] with prev the previous entry (0 for the first). Empty text has none.

func (*Segmenter) AppendLineBreaks

func (s *Segmenter) AppendLineBreaks(dst []LineBreak, text string) []LineBreak

AppendLineBreaks appends to dst the line break opportunities of text (UAX #14 rules LB2 to LB31) as byte offsets, in increasing order. A break at Pos allows a line to end just before it. Like the other kinds, offset 0 never appears and the end of the text always does; the end is Mandatory only when the text ends with a hard line break (LF, CR, CRLF, NEL, form feed, vertical tab or a line or paragraph separator). A break is Mandatory when the line must end there. Empty text has none.

func (*Segmenter) AppendSentenceBreaks

func (s *Segmenter) AppendSentenceBreaks(dst []int, text string) []int

AppendSentenceBreaks appends to dst the sentence boundaries of text (UAX #29 rules SB1 to SB998) as byte offsets: every boundary after offset 0, ending with len(text). Empty text has none.

func (*Segmenter) AppendWordBreaks

func (s *Segmenter) AppendWordBreaks(dst []int, text string) []int

AppendWordBreaks appends to dst the word boundaries of text (UAX #29 rules WB1 to WB999) as byte offsets: every boundary after offset 0, ending with len(text). Spaces and punctuation are segments of their own, so a boundary is not necessarily the edge of a word that a user would select. Empty text has none.

type ShapeOption

type ShapeOption func(*shapeParams)

ShapeOption configures a shaping call.

func WithDefaultScript

func WithDefaultScript(code string) ShapeOption

WithDefaultScript sets the script, by its ISO 15924 code, that a run is shaped as when none of its characters has a script of its own (digits, spaces and punctuation have none). It is the script a paragraph layout carries from the run before. WithScript takes precedence: it fixes the script whatever the text holds. An unknown code is ignored, so a run without a script of its own is then shaped by the default shaper. See Shaper.ShapeRuns, which carries the script along by itself.

Example

A run of digits and spaces has no script of its own; it takes the one the run before it was shaped with, or the one WithDefaultScript names.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	run, _ := onefont.Shape("12", face, onefont.WithDefaultScript("Arab"))
	fmt.Println(run.Script)
	run, _ = onefont.Shape("12", face)
	fmt.Println(run.Script)
}
Output:
Arab
Zyyy

func WithDirection

func WithDirection(d Direction) ShapeOption

WithDirection sets the direction of the run. The default is DirectionAuto.

Example

A right-to-left run comes back in visual order, so the glyphs read left to right and the clusters count down.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	run, _ := onefont.Shape("AB", face, onefont.WithDirection(onefont.DirectionRTL))
	fmt.Println(run.Glyphs, run.Clusters)
}
Output:
[2 1] [1 0]

func WithFeatureRanges added in v1.1.0

func WithFeatureRanges(ranges ...FeatureRange) ShapeOption

WithFeatureRanges sets features over ranges of the text, on top of the script's defaults and of WithFeatures: inside its range a setting replaces the value the whole-run features give, outside it has no effect. A range with End <= Start, or one lying outside the text, matches no glyph. Offsets count bytes from the start of the text given to the call; with Shaper.ShapeRuns, FallbackChain.ShapeRuns and Shaper.ShapeText they count from the start of the whole text, not of each run or piece. For features the font lacks the setting is ignored. Of several settings of one tag that overlap, the last one wins.

func WithFeatures

func WithFeatures(features ...Feature) ShapeOption

WithFeatures sets features on top of the script's defaults. Later settings of a tag replace earlier ones. Features the font does not have are ignored.

func WithGraphemeClusters added in v1.1.0

func WithGraphemeClusters() ShapeOption

WithGraphemeClusters makes every cluster of the result one extended grapheme cluster (UAX #29, with the conjunct rule GB9c), the unit a text cursor moves over, instead of HarfBuzz's default clusters. The two differ in scripts whose letters stack with a virama: HarfBuzz starts a new cluster at the half form before the virama's consonant, so Devanagari "स्ते" is two clusters; with this option it is one. A glyph's cluster is the byte offset of the first character of the grapheme cluster of the first character it stands for, so glyph shapes, advances and offsets are unchanged and only the cluster values merge. The default is off.

func WithLanguage

func WithLanguage(tag string) ShapeOption

WithLanguage sets the language as a BCP 47 tag ("tr", "zh-Hant", "sr-Cyrl"). It selects the font's language system for the lookups and so language specific forms. The default is no language.

func WithOrigins

func WithOrigins() ShapeOption

WithOrigins asks for Run.Origins: for every glyph, the byte offset of the character it was made from. It costs one more slice per run, so it is off by default.

Example

WithOrigins reports the character each glyph came from, whatever the shaper did to the glyph order and clusters.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	run, _ := onefont.Shape("A\u00e9B", face, onefont.WithOrigins())
	fmt.Println(run.Origins)
}
Output:
[0 1 3]

func WithScript

func WithScript(code string) ShapeOption

WithScript sets the script by its ISO 15924 code ("Latn", "Arab", "Hebr"; case does not matter). The default, and the result of an unknown code, is the script of the first character that has one (not Common or Inherited), or the one WithDefaultScript names when no character has one; failing that, a run whose Common characters are used by Arabic (the tatweel U+0640, the Arabic comma) is shaped as Arabic, so a span of tatweels joins. A given code forces the script: the text need not agree with it, so Arabic letters shaped as "Latn" get no joining forms. A run is shaped as one script; split mixed text first, or use Shaper.ShapeRuns.

type ShapedRun

type ShapedRun struct {
	// Start and End are the byte range of the run in the text.
	Start, End int
	// Font is the index in the chain of the font the run was shaped with.
	Font int
	// Level is the bidi embedding level of the run. [Shaper.ShapeText] sets
	// it to the resolved level; [FallbackChain.ShapeRuns] resolves no bidi
	// and sets 0 for a run shaped left to right and 1 for one shaped right to
	// left.
	Level BidiLevel
	// Run holds the glyphs, with clusters and origins as byte offsets into
	// the whole text. It is never nil when the error yielded with the
	// ShapedRun is nil. The Run is reused between iterations, so copy what you
	// keep.
	Run *Run
}

ShapedRun is a stretch of a text shaped with one font of a FallbackChain: what FallbackChain.ShapeRuns, Shaper.ShapeText and ShapeText yield.

type Shaper

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

Shaper is a reusable shaping buffer. Calling Shaper.Shape again with the same font, script, language and features reuses the lookup plan and the buffers, and allocates nothing once they have grown to the text's size.

The zero Shaper is ready to use. A Shaper must not be copied after first use, and is not safe for concurrent use; use one per goroutine. The Run it fills belongs to the caller.

func NewShaper

func NewShaper() *Shaper

NewShaper returns a Shaper ready to use.

func (*Shaper) Kerning

func (s *Shaper) Kerning(font Font, left, right GlyphID) int32

Kerning returns the pair adjustment of a glyph pair as Face.Kerning defines it, for any Font, reusing the Shaper's lookup plans. A nil font gives 0.

func (*Shaper) Shape

func (s *Shaper) Shape(dst *Run, text string, font Font, opts ...ShapeOption) error

Shape shapes text with font into dst, replacing what dst held. See Shape for the rules; the options are those of WithDirection, WithScript, WithLanguage and WithFeatures.

Nothing a font or text contains makes Shape panic or run unboundedly: substitution and positioning keep work, nesting and growth budgets. A lookup that would exceed the work or nesting budget stops being applied; one that would grow the run past its limit makes Shape return ErrLimit (see Shape for the limits).

Example

A Shaper keeps its buffers and lookup plans between calls, so shaping many texts with it into one Run allocates nothing once the buffers have grown.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	shaper := onefont.NewShaper()
	var run onefont.Run
	for _, text := range []string{"AB", "BA", "A"} {
		if err := shaper.Shape(&run, text, face); err != nil {
			panic(err)
		}
		fmt.Println(text, run.Glyphs)
	}
}
Output:
AB [1 2]
BA [2 1]
A [1]

func (*Shaper) ShapeRuns

func (s *Shaper) ShapeRuns(text string, font Font, runs []TextRun, opts ...ShapeOption) iter.Seq2[ShapedRun, error]

ShapeRuns shapes text as the given runs, in order, each on its own: only the run's characters take part, so nothing substitutes or kerns across two runs, and the run is shaped in its own direction. It yields every run with its glyphs, the way a paragraph layout shapes a paragraph one run after the other. The Run is reused between iterations, so copy what you keep.

Clusters and, with WithOrigins, origins are byte offsets into text, not into the run, so the glyphs of all runs line up with the one text.

The script of a run is that of its first character that has a script of its own. A run without one (digits, spaces and punctuation after Arabic text) takes the script of the run before it, so that it is shaped like its neighbours; the first run takes the one WithDefaultScript names, or none. WithScript instead fixes the script of every run and nothing is carried. Language and features apply to every run. WithDirection sets the direction of the runs whose Direction is DirectionAuto.

Each run is yielded as a ShapedRun, as FallbackChain.ShapeRuns does, with Start and End the clamped bounds, Font 0, Level 0 or 1 by the direction the run was shaped in, and Run never nil when the error is nil. A nil font, or a text longer than 1 GiB, yields one non-nil error wrapping ErrInvalidArgument or ErrLimit and ends the iteration.

Bounds that fall outside the text are clamped to it, and a run whose End is before its Start is empty; a bound inside a character shapes the invalid bytes as U+FFFD, as Shape does. The runs need not tile the text. The Shaper is used while the iteration runs, so it must not be used elsewhere at the same time.

Example

ShapeRuns shapes a paragraph run by run, as a layout engine does after bidi analysis. Clusters count bytes of the whole text.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	face, _ := onefont.Parse(fonttest.TrueType())
	text := "AB BA"
	runs := []onefont.TextRun{
		{Start: 0, End: 2, Direction: onefont.DirectionLTR},
		{Start: 2, End: 5, Direction: onefont.DirectionLTR},
	}
	for run, err := range onefont.NewShaper().ShapeRuns(text, face, runs) {
		if err != nil {
			panic(err)
		}
		fmt.Println(run.Start, run.Run.Glyphs, run.Run.Clusters)
	}
}
Output:
0 [1 2] [0 1]
2 [0 2 1] [2 3 4]

func (*Shaper) ShapeText

func (s *Shaper) ShapeText(text string, chain *FallbackChain, opts ...ShapeOption) iter.Seq2[ShapedRun, error]

ShapeText shapes a text of any mix of directions and scripts over a fallback chain, and yields the runs in visual order. It resolves the bidirectional algorithm (UAX #9) for each paragraph of text, takes the paragraph as one line, splits every bidi run by font as FallbackChain.Runs does, and shapes each piece with its own font in the direction of its level. Paragraphs come in text order; within a paragraph the runs come left to right as they are displayed, so a right-to-left bidi run yields its pieces from the end of the text towards its start, each piece with its glyphs in display order.

The base direction of the paragraphs is that of WithDirection: DirectionAuto, the default, takes each paragraph's from its first strong character, as Bidi.Resolve does. A run is always shaped in the direction of its level, whatever the option says. Script is worked out for each piece from its own text unless WithScript fixes it; language, features and WithOrigins apply to every piece. Mirroring of paired characters in right-to-left runs is left to the font's rtlm and the like; see BidiMirror to map characters yourself.

ShapedRun.Start and End, and the clusters and origins of the Run, are byte offsets into text. To lay text out in lines, break it first (Segmenter.AppendLineBreaks), and call ShapeText for each line: the line's own bidi resolution is then what the reader sees. The Run is reused between iterations, so copy what you keep.

An empty text yields nothing. A chain with no fonts, a nil chain entry that a piece needs, or a text longer than 1 GiB yields one error wrapping ErrInvalidArgument or ErrLimit and ends the iteration. The Shaper is used while the iteration runs, so it must not be used elsewhere at the same time. The chain is only read, so one chain may serve several goroutines, each with its own Shaper.

Example

ShapeText is the call for text of any mix of directions: it resolves bidi, cuts each bidi run by font, shapes every piece with its own font in its own direction, and yields the pieces in the order they are displayed. Here Hebrew and Arabic-Indic digits fall back to a second font, and the digits keep their reading order inside the right-to-left run.

package main

import (
	"fmt"

	"recursiveai.org/go/onefont"
	"recursiveai.org/go/onefont/internal/fonttest"
)

func main() {
	latin, _ := onefont.Parse(fonttest.Cover("ab cd"))
	other, _ := onefont.Parse(fonttest.Cover("\u05d0\u05d1\u0663\u0664"))
	chain := onefont.NewFallbackChain(latin, other)
	text := "ab \u05d0\u05d1 \u0663\u0664 cd"
	shaper := onefont.NewShaper()
	for sr, err := range shaper.ShapeText(text, chain) {
		if err != nil {
			panic(err)
		}
		fmt.Printf("%q font=%d level=%d %v glyphs=%v clusters=%v\n",
			text[sr.Start:sr.End], sr.Font, sr.Level, sr.Run.Direction, sr.Run.Glyphs, sr.Run.Clusters)
	}
}
Output:
"ab " font=0 level=0 ltr glyphs=[1 2 3] clusters=[0 1 2]
"٣٤" font=1 level=2 ltr glyphs=[3 4] clusters=[8 10]
" " font=0 level=1 rtl glyphs=[3] clusters=[7]
"אב" font=1 level=1 rtl glyphs=[2 1] clusters=[5 3]
" cd" font=0 level=0 ltr glyphs=[3 4 5] clusters=[12 13 14]

type Tag

type Tag uint32

Tag is an OpenType table tag: four ASCII bytes compared exactly.

const (
	TagHead Tag = 'h'<<24 | 'e'<<16 | 'a'<<8 | 'd'
	TagHhea Tag = 'h'<<24 | 'h'<<16 | 'e'<<8 | 'a'
	TagHmtx Tag = 'h'<<24 | 'm'<<16 | 't'<<8 | 'x'
	TagMaxp Tag = 'm'<<24 | 'a'<<16 | 'x'<<8 | 'p'
	TagOS2  Tag = 'O'<<24 | 'S'<<16 | '/'<<8 | '2'
	TagName Tag = 'n'<<24 | 'a'<<16 | 'm'<<8 | 'e'
	TagPost Tag = 'p'<<24 | 'o'<<16 | 's'<<8 | 't'
	TagCmap Tag = 'c'<<24 | 'm'<<16 | 'a'<<8 | 'p'
	TagKern Tag = 'k'<<24 | 'e'<<16 | 'r'<<8 | 'n'
	TagGlyf Tag = 'g'<<24 | 'l'<<16 | 'y'<<8 | 'f'
	TagLoca Tag = 'l'<<24 | 'o'<<16 | 'c'<<8 | 'a'
	TagCFF  Tag = 'C'<<24 | 'F'<<16 | 'F'<<8 | ' '
	TagCFF2 Tag = 'C'<<24 | 'F'<<16 | 'F'<<8 | '2'
	TagGDEF Tag = 'G'<<24 | 'D'<<16 | 'E'<<8 | 'F'
	TagGSUB Tag = 'G'<<24 | 'S'<<16 | 'U'<<8 | 'B'
	TagGPOS Tag = 'G'<<24 | 'P'<<16 | 'O'<<8 | 'S'
	TagFvar Tag = 'f'<<24 | 'v'<<16 | 'a'<<8 | 'r'
)

Table tags this package reads, plus the ones a shaper reads through Table.

func MakeTag

func MakeTag(s string) Tag

MakeTag returns the tag spelled by s. A string shorter than four bytes is padded with spaces, as OpenType does; bytes after the fourth are silently dropped, and bytes that are not printable ASCII make a tag no font has. Use ParseTag to reject such input.

func ParseTag

func ParseTag(s string) (Tag, error)

ParseTag returns the tag spelled by s: one to four printable ASCII characters (U+0020 to U+007E), padded with spaces to four as OpenType does. Any other string gives an error that wraps ErrInvalidArgument.

func (Tag) String

func (t Tag) String() string

String returns the four-character spelling of the tag.

type TextRun

type TextRun struct {
	Start, End int
	// Direction is the direction the run is shaped in. It wins over
	// [WithDirection]. With [DirectionAuto] the option applies, and without
	// the option the run's own first strong character decides.
	Direction Direction
}

TextRun is a stretch of a text, text[Start:End] in bytes, shaped in one direction. A layout engine cuts a paragraph into runs of one direction (bidi levels) and one font, and shapes each on its own.

type Variation

type Variation struct {
	Tag   Tag
	Value float32
}

Variation sets one axis of an instance to a user-space value.

type WebFontOption added in v1.1.0

type WebFontOption func(*webFontConfig)

WebFontOption configures UnwrapWebFont.

func WithMaxFontSize added in v1.1.0

func WithMaxFontSize(n int) WebFontOption

WithMaxFontSize sets the largest font, in bytes, that UnwrapWebFont unpacks: a file that would unpack to more is refused with an error wrapping ErrLimit. The default is 64 MiB. A web font is compressed, so this limit, not the file's size, is what stops a small file from asking for a very large amount of memory. A value below 1 means the default.

Directories

Path Synopsis
internal
arabic
Package arabic is the shaper for Arabic, Syriac, N'Ko and the other scripts whose letters join into cursive words (Mongolian, Mandaic, Manichaean, Psalter Pahlavi, Sogdian, Adlam, Hanifi Rohingya and more).
Package arabic is the shaper for Arabic, Syriac, N'Ko and the other scripts whose letters join into cursive words (Mongolian, Mandaic, Manichaean, Psalter Pahlavi, Sogdian, Adlam, Hanifi Rohingya and more).
bidi
Package bidi implements the Unicode Bidirectional Algorithm (UAX #9) for Unicode 17.0.0.
Package bidi implements the Unicode Bidirectional Algorithm (UAX #9) for Unicode 17.0.0.
brotli
Package brotli decodes the Brotli compressed data format (RFC 7932).
Package brotli decodes the Brotli compressed data format (RFC 7932).
complexshape
Package complexshape holds the shapers for the Universal Shaping Engine scripts, Khmer, Myanmar, Tibetan, and Thai and Lao.
Package complexshape holds the shapers for the Universal Shaping Engine scripts, Khmer, Myanmar, Tibetan, and Thai and Lao.
conformance
Package conformance locates the Unicode conformance data files for tests.
Package conformance locates the Unicode conformance data files for tests.
dict
Package dict finds word boundaries in runs of text written without spaces (Thai, Lao, Khmer and Burmese) by matching a word list.
Package dict finds word boundaries in runs of text written without spaces (Thai, Lao, Khmer and Burmese) by matching a word list.
fonttest
Package fonttest builds tiny synthetic fonts for tests and examples.
Package fonttest builds tiny synthetic fonts for tests and examples.
hangul
Package hangul is the shaper for Hangul.
Package hangul is the shaper for Hangul.
indic
Package indic is the shaper for the Indic scripts of Microsoft's script development pages: Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam and Sinhala.
Package indic is the shaper for the Indic scripts of Microsoft's script development pages: Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam and Sinhala.
otlayout
Package otlayout applies OpenType layout tables (GSUB, GPOS and GDEF) to a glyph buffer.
Package otlayout applies OpenType layout tables (GSUB, GPOS and GDEF) to a glyph buffer.
segment
Package segment finds text boundaries for Unicode 17.0.0: grapheme cluster, word and sentence boundaries (UAX #29) and line break opportunities (UAX #14), all with the default rules and no tailoring.
Package segment finds text boundaries for Unicode 17.0.0: grapheme cluster, word and sentence boundaries (UAX #29) and line break opportunities (UAX #14), all with the default rules and no tailoring.
shapeprep
Package shapeprep holds the character-level analysis that the complex script shapers run before and after glyph lookups: normalisation for shaping, Arabic joining, and syllable analysis for the Indic, USE, Khmer, Myanmar and Tibetan shapers, plus the Thai and Lao fix-ups.
Package shapeprep holds the character-level analysis that the complex script shapers run before and after glyph lookups: normalisation for shaping, Arabic joining, and syllable analysis for the Indic, USE, Khmer, Myanmar and Tibetan shapers, plus the Thai and Lao fix-ups.
shaping
Package shaping defines what a script shaper is and holds the shapers that need no package of their own: the default shaper and the Hebrew one.
Package shaping defines what a script shaper is and holds the shapers that need no package of their own: the default shaper and the Hebrew one.
ucd
Package ucd holds the Unicode character properties onefont needs, as compact two-stage lookup tables generated from the Unicode Character Database (see tools/ucdgen).
Package ucd holds the Unicode character properties onefont needs, as compact two-stage lookup tables generated from the Unicode Character Database (see tools/ucdgen).
varstore
Package varstore evaluates OpenType item variation stores and delta-set index maps (OpenType "Item variation stores" and "DeltaSetIndexMap"), the structures HVAR, MVAR, CFF2, GDEF and GPOS use to say how a value changes with the design coordinates.
Package varstore evaluates OpenType item variation stores and delta-set index maps (OpenType "Item variation stores" and "DeltaSetIndexMap"), the structures HVAR, MVAR, CFF2, GDEF and GPOS use to say how a value changes with the design coordinates.
webfont
Package webfont unwraps WOFF 1.0 and WOFF 2.0 files (W3C Recommendations) to the sfnt font they hold.
Package webfont unwraps WOFF 1.0 and WOFF 2.0 files (W3C Recommendations) to the sfnt font they hold.

Jump to

Keyboard shortcuts

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