font

package
v0.0.0-...-8f51401 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2025 License: BSD-3-Clause, Unlicense Imports: 15 Imported by: 0

README

font

font is a library that handles loading and utilizing Opentype fonts.

font/opentype implements the low level parsing of a font file and its tables, and font provides an higher level API usable by shapers and renderers.

Documentation

Overview

Package font provides an high level API to access Opentype font properties. See packages [opentype] and opentype/tables for a lower level, more detailled API.

Index

Constants

View Source
const (
	// VariantNotFound is returned when the font does not have a glyph for
	// the given rune and selector.
	VariantNotFound = iota
	// VariantUseDefault is returned when the regular glyph should be used (ignoring the selector).
	VariantUseDefault
	// VariantFound is returned when the font has a variant for the glyph and selector.
	VariantFound
)
View Source
const UseMarkFilteringSet = 1 << 4

Variables

This section is empty.

Functions

func LoadHeadTable

func LoadHeadTable(ld *ot.Loader, buffer []byte) (tables.Head, []byte, error)

LoadHeadTable loads the 'head' or the 'bhed' table.

If a 'bhed' Apple table is present, it replaces the 'head' one.

[buffer] may be provided to reduce allocations; the returned tables.Head is guaranteed not to retain any reference on [buffer]. If [buffer] is nil or has not enough capacity, a new slice is allocated (and returned).

func NormalizeFamily

func NormalizeFamily(family string) string

NormalizeFamily removes spaces and lower the given string.

func ProcessCmap

func ProcessCmap(cmap tables.Cmap, os2FontPage tables.FontPage) (Cmap, UnicodeVariations, error)

ProcessCmap sanitize the given 'cmap' subtable, and select the best encoding when several subtables are given. When present, the variation selectors are returned. [os2FontPage] is used for legacy arabic fonts.

The returned values are copied from the input 'cmap', meaning they do not retain any reference on the input storage.

Types

type AATStateTable

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

AATStateTable supports both regular and extended AAT state machines

func (*AATStateTable) GetClass

func (st *AATStateTable) GetClass(glyph GID) uint16

GetClass return the class for the given glyph, with the correct default value.

func (*AATStateTable) GetEntry

func (st *AATStateTable) GetEntry(state, class uint16) tables.AATStateEntry

GetEntry return the entry for the given state and class, and handle invalid values (by returning an empty entry).

type Aspect

type Aspect struct {
	Style   Style
	Weight  Weight
	Stretch Stretch
}

Aspect stores the properties that specify which font in a family to use: style, weight, and stretchiness.

func (*Aspect) SetDefaults

func (as *Aspect) SetDefaults()

SetDefaults replace unspecified values by the default values: StyleNormal, WeightNormal, StretchNormal

type BitmapFormat

type BitmapFormat uint8

BitmapFormat identifies the format on the glyph raw data. Across the various font files, many formats may be encountered : black and white bitmaps, PNG, TIFF, JPG.

const (

	// The [GlyphBitmap.Data] slice stores a black or white (0/1)
	// bit image, whose length L satisfies
	// L * 8 >= [GlyphBitmap.Width] * [GlyphBitmap.Height]
	BlackAndWhite BitmapFormat
	// The [GlyphBitmap.Data] slice stores a PNG encoded image
	PNG
	// The [GlyphBitmap.Data] slice stores a JPG encoded image
	JPG
	// The [GlyphBitmap.Data] slice stores a TIFF encoded image
	TIFF
)

type BitmapSize

type BitmapSize struct {
	Height, Width uint16
	XPpem, YPpem  uint16
}

BitmapSize expose the size of bitmap glyphs. One font may contain several sizes.

type Cmap

type Cmap interface {
	// Iter returns a new iterator over the cmap
	// Multiple iterators may be used over the same cmap
	// The returned interface is garanted not to be nil.
	Iter() CmapIter

	// Lookup avoid the construction of a map and provides
	// an alternative when only few runes need to be fetched.
	// It returns a default value and false when no glyph is provided.
	Lookup(rune) (GID, bool)
}

Cmap stores a compact representation of a cmap, offering both on-demand rune lookup and full rune range. It is conceptually equivalent to a map[rune]GID, but is often implemented more efficiently.

type CmapIter

type CmapIter interface {
	// Next returns true if the iterator still has data to yield
	Next() bool

	// Char must be called only when `Next` has returned `true`
	Char() (rune, GID)
}

CmapIter is an iterator over a Cmap.

type CmapRuneRanger

type CmapRuneRanger interface {
	// RuneRanges returns a list of (start, end) rune pairs, both included.
	// `dst` is an optional buffer used to reduce allocations
	RuneRanges(dst [][2]rune) [][2]rune
}

CmapRuneRanger is implemented by cmaps whose coverage is defined in terms of rune ranges

type Description

type Description struct {
	Family string
	Aspect Aspect
}

Description provides font metadata.

func Describe

func Describe(ld *ot.Loader, buffer []byte) (Description, []byte)

Describe provides access to family and aspect.

'buffer' may be provided to reduce allocations.

It provides an efficient API, loading only the mininum tables required. See also the method Font.Describe if you already have loaded the font.

type Face

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

Face is a font with user-provided settings. Contrary to the *Font objects, Faces are NOT safe for concurrent use. A Face caches glyph extents and should be reused when possible.

func NewFace

func NewFace(font *Font) *Face

NewFace wraps font and initializes glyph caches.

func ParseTTC

func ParseTTC(file Resource) ([]*Face, error)

ParseTTC parse an Opentype font file, with support for collections. Single font files are supported, returning a slice with length 1.

func ParseTTF

func ParseTTF(file Resource) (*Face, error)

ParseTTF parse an Opentype font file (.otf, .ttf). See ParseTTC for support for collections.

func (*Face) Coords

func (f *Face) Coords() []tables.Coord

Coords return a read-only slice of the current variable coordinates, expressed in normalized units. It is empty for non variable fonts.

func (*Face) FontHExtents

func (f *Face) FontHExtents() (FontExtents, bool)

FontHExtents returns the extents of the font for horizontal text, or false it not available, in font units.

func (*Face) FontVExtents

func (f *Face) FontVExtents() (FontExtents, bool)

FontVExtents is the same as `FontHExtents`, but for vertical text.

func (*Face) GlyphData

func (f *Face) GlyphData(gid GID) GlyphData

GlyphData returns the glyph content for [gid], or nil if not found.

func (*Face) GlyphExtents

func (f *Face) GlyphExtents(glyph GID) (GlyphExtents, bool)

func (*Face) GlyphVOrigin

func (f *Face) GlyphVOrigin(glyph GID) (x, y int32, found bool)

func (*Face) HorizontalAdvance

func (f *Face) HorizontalAdvance(gid GID) float32

func (*Face) LineMetric

func (f *Face) LineMetric(metric LineMetric) float32

LineMetric returns the metric identified by `metric` (in fonts units).

func (*Face) Ppem

func (f *Face) Ppem() (x, y uint16)

Ppem returns the horizontal and vertical pixels-per-em (ppem), used to select bitmap sizes.

func (*Face) SetCoords

func (f *Face) SetCoords(coords []tables.Coord)

SetCoords applies a list of variation coordinates, expressed in normalized units. Use [NormalizeVariations] to convert from design (user) space units.

func (*Face) SetPpem

func (f *Face) SetPpem(x, y uint16)

SetPpem applies horizontal and vertical pixels-per-em (ppem).

func (*Face) SetVariations

func (face *Face) SetVariations(variations []Variation)

SetVariations applies a list of font-variation settings to a font, defaulting to the values given in the `fvar` table. Note that passing an empty slice will instead remove the coordinates.

func (*Face) VerticalAdvance

func (f *Face) VerticalAdvance(gid GID) float32

type Feature

type Feature struct {
	tables.Feature
	Tag Tag
}

type Font

type Font struct {
	// Cmap is the 'cmap' table
	Cmap Cmap

	GDEF tables.GDEF // An absent table has a nil GlyphClassDef
	Trak tables.Trak
	Ankr tables.Ankr
	Feat tables.Feat
	Ltag tables.Ltag
	Morx Morx
	Kern Kernx
	Kerx Kernx
	GSUB GSUB // An absent table has a nil slice of lookups
	GPOS GPOS // An absent table has a nil slice of lookups
	// contains filtered or unexported fields
}

Font represents one Opentype font file (or one sub font of a collection). It is an educated view of the underlying font file, optimized for quick access to information required by text layout engines.

All its methods are read-only and a *Font object is thus safe for concurrent use.

func NewFont

func NewFont(ld *ot.Loader) (*Font, error)

NewFont loads all the font tables, sanitizing them. An error is returned only when required tables 'cmap', 'head', 'maxp' are invalid (or missing). More control on errors is available by using package tables.

func (*Font) BitmapSizes

func (font *Font) BitmapSizes() []BitmapSize

BitmapSizes returns the size of bitmap glyphs present in the font.

func (*Font) Describe

func (ft *Font) Describe() Description

Describe provides access to family and aspect.

See also the package level function Describe, which is more efficient if you only need the font metadata.

func (*Font) GetGlyphContourPoint

func (f *Font) GetGlyphContourPoint(glyph GID, pointIndex uint16) (x, y int32, ok bool)

func (*Font) GlyphHOrigin

func (f *Font) GlyphHOrigin(GID) (x, y int32, found bool)

func (*Font) GlyphName

func (f *Font) GlyphName(glyph GID) string

GlyphName returns the name of the given glyph, or an empty string if the glyph is invalid or has no name.

func (*Font) HasVerticalMetrics

func (f *Font) HasVerticalMetrics() bool

HasVerticalMetrics returns true if a the 'vmtx' table is present. If not, client should avoid calls to [VerticalAdvance], which will returns a defaut value.

func (*Font) IsMonospace

func (fd *Font) IsMonospace() bool

IsMonospace returns 'true' if the font is monospace, by inspecting the horizontal advances of its glyphs.

func (*Font) NominalGlyph

func (f *Font) NominalGlyph(ch rune) (GID, bool)

NominalGlyph returns the glyph used to represent the given rune, or false if not found. Note that it only looks into the cmap, without taking account substitutions nor variation selectors.

func (*Font) NormalizeVariations

func (f *Font) NormalizeVariations(coords []float32) []VarCoord

NormalizeVariations normalize the given design-space coordinates. The minimum and maximum values for the axis are mapped to the interval [-1,1], with the default axis value mapped to 0.

Any additional scaling defined in the face's `avar` table is also applied, as described at https://docs.microsoft.com/en-us/typography/opentype/spec/avar.

This method panics if `coords` has not the correct length, that is the number of axis inf 'fvar'.

func (*Font) Upem

func (f *Font) Upem() uint16

Upem returns the units per em of the font file. This value is only relevant for scalable fonts.

func (*Font) VariationGlyph

func (f *Font) VariationGlyph(ch, varSelector rune) (GID, bool)

VariationGlyph retrieves the glyph ID for a specified Unicode code point followed by a specified Variation Selector code point, or false if not found

type FontExtents

type FontExtents struct {
	Ascender  float32 // Typographic ascender.
	Descender float32 // Typographic descender.
	LineGap   float32 // Suggested line spacing gap.
}

FontExtents exposes font-wide extent values, measured in font units. Note that typically ascender is positive and descender negative in coordinate systems that grow up.

type FontID

type FontID struct {
	File string // The filename or identifier of the font file.

	// The index of the face in a collection. It is always 0 for
	// single font files.
	Index uint16

	// For variable fonts, stores 1 + the instance index.
	// It is set to 0 to ignore variations, or for non variable fonts.
	Instance uint16
}

FontID represents an identifier of a font (possibly in a collection), and an optional variable instance.

type GID

type GID = ot.GID

GID is used to identify glyphs in a font. It is mostly internal to the font and should not be confused with Unicode code points. Note that, despite Opentype font files using uint16, we choose to use uint32, to allow room for future extension.

const EmptyGlyph GID = math.MaxUint32

EmptyGlyph represents an invisible glyph, which should not be drawn, but whose advance and offsets should still be accounted for when rendering.

type GPOS

type GPOS struct {
	Layout
	Lookups []GPOSLookup
}

type GPOSLookup

type GPOSLookup struct {
	LookupOptions
	Subtables []tables.GPOSLookup
}

type GSUB

type GSUB struct {
	Layout
	Lookups []GSUBLookup
}

type GSUBLookup

type GSUBLookup struct {
	LookupOptions
	Subtables []tables.GSUBLookup
}

type GlyphBitmap

type GlyphBitmap struct {
	// The actual image content, whose interpretation depends
	// on the Format field.
	Data          []byte
	Format        BitmapFormat
	Width, Height int // number of columns and rows

	// Outline may be specified to be drawn with bitmap
	Outline *GlyphOutline
}

type GlyphData

type GlyphData interface {
	// contains filtered or unexported methods
}

GlyphData describe how to draw a glyph. It is either an GlyphOutline, GlyphSVG or GlyphBitmap.

type GlyphExtents

type GlyphExtents = ot.GlyphExtents

GlyphExtents exposes extent values, measured in font units. Note that height is negative in coordinate systems that grow up.

type GlyphOutline

type GlyphOutline struct {
	Segments []Segment
}

GlyphOutline exposes the path to draw for vector glyph. Coordinates are expressed in fonts units.

func (GlyphOutline) Sideways

func (o GlyphOutline) Sideways(yOffset float32)

Sideways updates the coordinates of the outline by applying a 90° clockwise rotation, and adding [yOffset] afterwards.

When used for vertical text, pass -Glyph.YOffset, converted in font units, as [yOffset] (a positive value to lift the glyph up).

type GlyphSVG

type GlyphSVG struct {
	// The SVG image content, decompressed if needed.
	// The actual glyph description is an SVG element
	// with id="glyph<GID>" (as in id="glyph12"),
	// and several glyphs may share the same Source
	Source []byte

	// According to the specification, a fallback outline
	// should be specified for each SVG glyphs
	Outline GlyphOutline
}

GlyphSVG is an SVG description for the glyph, as found in Opentype SVG table.

type Kern0

type Kern0 []tables.Kernx0Record

func (Kern0) KernPair

func (kd Kern0) KernPair(left, right GID) int16

type Kern1

type Kern1 struct {
	Values  []int16 // After successful parsing, may be safely indexed by AATStateEntry.AsKernxIndex() from `Machine`
	Machine AATStateTable
}

type Kern2

type Kern2 tables.KerxData2

func (Kern2) KernPair

func (kd Kern2) KernPair(left, right GID) int16

type Kern3

type Kern3 tables.KernData3

func (Kern3) KernPair

func (kd Kern3) KernPair(left, right GID) int16

type Kern4

type Kern4 struct {
	Anchors tables.KerxAnchors
	Machine AATStateTable
	// contains filtered or unexported fields
}

func (Kern4) ActionType

func (k Kern4) ActionType() uint8

ActionType returns 0, 1 or 2 .

type Kern6

type Kern6 tables.KerxData6

func (Kern6) KernPair

func (kd Kern6) KernPair(left, right GID) int16

type KernSubtable

type KernSubtable struct {
	Data interface {
		// contains filtered or unexported methods
	}

	// IsExtended [true] for AAT `kerx` subtables, false for 'kern' subtables
	IsExtended bool

	// 0 for scalar values
	TupleCount int
	// contains filtered or unexported fields
}

KernSubtable represents a 'kern' or 'kerx' subtable.

func (KernSubtable) IsBackwards

func (k KernSubtable) IsBackwards() bool

IsBackwards returns true if state-table based should process the glyphs backwards.

func (KernSubtable) IsCrossStream

func (k KernSubtable) IsCrossStream() bool

IsCrossStream returns true if the subtable has cross-stream kerning values.

func (KernSubtable) IsHorizontal

func (k KernSubtable) IsHorizontal() bool

IsHorizontal returns true if the subtable has horizontal kerning values.

func (KernSubtable) IsVariation

func (k KernSubtable) IsVariation() bool

IsVariation returns true if the subtable has variation kerning values.

type Kernx

type Kernx []KernSubtable

Kernx represents a 'kern' or 'kerx' kerning table. It supports both Microsoft and Apple formats.

type Layout

type Layout struct {
	Scripts           []Script
	Features          []Feature
	FeatureVariations []tables.FeatureVariationRecord
}

shared between GSUB and GPOS

func (*Layout) FindFeatureIndex

func (la *Layout) FindFeatureIndex(featureTag Tag) (uint16, bool)

FindFeatureIndex fetches the index for a given feature tag in the GSUB or GPOS table. Returns false if not found

func (*Layout) FindScript

func (la *Layout) FindScript(script Tag) int

FindScript looks for [script] and return its index into the Scripts slice, or -1 if the tag is not found.

func (*Layout) FindVariationIndex

func (la *Layout) FindVariationIndex(coords []VarCoord) int

FindVariationIndex returns the first feature variation matching the specified variation coordinates, as an index in the `FeatureVariations` field. It returns `-1` if not found.

type LineMetric

type LineMetric uint8

LineMetric identifies one metric about the font.

const (
	// Distance above the baseline of the top of the underline.
	// Since most fonts have underline positions beneath the baseline, this value is typically negative.
	UnderlinePosition LineMetric = iota

	// Suggested thickness to draw for the underline.
	UnderlineThickness

	// Distance above the baseline of the top of the strikethrough.
	StrikethroughPosition

	// Suggested thickness to draw for the strikethrough.
	StrikethroughThickness

	SuperscriptEmYSize
	SuperscriptEmXOffset

	SubscriptEmYSize
	SubscriptEmYOffset
	SubscriptEmXOffset

	CapHeight
	XHeight
)

type LookupOptions

type LookupOptions struct {
	// Lookup qualifiers.
	Flag uint16
	// Index (base 0) into GDEF mark glyph sets structure,
	// meaningfull only if UseMarkFilteringSet is set.
	MarkFilteringSet uint16
}

func (LookupOptions) Props

func (lo LookupOptions) Props() uint32

Props returns a 32-bit integer where the lower 16-bit is `Flag` and the higher 16-bit is `MarkFilteringSet` if the lookup uses one.

type Morx

type Morx []MorxChain

type MorxChain

type MorxChain struct {
	Features     []tables.AATFeature
	Subtables    []MorxSubtable
	DefaultFlags uint32
}

type MorxContextualSubtable

type MorxContextualSubtable struct {
	Substitutions []tables.AATLookup
	Machine       AATStateTable
}

type MorxInsertionSubtable

type MorxInsertionSubtable struct {
	// After successul parsing, this array may be safely
	// indexed by the indexes and counts from Machine entries.
	Insertions []GID
	Machine    AATStateTable
}

type MorxLigatureSubtable

type MorxLigatureSubtable struct {
	LigatureAction []uint32
	Components     []uint16
	Ligatures      []GID
	Machine        AATStateTable
}

type MorxNonContextualSubtable

type MorxNonContextualSubtable struct {
	Class tables.AATLookup // the lookup value is interpreted as a GlyphIndex
}

type MorxRearrangementSubtable

type MorxRearrangementSubtable AATStateTable

type MorxSubtable

type MorxSubtable struct {
	Data interface {
		// contains filtered or unexported methods
	}
	Coverage uint8  // high byte of the coverage flag
	Flags    uint32 // Mask identifying which subtable this is.
}

type Resource

type Resource = ot.Resource

Resource is a combination of io.Reader, io.Seeker and io.ReaderAt. This interface is satisfied by most things that you'd want to parse, for example *os.File, io.SectionReader or *bytes.Reader.

type Script

type Script struct {
	tables.Script
	Tag Tag
}

type Segment

type Segment = ot.Segment

type SegmentPoint

type SegmentPoint = ot.SegmentPoint

type SimpleKerns

type SimpleKerns interface {
	// KernPair return the kern value for the given pair, or zero.
	// The value is expressed in glyph units and
	// is negative when glyphs should be closer.
	KernPair(left, right GID) int16
}

SimpleKerns store a compact form of the kerning values, which is restricted to (one direction) kerning pairs. It is only implemented by Kern0, Kern2, Kern3 and Kern6, where Kern1 and Kern4 requires a state machine to be interpreted.

type Stretch

type Stretch float32

Stretch is the width of a font as an approximate fraction of the normal width. Widths range from 0.5 to 2.0 inclusive, with 1.0 as the normal width.

const (
	// Ultra-condensed width (50%), the narrowest possible.
	StretchUltraCondensed Stretch = 0.5
	// Extra-condensed width (62.5%).
	StretchExtraCondensed Stretch = 0.625
	// Condensed width (75%).
	StretchCondensed Stretch = 0.75
	// Semi-condensed width (87.5%).
	StretchSemiCondensed Stretch = 0.875
	// Normal width (100%).
	StretchNormal Stretch = 1.0
	// Semi-expanded width (112.5%).
	StretchSemiExpanded Stretch = 1.125
	// Expanded width (125%).
	StretchExpanded Stretch = 1.25
	// Extra-expanded width (150%).
	StretchExtraExpanded Stretch = 1.5
	// Ultra-expanded width (200%), the widest possible.
	StretchUltraExpanded Stretch = 2.0
)

type Style

type Style uint8

Style (also called slant) allows italic or oblique faces to be selected.

const (
	// A face that is neither italic not obliqued.
	StyleNormal Style = iota + 1
	// A form that is generally cursive in nature or slanted.
	// This groups what is usually called Italic or Oblique.
	StyleItalic
)

note that we use the 0 value to indicate no style has been found yet

type Tag

type Tag = ot.Tag

Tag represents an open-type name. These are technically uint32's, but are usually displayed in ASCII as they are all acronyms. See https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6.html#Overview

type UnicodeVariations

type UnicodeVariations []variationSelector

func (UnicodeVariations) GetGlyphVariant

func (t UnicodeVariations) GetGlyphVariant(r, selector rune) (GID, uint8)

GetGlyphVariant returns the glyph index to used to [r] combined with [selector], with one of the tri-state flags [VariantNotFound, VariantUseDefault, VariantFound]

type VarCoord

type VarCoord = tables.Coord

VarCoord stores font variation coordinates, which are real numbers in [-1;1], stored as fixed 2.14 integer.

type Variation

type Variation struct {
	Tag   Tag     // Variation-axis identifier tag
	Value float32 // In design units
}

Variation defines a value for a wanted variation axis.

type Weight

type Weight float32

Weight is the degree of blackness or stroke thickness of a font. This value ranges from 100.0 to 900.0, with 400.0 as normal.

const (
	// Thin weight (100), the thinnest value.
	WeightThin Weight = 100
	// Extra light weight (200).
	WeightExtraLight Weight = 200
	// Light weight (300).
	WeightLight Weight = 300
	// Normal (400).
	WeightNormal Weight = 400
	// Medium weight (500, higher than normal).
	WeightMedium Weight = 500
	// Semibold weight (600).
	WeightSemibold Weight = 600
	// Bold weight (700).
	WeightBold Weight = 700
	// Extra-bold weight (800).
	WeightExtraBold Weight = 800
	// Black weight (900), the thickest value.
	WeightBlack Weight = 900
)

Directories

Path Synopsis
cff
interpreter
Package psinterpreter implement a Postscript interpreter required to parse .CFF files, and Type1 and Type2 Charstrings.
Package psinterpreter implement a Postscript interpreter required to parse .CFF files, and Type1 and Type2 Charstrings.
Package opentype provides the low level routines required to read and write Opentype font files, including collections.
Package opentype provides the low level routines required to read and write Opentype font files, including collections.

Jump to

Keyboard shortcuts

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