ot

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package ot provides OpenType font table parsing.

Package ot provides OpenType font table parsing.

Index

Constants

View Source
const (
	FontPageNone       uint16 = 0
	FontPageHebrew     uint16 = 0xB100 // Hebrew Windows 3.1 font page
	FontPageSimpArabic uint16 = 0xB200 // Simplified Arabic Windows 3.1 font page
	FontPageTradArabic uint16 = 0xB300 // Traditional Arabic Windows 3.1 font page
	FontPageOEMArabic  uint16 = 0xB400 // OEM Arabic Windows 3.1 font page
	FontPageSimpFarsi  uint16 = 0xBA00 // Simplified Farsi Windows 3.1 font page
	FontPageTradFarsi  uint16 = 0xBB00 // Traditional Farsi Windows 3.1 font page
	FontPageThai       uint16 = 0xDE00 // Thai Windows 3.1 font page
)

Font page types from OS/2 table fsSelection field (version 0 only) Source: HarfBuzz hb-ot-os2-table.hh:333-342

View Source
const (
	// FeatureGlobalStart indicates feature applies from buffer start.
	FeatureGlobalStart uint = 0
	// FeatureGlobalEnd indicates feature applies to buffer end.
	FeatureGlobalEnd uint = ^uint(0)
)
View Source
const (
	// MaskGlobal is set on all glyphs. Features like ccmp, rlig, calt, liga use this.
	// HarfBuzz: global_mask = 1 << 31 (highest bit, so lower bits can be used for features)
	MaskGlobal uint32 = 1 << 31

	// Arabic positional feature masks
	// HarfBuzz: arabic_features[] in hb-ot-shaper-arabic.cc maps actions to features
	MaskIsol uint32 = 1 << 1 // Isolated form
	MaskFina uint32 = 1 << 2 // Final form
	MaskFin2 uint32 = 1 << 3 // Terminal form (Syriac)
	MaskFin3 uint32 = 1 << 4 // Terminal form (Syriac)
	MaskMedi uint32 = 1 << 5 // Medial form
	MaskMed2 uint32 = 1 << 6 // Medial form (Syriac)
	MaskInit uint32 = 1 << 7 // Initial form

	// Combined mask for all Arabic positional features
	MaskArabicPositional = MaskIsol | MaskFina | MaskFin2 | MaskFin3 | MaskMedi | MaskMed2 | MaskInit

	// USE shaper feature masks
	// HarfBuzz: use_plan->rphf_mask = plan->map.get_1_mask(HB_TAG('r','p','h','f'))
	MaskRphf uint32 = 1 << 8 // Repha feature (USE shaper)

)

Mask constants for feature filtering

View Source
const (
	GlyphClassUnclassified = 0 // Unclassified glyph
	GlyphClassBase         = 1 // Base glyph (single character, spacing glyph)
	GlyphClassLigature     = 2 // Ligature glyph (multiple characters, spacing glyph)
	GlyphClassMark         = 3 // Mark glyph (non-spacing combining glyph)
	GlyphClassComponent    = 4 // Component glyph (part of a ligature)
)

GlyphClass constants for GDEF glyph classification.

View Source
const (
	GPOSTypeSingle       = 1
	GPOSTypePair         = 2
	GPOSTypeCursive      = 3
	GPOSTypeMarkBase     = 4
	GPOSTypeMarkLig      = 5
	GPOSTypeMarkMark     = 6
	GPOSTypeContext      = 7
	GPOSTypeChainContext = 8
	GPOSTypeExtension    = 9
)

GPOS lookup types

View Source
const (
	ValueFormatXPlacement = 0x0001 // Horizontal adjustment for placement
	ValueFormatYPlacement = 0x0002 // Vertical adjustment for placement
	ValueFormatXAdvance   = 0x0004 // Horizontal adjustment for advance
	ValueFormatYAdvance   = 0x0008 // Vertical adjustment for advance
	ValueFormatXPlaDevice = 0x0010 // Device table for horizontal placement
	ValueFormatYPlaDevice = 0x0020 // Device table for vertical placement
	ValueFormatXAdvDevice = 0x0040 // Device table for horizontal advance
	ValueFormatYAdvDevice = 0x0080 // Device table for vertical advance
)

ValueFormat flags - determine which values are present in a ValueRecord

View Source
const (
	// LookupFlagRightToLeft indicates right-to-left cursive attachment.
	LookupFlagRightToLeft = 0x0001
	// LookupFlagIgnoreBaseGlyphs causes base glyphs to be skipped.
	LookupFlagIgnoreBaseGlyphs = 0x0002
	// LookupFlagIgnoreLigatures causes ligature glyphs to be skipped.
	LookupFlagIgnoreLigatures = 0x0004
	// LookupFlagIgnoreMarks causes mark glyphs to be skipped.
	LookupFlagIgnoreMarks = 0x0008
	// LookupFlagUseMarkFilteringSet indicates that MarkFilteringSet is used.
	LookupFlagUseMarkFilteringSet = 0x0010
	// LookupFlagMarkAttachTypeMask is the mask for mark attachment type filtering.
	LookupFlagMarkAttachTypeMask = 0xFF00
)

LookupFlag bit constants for GSUB/GPOS lookups.

View Source
const (
	AttachTypeNone    = 0
	AttachTypeMark    = 1
	AttachTypeCursive = 2
)

AttachType constants for glyph attachment

View Source
const (
	GSUBTypeSingle             = 1
	GSUBTypeMultiple           = 2
	GSUBTypeAlternate          = 3
	GSUBTypeLigature           = 4
	GSUBTypeContext            = 5
	GSUBTypeChainContext       = 6
	GSUBTypeExtension          = 7
	GSUBTypeReverseChainSingle = 8
)

GSUB lookup types

View Source
const (
	GlyphPropsBaseGlyph        uint16 = 0x02 // GDEF class 1: Base glyph
	GlyphPropsLigature         uint16 = 0x04 // GDEF class 2: Ligature glyph
	GlyphPropsMark             uint16 = 0x08 // GDEF class 3: Mark glyph
	GlyphPropsSubstituted      uint16 = 0x10 // Glyph was substituted by GSUB
	GlyphPropsLigated          uint16 = 0x20 // Glyph is result of ligature substitution
	GlyphPropsMultiplied       uint16 = 0x40 // Glyph is component of multiple substitution
	GlyphPropsDefaultIgnorable uint16 = 0x80 // Unicode default ignorable character
	// HarfBuzz UPROPS_MASK_Cf_ZWNJ and UPROPS_MASK_Cf_ZWJ in hb-ot-layout.hh
	GlyphPropsZWNJ uint16 = 0x100 // Zero-Width Non-Joiner (U+200C)
	GlyphPropsZWJ  uint16 = 0x200 // Zero-Width Joiner (U+200D)
	// HarfBuzz UPROPS_MASK_HIDDEN in hb-ot-layout.hh:199
	// Set for: CGJ (U+034F), Mongolian FVS (U+180B-U+180D, U+180F), TAG chars (U+E0020-U+E007F)
	// These should NOT be skipped during GSUB context matching (ignore_hidden=false for GSUB)
	GlyphPropsHidden uint16 = 0x400

	// GlyphPropsPreserve are the flags preserved across substitutions
	GlyphPropsPreserve uint16 = GlyphPropsSubstituted | GlyphPropsLigated | GlyphPropsMultiplied | GlyphPropsDefaultIgnorable | GlyphPropsZWNJ | GlyphPropsZWJ | GlyphPropsHidden
)

Glyph property constants. HarfBuzz equivalent: HB_OT_LAYOUT_GLYPH_PROPS_* in hb-ot-layout.hh

View Source
const (
	GC_Cc uint8 = iota // Control
	GC_Cf              // Format
	GC_Cn              // Unassigned
	GC_Co              // Private Use
	GC_Cs              // Surrogate
	GC_Ll              // Lowercase Letter
	GC_Lm              // Modifier Letter
	GC_Lo              // Other Letter
	GC_Lt              // Titlecase Letter
	GC_Lu              // Uppercase Letter
	GC_Mc              // Spacing Mark
	GC_Me              // Enclosing Mark
	GC_Mn              // Nonspacing Mark
	GC_Nd              // Decimal Number
	GC_Nl              // Letter Number
	GC_No              // Other Number
	GC_Pc              // Connector Punctuation
	GC_Pd              // Dash Punctuation
	GC_Pe              // Close Punctuation
	GC_Pf              // Final Punctuation
	GC_Pi              // Initial Punctuation
	GC_Po              // Other Punctuation
	GC_Ps              // Open Punctuation
	GC_Sc              // Currency Symbol
	GC_Sk              // Modifier Symbol
	GC_Sm              // Math Symbol
	GC_So              // Other Symbol
	GC_Zl              // Line Separator
	GC_Zp              // Paragraph Separator
	GC_Zs              // Space Separator
)

General Category values matching HarfBuzz order. HarfBuzz equivalent: hb_unicode_general_category_t

View Source
const HBMaxNestingLevel = 64

HBMaxNestingLevel is the maximum nesting level for recursive lookups. HarfBuzz: HB_MAX_NESTING_LEVEL = 64

View Source
const MaxCombiningMarks = 32

MaxCombiningMarks is the maximum number of combining marks to reorder. HarfBuzz equivalent: HB_OT_SHAPE_MAX_COMBINING_MARKS (default 32)

View Source
const MaxNestingLevel = 64

GSUBContext provides context for GSUB application. MaxNestingLevel is the maximum recursion depth for nested lookups. HarfBuzz equivalent: HB_MAX_NESTING_LEVEL

View Source
const NotCovered = ^uint32(0)

NotCovered is returned when a glyph is not in a coverage table.

View Source
const VariationsNotFoundIndex = 0xFFFFFFFF

VariationsNotFoundIndex indicates no matching FeatureVariations record was found. HarfBuzz: HB_OT_LAYOUT_NO_VARIATIONS_INDEX

Variables

View Source
var (
	TagAxisWeight      = MakeTag('w', 'g', 'h', 't') // Weight axis
	TagAxisWidth       = MakeTag('w', 'd', 't', 'h') // Width axis
	TagAxisSlant       = MakeTag('s', 'l', 'n', 't') // Slant axis
	TagAxisItalic      = MakeTag('i', 't', 'a', 'l') // Italic axis
	TagAxisOpticalSize = MakeTag('o', 'p', 's', 'z') // Optical size axis
)

Variable font axis tags (registered axes)

View Source
var (
	TagKern = MakeTag('k', 'e', 'r', 'n') // Kerning
	TagCurs = MakeTag('c', 'u', 'r', 's') // Cursive Positioning
	TagMark = MakeTag('m', 'a', 'r', 'k') // Mark Positioning
	TagMkmk = MakeTag('m', 'k', 'm', 'k') // Mark-to-Mark Positioning
	TagAbvm = MakeTag('a', 'b', 'v', 'm') // Above-base Mark Positioning
	TagBlwm = MakeTag('b', 'l', 'w', 'm') // Below-base Mark Positioning
	TagDist = MakeTag('d', 'i', 's', 't') // Distances
)

Common GPOS feature tags

View Source
var (
	TagLiga = MakeTag('l', 'i', 'g', 'a') // Standard Ligatures
	TagClig = MakeTag('c', 'l', 'i', 'g') // Contextual Ligatures
	TagDlig = MakeTag('d', 'l', 'i', 'g') // Discretionary Ligatures
	TagHlig = MakeTag('h', 'l', 'i', 'g') // Historical Ligatures
	TagCcmp = MakeTag('c', 'c', 'm', 'p') // Glyph Composition/Decomposition
	TagLocl = MakeTag('l', 'o', 'c', 'l') // Localized Forms
	TagRlig = MakeTag('r', 'l', 'i', 'g') // Required Ligatures
	TagSmcp = MakeTag('s', 'm', 'c', 'p') // Small Capitals
	TagCalt = MakeTag('c', 'a', 'l', 't') // Contextual Alternates
)

Common feature tags

View Source
var (
	TagMlym = MakeTag('M', 'l', 'y', 'm') // Malayalam
	TagTaml = MakeTag('T', 'a', 'm', 'l') // Tamil
)

Script tags for Indic scripts HarfBuzz equivalent: HB_SCRIPT_MALAYALAM, HB_SCRIPT_TAMIL, etc.

View Source
var (
	ErrInvalidFont    = errors.New("invalid font data")
	ErrTableNotFound  = errors.New("table not found")
	ErrInvalidTable   = errors.New("invalid table data")
	ErrInvalidOffset  = errors.New("offset out of bounds")
	ErrInvalidFormat  = errors.New("unsupported format")
	ErrInvalidFeature = errors.New("invalid feature string")
)

Common errors

View Source
var (
	TagCmap = MakeTag('c', 'm', 'a', 'p')
	TagHead = MakeTag('h', 'e', 'a', 'd')
	TagHhea = MakeTag('h', 'h', 'e', 'a')
	TagHmtx = MakeTag('h', 'm', 't', 'x')
	TagMaxp = MakeTag('m', 'a', 'x', 'p')
	TagName = MakeTag('n', 'a', 'm', 'e')
	TagOS2  = MakeTag('O', 'S', '/', '2')
	TagPost = MakeTag('p', 'o', 's', 't')
	TagGlyf = MakeTag('g', 'l', 'y', 'f')
	TagLoca = MakeTag('l', 'o', 'c', 'a')
	TagGDEF = MakeTag('G', 'D', 'E', 'F')
	TagGSUB = MakeTag('G', 'S', 'U', 'B')
	TagGPOS = MakeTag('G', 'P', 'O', 'S')
	TagCvt  = MakeTag('c', 'v', 't', ' ')
	TagFpgm = MakeTag('f', 'p', 'g', 'm')
	TagPrep = MakeTag('p', 'r', 'e', 'p')
	TagGasp = MakeTag('g', 'a', 's', 'p')
	TagVhea = MakeTag('v', 'h', 'e', 'a')
	TagVmtx = MakeTag('v', 'm', 't', 'x')
	TagVORG = MakeTag('V', 'O', 'R', 'G')
)

Common OpenType tags

View Source
var ArabicShaper = &OTShaper{
	Name:                    "arabic",
	NormalizationPreference: NormalizationModeAuto,
	ZeroWidthMarks:          ZeroWidthMarksByGDEFLate,
	FallbackPosition:        true,
}

ArabicShaper handles Arabic and related scripts. HarfBuzz equivalent: _hb_ot_shaper_arabic in hb-ot-shaper-arabic.cc:752-768

View Source
var BCP47ToOpenType = map[string][]Tag{}/* 1029 elements not displayed */

BCP47ToOpenType maps BCP 47 language tags to OpenType language system tags. HarfBuzz equivalent: ot_languages2[] and ot_languages3[] in hb-ot-tag-table.hh

View Source
var DefaultShaper = &OTShaper{
	Name:                    "default",
	NormalizationPreference: NormalizationModeAuto,
	ZeroWidthMarks:          ZeroWidthMarksByGDEFLate,
	FallbackPosition:        true,
}

DefaultShaper is the default shaper for scripts without special handling. HarfBuzz equivalent: _hb_ot_shaper_default in hb-ot-shaper-default.cc:34-50

View Source
var HangulShaper = &OTShaper{
	Name:                    "hangul",
	NormalizationPreference: NormalizationModeNone,
	ZeroWidthMarks:          ZeroWidthMarksNone,
	FallbackPosition:        true,
}

HangulShaper handles Hangul script. HarfBuzz equivalent: _hb_ot_shaper_hangul

View Source
var HebrewShaper = &OTShaper{
	Name:                    "hebrew",
	NormalizationPreference: NormalizationModeAuto,
	ZeroWidthMarks:          ZeroWidthMarksByGDEFLate,
	FallbackPosition:        true,
}

HebrewShaper handles Hebrew script. HarfBuzz equivalent: _hb_ot_shaper_hebrew

View Source
var IndicShaper = &OTShaper{
	Name:                    "indic",
	NormalizationPreference: NormalizationModeComposedDiacritics,
	ZeroWidthMarks:          ZeroWidthMarksNone,
	FallbackPosition:        false,
}

IndicShaper handles Indic scripts. HarfBuzz equivalent: _hb_ot_shaper_indic

View Source
var KhmerShaper = &OTShaper{
	Name:                    "khmer",
	NormalizationPreference: NormalizationModeComposedDiacritics,
	ZeroWidthMarks:          ZeroWidthMarksNone,
	FallbackPosition:        false,
}

KhmerShaper handles Khmer script. HarfBuzz equivalent: _hb_ot_shaper_khmer

View Source
var MyanmarShaper = &OTShaper{
	Name:                    "myanmar",
	NormalizationPreference: NormalizationModeComposedDiacritics,
	ZeroWidthMarks:          ZeroWidthMarksByGDEFEarly,
	FallbackPosition:        false,
}

MyanmarShaper handles Myanmar script. HarfBuzz equivalent: _hb_ot_shaper_myanmar (hb-ot-shaper-myanmar.cc:361)

View Source
var OpenTypeToBCP47 = map[Tag]string{}/* 668 elements not displayed */

OpenTypeToBCP47 maps OpenType language system tags to BCP 47 language tags. HarfBuzz equivalent: hb_ot_ambiguous_tag_to_language() in hb-ot-tag-table.hh

View Source
var QaagShaper = &OTShaper{
	Name:                    "qaag",
	NormalizationPreference: NormalizationModeNone,
	ZeroWidthMarks:          ZeroWidthMarksNone,
	FallbackPosition:        false,
}

QaagShaper is the shaper for Zawgyi (Myanmar visual encoding). HarfBuzz equivalent: _hb_ot_shaper_myanmar_zawgyi in hb-ot-shaper-myanmar.cc:363-378

Zawgyi is a legacy encoding for Myanmar that uses visual ordering. Characters are already in display order, so no reordering is needed. All callbacks are nil (use default behavior), but with: - NormalizationModeNone: No normalization - ZeroWidthMarksNone: Don't zero mark advances - FallbackPosition: false: No fallback positioning

View Source
var TagAvar = MakeTag('a', 'v', 'a', 'r')

TagAvar is the table tag for the axis variations table.

View Source
var TagCFF = MakeTag('C', 'F', 'F', ' ')

TagCFF is the table tag for CFF data.

View Source
var TagCvar = MakeTag('c', 'v', 'a', 'r')

TagCvar is the table tag for the CVT variations table.

View Source
var TagFvar = MakeTag('f', 'v', 'a', 'r')

TagFvar is the table tag for the font variations table.

View Source
var TagGvar = MakeTag('g', 'v', 'a', 'r')

TagGvar is the table tag for the glyph variations table.

View Source
var TagHvar = MakeTag('H', 'V', 'A', 'R')

TagHvar is the table tag for the horizontal metrics variations table.

View Source
var TagKernTable = MakeTag('k', 'e', 'r', 'n')

TagKernTable is the tag for the kern table.

View Source
var TagMvar = MakeTag('M', 'V', 'A', 'R')

TagMvar is the table tag for the metrics variations table.

View Source
var TagSTAT = MakeTag('S', 'T', 'A', 'T')

TagSTAT is the table tag for the style attributes table.

View Source
var TagVvar = MakeTag('V', 'V', 'A', 'R')

TagVvar is the table tag for the vertical metrics variations table.

View Source
var ThaiShaper = &OTShaper{
	Name:                    "thai",
	NormalizationPreference: NormalizationModeAuto,
	ZeroWidthMarks:          ZeroWidthMarksByGDEFLate,
	FallbackPosition:        true,
}

ThaiShaper handles Thai and Lao scripts. HarfBuzz equivalent: _hb_ot_shaper_thai

View Source
var USEShaper = &OTShaper{
	Name:                    "use",
	NormalizationPreference: NormalizationModeComposedDiacritics,
	ZeroWidthMarks:          ZeroWidthMarksByGDEFEarly,
	FallbackPosition:        false,
}

USEShaper handles USE (Universal Shaping Engine) scripts. HarfBuzz equivalent: _hb_ot_shaper_use

View Source
var VowelConstraints = map[string][]VowelConstraint{
	"Devanagari": {
		{Codepoints: []Codepoint{0x0905, 0x0946}},
		{Codepoints: []Codepoint{0x0905, 0x093E}},
		{Codepoints: []Codepoint{0x0930, 0x094D, 0x0907}},
		{Codepoints: []Codepoint{0x0909, 0x0941}},
		{Codepoints: []Codepoint{0x090F, 0x0945}},
		{Codepoints: []Codepoint{0x090F, 0x0946}},
		{Codepoints: []Codepoint{0x090F, 0x0947}},
		{Codepoints: []Codepoint{0x0905, 0x0949}},
		{Codepoints: []Codepoint{0x0906, 0x0945}},
		{Codepoints: []Codepoint{0x0905, 0x094A}},
		{Codepoints: []Codepoint{0x0906, 0x0946}},
		{Codepoints: []Codepoint{0x0905, 0x094B}},
		{Codepoints: []Codepoint{0x0906, 0x0947}},
		{Codepoints: []Codepoint{0x0905, 0x094C}},
		{Codepoints: []Codepoint{0x0906, 0x0948}},
		{Codepoints: []Codepoint{0x0905, 0x0945}},
		{Codepoints: []Codepoint{0x0905, 0x093A}},
		{Codepoints: []Codepoint{0x0905, 0x093B}},
		{Codepoints: []Codepoint{0x0906, 0x093A}},
		{Codepoints: []Codepoint{0x0905, 0x094F}},
		{Codepoints: []Codepoint{0x0905, 0x0956}},
		{Codepoints: []Codepoint{0x0905, 0x0957}},
	},
	"Bengali": {
		{Codepoints: []Codepoint{0x0985, 0x09BE}},
		{Codepoints: []Codepoint{0x098B, 0x09C3}},
		{Codepoints: []Codepoint{0x098C, 0x09E2}},
	},
	"Gurmukhi": {
		{Codepoints: []Codepoint{0x0A05, 0x0A3E}},
		{Codepoints: []Codepoint{0x0A72, 0x0A3F}},
		{Codepoints: []Codepoint{0x0A72, 0x0A40}},
		{Codepoints: []Codepoint{0x0A73, 0x0A41}},
		{Codepoints: []Codepoint{0x0A73, 0x0A42}},
		{Codepoints: []Codepoint{0x0A72, 0x0A47}},
		{Codepoints: []Codepoint{0x0A05, 0x0A48}},
		{Codepoints: []Codepoint{0x0A73, 0x0A4B}},
		{Codepoints: []Codepoint{0x0A05, 0x0A4C}},
	},
	"Gujarati": {
		{Codepoints: []Codepoint{0x0A85, 0x0ABE}},
		{Codepoints: []Codepoint{0x0A85, 0x0AC5}},
		{Codepoints: []Codepoint{0x0A85, 0x0AC7}},
		{Codepoints: []Codepoint{0x0A85, 0x0AC8}},
		{Codepoints: []Codepoint{0x0A85, 0x0AC9}},
		{Codepoints: []Codepoint{0x0A85, 0x0ACB}},
		{Codepoints: []Codepoint{0x0A85, 0x0ABE, 0x0AC5}},
		{Codepoints: []Codepoint{0x0A85, 0x0ACC}},
		{Codepoints: []Codepoint{0x0A85, 0x0ABE, 0x0AC8}},
		{Codepoints: []Codepoint{0x0AC5, 0x0ABE}},
	},
	"Oriya": {
		{Codepoints: []Codepoint{0x0B05, 0x0B3E}},
		{Codepoints: []Codepoint{0x0B0F, 0x0B57}},
		{Codepoints: []Codepoint{0x0B13, 0x0B57}},
	},
	"Tamil": {
		{Codepoints: []Codepoint{0x0B85, 0x0BC2}},
	},
	"Telugu": {
		{Codepoints: []Codepoint{0x0C12, 0x0C55}},
		{Codepoints: []Codepoint{0x0C12, 0x0C4C}},
		{Codepoints: []Codepoint{0x0C3F, 0x0C55}},
		{Codepoints: []Codepoint{0x0C46, 0x0C55}},
		{Codepoints: []Codepoint{0x0C4A, 0x0C55}},
	},
	"Kannada": {
		{Codepoints: []Codepoint{0x0C89, 0x0CBE}},
		{Codepoints: []Codepoint{0x0C92, 0x0CCC}},
		{Codepoints: []Codepoint{0x0C8B, 0x0CBE}},
	},
	"Malayalam": {
		{Codepoints: []Codepoint{0x0D07, 0x0D57}},
		{Codepoints: []Codepoint{0x0D09, 0x0D57}},
		{Codepoints: []Codepoint{0x0D0E, 0x0D46}},
		{Codepoints: []Codepoint{0x0D12, 0x0D3E}},
		{Codepoints: []Codepoint{0x0D12, 0x0D57}},
	},
	"Sinhala": {
		{Codepoints: []Codepoint{0x0D85, 0x0DCF}},
		{Codepoints: []Codepoint{0x0D85, 0x0DD0}},
		{Codepoints: []Codepoint{0x0D85, 0x0DD1}},
		{Codepoints: []Codepoint{0x0D8B, 0x0DDF}},
		{Codepoints: []Codepoint{0x0D8D, 0x0DD8}},
		{Codepoints: []Codepoint{0x0D8F, 0x0DDF}},
		{Codepoints: []Codepoint{0x0D91, 0x0DCA}},
		{Codepoints: []Codepoint{0x0D91, 0x0DD9}},
		{Codepoints: []Codepoint{0x0D91, 0x0DDA}},
		{Codepoints: []Codepoint{0x0D91, 0x0DDC}},
		{Codepoints: []Codepoint{0x0D91, 0x0DDD}},
		{Codepoints: []Codepoint{0x0D91, 0x0DDE}},
		{Codepoints: []Codepoint{0x0D94, 0x0DDF}},
	},
	"Brahmi": {
		{Codepoints: []Codepoint{0x11005, 0x11038}},
		{Codepoints: []Codepoint{0x1100B, 0x1103E}},
		{Codepoints: []Codepoint{0x1100F, 0x11042}},
	},
	"Khojki": {
		{Codepoints: []Codepoint{0x11200, 0x1122C}},
		{Codepoints: []Codepoint{0x11240, 0x1122E}},
		{Codepoints: []Codepoint{0x11206, 0x1122C}},
		{Codepoints: []Codepoint{0x11200, 0x11231}},
		{Codepoints: []Codepoint{0x11200, 0x11233}},
		{Codepoints: []Codepoint{0x11200, 0x1122C, 0x11231}},
		{Codepoints: []Codepoint{0x1122C, 0x11230}},
		{Codepoints: []Codepoint{0x1122C, 0x11231}},
	},
	"Khudawadi": {
		{Codepoints: []Codepoint{0x112B0, 0x112E0}},
		{Codepoints: []Codepoint{0x112B0, 0x112E5}},
		{Codepoints: []Codepoint{0x112B0, 0x112E6}},
		{Codepoints: []Codepoint{0x112B0, 0x112E7}},
		{Codepoints: []Codepoint{0x112B0, 0x112E8}},
	},
	"Tirhuta": {
		{Codepoints: []Codepoint{0x11481, 0x114B0}},
		{Codepoints: []Codepoint{0x114AA, 0x114B5}},
		{Codepoints: []Codepoint{0x114AA, 0x114B6}},
		{Codepoints: []Codepoint{0x1148B, 0x114BA}},
		{Codepoints: []Codepoint{0x1148D, 0x114BA}},
	},
	"Modi": {
		{Codepoints: []Codepoint{0x11600, 0x11639}},
		{Codepoints: []Codepoint{0x11600, 0x1163A}},
		{Codepoints: []Codepoint{0x11601, 0x11639}},
		{Codepoints: []Codepoint{0x11601, 0x1163A}},
	},
	"Takri": {
		{Codepoints: []Codepoint{0x11680, 0x116AD}},
		{Codepoints: []Codepoint{0x11686, 0x116B2}},
		{Codepoints: []Codepoint{0x11680, 0x116B4}},
		{Codepoints: []Codepoint{0x11680, 0x116B5}},
	},
}

VowelConstraints maps script names to their prohibited vowel sequences. HarfBuzz equivalent: _hb_preprocess_text_vowel_constraints()

Functions

func BuildLoca

func BuildLoca(offsets []uint32, useShort bool) []byte

BuildLoca builds a loca table from glyph offsets. If useShort is true, uses 16-bit format (offsets must be even and < 131072).

func CheckVowelConstraints added in v0.0.4

func CheckVowelConstraints(codepoints []Codepoint, pos int, script Tag) int

CheckVowelConstraints checks if a sequence starting at the given position matches any prohibited vowel sequence for the script. Returns the length of the matched constraint (0 if no match). HarfBuzz equivalent: pattern matching in _hb_preprocess_text_vowel_constraints()

func ClearShaperCache

func ClearShaperCache()

ClearShaperCache clears the internal shaper cache. Call this if fonts are being released to allow garbage collection.

func FindSyllablesIndic added in v0.0.4

func FindSyllablesIndic(info []IndicInfo) (hasBroken bool)

FindSyllablesIndic finds Indic syllable boundaries in the buffer. It sets info[i].Syllable to (serial << 4 | type) for each glyph. HarfBuzz equivalent: find_syllables_indic() in hb-ot-shaper-indic-machine.hh

func FindSyllablesKhmer added in v0.0.4

func FindSyllablesKhmer(buf *Buffer, categories []KhmerCategory) (hasBroken bool)

FindSyllablesKhmer finds Khmer syllable boundaries in the buffer. It sets the syllable field in Info[i].Mask to (serial << 4 | type) for each glyph. HarfBuzz equivalent: find_syllables_khmer() in hb-ot-shaper-khmer-machine.hh

func FindSyllablesMyanmar added in v0.0.4

func FindSyllablesMyanmar(buf *Buffer, categories []MyanmarCategory) (hasBroken bool)

FindSyllablesMyanmar finds Myanmar syllable boundaries in the buffer. It sets the syllable field in Info[i].Syllable to (serial << 4 | type) for each glyph. HarfBuzz equivalent: find_syllables_myanmar() in hb-ot-shaper-myanmar-machine.hh

func FindSyllablesUSE added in v0.0.4

func FindSyllablesUSE(syllables []USESyllableInfo) (hasBroken bool)

FindSyllablesUSE finds USE syllable boundaries in the buffer. It sets syllables[i].Syllable to (serial << 4 | type) for each glyph. HarfBuzz equivalent: find_syllables_use() in hb-ot-shaper-use-machine.hh

func GetGlyphName

func GetGlyphName(glyph GlyphID) string

GetGlyphName returns a debug name for a glyph (just the ID as string).

func GetIndicCategories added in v0.0.4

func GetIndicCategories(u Codepoint) (IndicCategory, IndicPosition)

GetIndicCategories returns the category and position for a Unicode codepoint. HarfBuzz equivalent: hb_indic_get_categories()

func InstanceSimpleGlyph added in v0.0.3

func InstanceSimpleGlyph(data []byte, xDeltas, yDeltas []int16) []byte

InstanceSimpleGlyph creates a new glyph with deltas applied to points.

func IsDefaultIgnorable added in v0.0.4

func IsDefaultIgnorable(cp Codepoint) bool

IsDefaultIgnorable returns true if the codepoint is a Unicode Default Ignorable. Based on HarfBuzz hb-unicode.hh is_default_ignorable().

func IsIndicConsonant added in v0.0.4

func IsIndicConsonant(cat IndicCategory) bool

IsIndicConsonant returns true if the category is a consonant type. HarfBuzz: is_consonant() using CONSONANT_FLAGS_INDIC

func IsIndicHalant added in v0.0.4

func IsIndicHalant(cat IndicCategory) bool

IsIndicHalant returns true if the category is Halant.

func IsIndicJoiner added in v0.0.4

func IsIndicJoiner(cat IndicCategory) bool

IsIndicJoiner returns true if the category is ZWJ or ZWNJ.

func IsPositionalFeature added in v0.0.4

func IsPositionalFeature(tag Tag) bool

IsPositionalFeature returns true if the tag is an Arabic positional feature.

func IsScriptCommon added in v0.0.4

func IsScriptCommon(cp Codepoint) bool

IsScriptCommon returns true if the codepoint is in Common or Inherited script. These codepoints don't determine the script of a text run. HarfBuzz: checks for HB_SCRIPT_COMMON and HB_SCRIPT_INHERITED

func IsUnicodeMark added in v0.0.4

func IsUnicodeMark(cp Codepoint) bool

IsUnicodeMark returns true if the codepoint is a Unicode mark (Mn, Mc, or Me). HarfBuzz equivalent: _hb_glyph_info_is_unicode_mark() in hb-ot-layout.hh:272

func IsVariationSelector added in v0.0.4

func IsVariationSelector(cp Codepoint) bool

IsVariationSelector returns true if the codepoint is a Variation Selector. Includes: U+180B-U+180D, U+180F (Mongolian FVS), U+FE00-U+FE0F (VS1-VS16), and U+E0100-U+E01EF (VS17-VS256).

func NeedsVowelConstraintProcessing added in v0.0.4

func NeedsVowelConstraintProcessing(script Tag) bool

NeedsVowelConstraintProcessing returns true if the script has vowel constraints.

func PreprocessVowelConstraints added in v0.0.4

func PreprocessVowelConstraints(buf *Buffer)

PreprocessVowelConstraints inserts dotted circles between invalid vowel sequences. HarfBuzz equivalent: _hb_preprocess_text_vowel_constraints() in hb-ot-shaper-vowel-constraints.cc

This function scans the buffer for script-specific prohibited vowel sequences and inserts a dotted circle (U+25CC) to break them up. This prevents text from looking like a different vowel than intended.

Uses HarfBuzz's output buffer pattern: clear_output(), next_glyph(), output_glyph(), sync()

func PropagateAttachmentOffsets added in v0.0.4

func PropagateAttachmentOffsets(positions []GlyphPos, direction Direction)

PropagateAttachmentOffsets propagates positioning offsets along the attachment chain. This must be called after all GPOS lookups have been applied. It handles both mark attachments (marks inherit base offsets) and cursive attachments (cursive children inherit parent's cross-direction offset).

func RemapCharString

func RemapCharString(cs []byte, globalMap, localMap map[int]int,
	oldGlobalBias, oldLocalBias, newGlobalBias, newLocalBias int) []byte

RemapCharString rewrites a CharString with remapped subroutine numbers. This is the HarfBuzz-style implementation using two phases: 1. Parse the CharString completely, storing pointers to original bytes 2. Serialize: copy original bytes for everything except subroutine calls

Key insight from HarfBuzz (hb-subset-cff-common.hh): - Original bytes are preserved for operands (including fixed-point numbers) - Only subroutine numbers need to be re-encoded with new biased values

func RemapComposite

func RemapComposite(data []byte, glyphMap map[GlyphID]GlyphID) []byte

RemapComposite creates a new composite glyph with remapped component IDs.

func Shape

func Shape(font *Font, buf *Buffer, features []Feature) error

Shape is a convenience function that shapes text in a buffer using a font. It caches shapers internally for efficiency. This is similar to HarfBuzz's hb_shape() function.

func TagToLanguage added in v0.0.4

func TagToLanguage(tag Tag) string

TagToLanguage converts an OpenType language system tag to a BCP 47 language tag. Returns empty string if no mapping exists. HarfBuzz equivalent: hb_ot_tag_to_language() in hb-ot-tag.cc

Types

type AlternateSubst

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

AlternateSubst represents an Alternate Substitution subtable (1 -> 1 from set). It allows choosing one glyph from a set of alternatives.

func (*AlternateSubst) Apply

func (a *AlternateSubst) Apply(ctx *OTApplyContext) int

Apply applies the alternate substitution. It extracts the alternate index from the lookup mask and glyph mask, matching HarfBuzz's AlternateSet::apply in OT/Layout/GSUB/AlternateSet.hh. The feature value (e.g., salt=2) is encoded in the mask bits.

func (*AlternateSubst) ApplyWithIndex

func (a *AlternateSubst) ApplyWithIndex(ctx *OTApplyContext, altIndex int) int

ApplyWithIndex applies the alternate substitution with a specific alternate index. altIndex is 0-based (0 = first alternate, 1 = second, etc.)

func (*AlternateSubst) GetAlternates

func (a *AlternateSubst) GetAlternates(glyph GlyphID) []GlyphID

GetAlternates returns the available alternates for a glyph. Returns nil if the glyph is not covered.

func (*AlternateSubst) Mapping

func (a *AlternateSubst) Mapping() map[GlyphID][]GlyphID

Mapping returns the input->alternates mapping for glyph closure computation.

type Anchor

type Anchor struct {
	Format uint16
	X      int16 // X coordinate in design units
	Y      int16 // Y coordinate in design units
	// Format 2 adds: anchorPoint (contour point index)
	AnchorPoint uint16
}

Anchor represents an anchor point for mark positioning. It stores x,y coordinates in design units.

type ArabicAction added in v0.0.4

type ArabicAction uint8

ArabicAction represents the shaping action for a character. HarfBuzz equivalent: hb-ot-shaper-arabic.cc:115-131 (arabic_action_t) The order MUST match arabic_features array and HarfBuzz's enum.

type AttachList

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

AttachList contains attachment points for glyphs.

type Avar added in v0.0.3

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

Avar represents a parsed avar (Axis Variations) table. It provides non-linear mapping for normalized axis values.

func ParseAvar added in v0.0.3

func ParseAvar(data []byte) (*Avar, error)

ParseAvar parses an avar table.

func (*Avar) HasData added in v0.0.3

func (a *Avar) HasData() bool

HasData returns true if the avar table has valid data.

func (*Avar) MapCoords added in v0.0.3

func (a *Avar) MapCoords(coords []int) []int

MapCoords maps an array of normalized coordinates through avar. Input and output are in F2DOT14 format.

func (*Avar) MapValue added in v0.0.3

func (a *Avar) MapValue(axisIndex int, value int) int

MapValue maps a normalized coordinate through the avar segment map. Both input and output are in F2DOT14 format.

type AxisFlags added in v0.0.3

type AxisFlags uint16

AxisFlags for variation axes.

const (
	// AxisFlagHidden indicates the axis should not be exposed in user interfaces.
	AxisFlagHidden AxisFlags = 0x0001
)

type AxisInfo added in v0.0.3

type AxisInfo struct {
	Index        int
	Tag          Tag
	NameID       uint16
	Flags        AxisFlags
	MinValue     float32
	DefaultValue float32
	MaxValue     float32
}

AxisInfo describes a variation axis.

type BaseArray

type BaseArray struct {
	Rows       int
	ClassCount int
	Anchors    [][]*Anchor // [row][class] -> Anchor (may be nil)
}

BaseArray contains anchors for base glyphs, organized as a matrix. Rows correspond to base glyphs (in BaseCoverage order). Columns correspond to mark classes (0 to classCount-1).

func (*BaseArray) GetAnchor

func (ba *BaseArray) GetAnchor(baseIndex, markClass int) *Anchor

GetAnchor returns the anchor for a given base glyph index and mark class.

type BasePos added in v0.0.4

type BasePos uint8

BasePos indicates how to find the base consonant. HarfBuzz equivalent: base_pos_t

const (
	BasePosLastSinhala BasePos = iota // Last consonant (Sinhala-style)
	BasePosLast                       // Last consonant
	BasePosFirst                      // First consonant (for some scripts)
)

type BlwfMode added in v0.0.4

type BlwfMode uint8

BlwfMode indicates how below-forms are handled. HarfBuzz equivalent: blwf_mode_t

const (
	BlwfModePreAndPost BlwfMode = iota // Below-forms before and after base
	BlwfModePostOnly                   // Below-forms only after base
)

type Buffer

type Buffer struct {
	Info      []GlyphInfo
	Pos       []GlyphPos
	Direction Direction
	Flags     BufferFlags

	// Idx is the cursor into Info and Pos arrays.
	// HarfBuzz: hb_buffer_t::idx (hb-buffer.hh line 97)
	Idx int

	// Script and Language for shaping (optional, can be auto-detected)
	Script             Tag
	Language           Tag
	LanguageCandidates []Tag // Multiple language candidates in priority order (BCP47→OT may produce multiple)

	// PreContext and PostContext hold Unicode codepoints that surround the text being shaped.
	// Used for Arabic joining: context characters affect the joining form of the first/last glyphs.
	// HarfBuzz equivalent: context[2][CONTEXT_LENGTH] and context_len[2] in hb-buffer.hh:110-111
	PreContext  []Codepoint
	PostContext []Codepoint

	// ScratchFlags holds temporary flags used during shaping.
	// HarfBuzz equivalent: scratch_flags in hb-buffer.hh
	ScratchFlags ScratchFlags

	// RandomState for the 'rand' feature's pseudo-random number generator.
	// HarfBuzz equivalent: random_state in hb-buffer.hh
	// Uses minstd_rand: state = state * 48271 % 2147483647
	// Initial value 1 (set in NewBuffer/reset).
	RandomState uint32

	// ClusterLevel controls cluster merging behavior.
	// HarfBuzz equivalent: cluster_level in hb-buffer.hh
	// 0 = MONOTONE_GRAPHEMES (default): merge marks into base, monotone order
	// 1 = MONOTONE_CHARACTERS: keep marks separate, monotone order
	// 2 = CHARACTERS: keep marks separate, no monotone enforcement
	// 3 = GRAPHEMES: merge marks into base, no monotone enforcement
	ClusterLevel int

	// NotFoundVSGlyph is the glyph ID to use for variation selectors that are
	// not found in the font. -1 means not set (VS will be removed from buffer).
	// HarfBuzz equivalent: not_found_variation_selector in hb-buffer.hh
	NotFoundVSGlyph int
	// contains filtered or unexported fields
}

Buffer holds a sequence of glyphs being shaped.

func NewBuffer

func NewBuffer() *Buffer

NewBuffer creates a new empty buffer. Direction is initially unset (0) and should be set explicitly or via GuessSegmentProperties.

func (*Buffer) AddCodepoints

func (b *Buffer) AddCodepoints(codepoints []Codepoint)

AddCodepoints adds Unicode codepoints to the buffer. Marks (Unicode category M) are assigned to the same cluster as the preceding base character.

func (*Buffer) AddMasks added in v0.0.4

func (buf *Buffer) AddMasks(mask uint32)

AddMasks adds mask bits to all glyphs. HarfBuzz equivalent: hb_buffer_t::add_masks()

func (*Buffer) AddString

func (b *Buffer) AddString(s string)

AddString adds a string to the buffer. Marks (Unicode category M) are assigned to the same cluster as the preceding base character.

func (*Buffer) AllocateLigID added in v0.0.4

func (b *Buffer) AllocateLigID() uint8

AllocateLigID allocates a new ligature ID. HarfBuzz equivalent: _hb_allocate_lig_id() in hb-ot-layout.hh:512

func (*Buffer) BacktrackInfo added in v0.0.4

func (b *Buffer) BacktrackInfo(pos int) *GlyphInfo

BacktrackInfo returns the GlyphInfo at the given backtrack position. HarfBuzz: prev() uses out_info when have_output is true. This is needed because backtrack matching uses the output buffer, not input!

func (*Buffer) BacktrackLen added in v0.0.4

func (b *Buffer) BacktrackLen() int

BacktrackLen returns the number of glyphs available for backtrack matching. HarfBuzz equivalent: hb_buffer_t::backtrack_len() in hb-buffer.hh:232 When have_output is true, this returns out_len (output buffer size). When have_output is false, this returns idx (current position in input).

func (*Buffer) Clear

func (b *Buffer) Clear()

Clear removes all glyphs from the buffer.

func (*Buffer) Codepoints added in v0.0.4

func (b *Buffer) Codepoints() []Codepoint

Codepoints returns a slice of codepoints from the buffer.

func (*Buffer) GlyphIDs

func (b *Buffer) GlyphIDs() []GlyphID

GlyphIDs returns just the glyph IDs.

func (*Buffer) GuessSegmentProperties

func (b *Buffer) GuessSegmentProperties()

GuessSegmentProperties guesses direction, script, and language from buffer content. This is similar to HarfBuzz's hb_buffer_guess_segment_properties().

func (*Buffer) HaveOutput added in v0.0.4

func (b *Buffer) HaveOutput() bool

HaveOutput returns whether the buffer is in output mode.

func (*Buffer) Len

func (b *Buffer) Len() int

Len returns the number of glyphs in the buffer.

func (*Buffer) MergeClusters added in v0.0.4

func (b *Buffer) MergeClusters(start, end int)

MergeClusters merges clusters in the range [start, end). All glyphs in the range are assigned the minimum cluster value found in the range. HarfBuzz equivalent: hb_buffer_t::merge_clusters_impl() in hb-buffer.cc:547-582

func (*Buffer) Reset

func (b *Buffer) Reset()

Reset clears the buffer and resets all properties to defaults.

func (*Buffer) ResetMasks added in v0.0.4

func (buf *Buffer) ResetMasks(mask uint32)

ResetMasks sets all glyphs to the given mask. HarfBuzz equivalent: hb_buffer_t::reset_masks()

func (*Buffer) Reverse added in v0.0.4

func (b *Buffer) Reverse()

Reverse reverses the order of glyphs in the buffer. HarfBuzz equivalent: hb_buffer_reverse() in hb-buffer.cc:387

func (*Buffer) ReverseRange added in v0.0.4

func (b *Buffer) ReverseRange(start, end int)

ReverseRange reverses the order of glyphs in the range [start, end). HarfBuzz equivalent: buffer->reverse_range() in hb-buffer.hh:242-247

func (*Buffer) SetDirection

func (b *Buffer) SetDirection(dir Direction)

SetDirection sets the text direction.

func (*Buffer) SetMasksForClusterRange added in v0.0.4

func (buf *Buffer) SetMasksForClusterRange(value, mask uint32, clusterStart, clusterEnd int)

SetMasksForClusterRange sets mask bits for glyphs in a cluster range. HarfBuzz equivalent: hb_buffer_t::set_masks()

type BufferFlags

type BufferFlags uint32

BufferFlags controls buffer behavior during shaping. These match HarfBuzz's hb_buffer_flags_t.

const (
	// BufferFlagDefault is the default buffer flag.
	BufferFlagDefault BufferFlags = 0
	// BufferFlagBOT indicates beginning of text paragraph.
	BufferFlagBOT BufferFlags = 1 << iota
	// BufferFlagEOT indicates end of text paragraph.
	BufferFlagEOT
	// BufferFlagPreserveDefaultIgnorables keeps default ignorable characters visible.
	BufferFlagPreserveDefaultIgnorables
	// BufferFlagRemoveDefaultIgnorables removes default ignorable characters from output.
	BufferFlagRemoveDefaultIgnorables
	// BufferFlagDoNotInsertDottedCircle prevents dotted circle insertion for invalid sequences.
	BufferFlagDoNotInsertDottedCircle
)

type CFF

type CFF struct {
	Name        string
	TopDict     TopDict
	Strings     []string // Custom strings (SID 391+)
	GlobalSubrs [][]byte // Global subroutines
	CharStrings [][]byte // Per-glyph CharStrings
	PrivateDict PrivateDict
	LocalSubrs  [][]byte  // Local subroutines
	Charset     []GlyphID // Glyph ID to SID mapping

	// CID fonts
	IsCID    bool
	FDArray  []FontDict
	FDSelect []byte
	// contains filtered or unexported fields
}

CFF represents a parsed CFF (Compact Font Format) table.

func ParseCFF

func ParseCFF(data []byte) (*CFF, error)

ParseCFF parses a CFF table from raw data.

func (*CFF) GetGlyphFromName added in v0.0.4

func (c *CFF) GetGlyphFromName(name string) (GlyphID, bool)

GetGlyphFromName returns the glyph ID for a given glyph name. Returns (0, false) if the name cannot be found. HarfBuzz equivalent: hb_ot_cff1_table_t::get_glyph_from_name() in hb-ot-cff1-table.hh:1408-1464

func (*CFF) GetGlyphName added in v0.0.4

func (c *CFF) GetGlyphName(glyph GlyphID) string

GetGlyphName returns the glyph name for a given glyph ID. Returns empty string if the glyph has no name (CID fonts or invalid glyph). HarfBuzz equivalent: hb_ot_cff1_table_t::get_glyph_name() in hb-ot-cff1-table.hh:1379-1406

func (*CFF) GetString

func (c *CFF) GetString(sid int) string

GetString returns the string for a given SID.

func (*CFF) NumGlyphs

func (c *CFF) NumGlyphs() int

NumGlyphs returns the number of glyphs in the CFF font.

type CaretValue

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

CaretValue represents a caret position within a ligature.

func (*CaretValue) Coordinate

func (cv *CaretValue) Coordinate() int16

Coordinate returns the coordinate value for a CaretValue (format 1 or 3).

func (*CaretValue) Format

func (cv *CaretValue) Format() uint16

Format returns the CaretValue format (1, 2, or 3).

func (*CaretValue) PointIndex

func (cv *CaretValue) PointIndex() uint16

PointIndex returns the contour point index for a CaretValue (format 2).

type ChainContextPos

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

ChainContextPos represents a Chaining Context Positioning subtable (GPOS Type 8). It matches backtrack, input, and lookahead sequences, then applies nested lookups. HarfBuzz equivalent: ChainContextPos in OT/Layout/GPOS/ChainContextPos.hh

func (*ChainContextPos) Apply

func (ccp *ChainContextPos) Apply(ctx *OTApplyContext) bool

Apply applies chaining context positioning.

type ChainContextSubst

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

ChainContextSubst represents a Chaining Context Substitution subtable (GSUB Type 6). It enables substitution based on surrounding context (backtrack, input, lookahead).

func (*ChainContextSubst) Apply

func (ccs *ChainContextSubst) Apply(ctx *OTApplyContext) int

Apply applies the chaining context substitution.

type ChainRule

type ChainRule struct {
	Backtrack     []GlyphID      // Backtrack sequence (in reverse order)
	Input         []GlyphID      // Input sequence (starting from second glyph)
	Lookahead     []GlyphID      // Lookahead sequence
	LookupRecords []LookupRecord // Lookups to apply
}

ChainRule represents a single chaining context rule.

type CharStringInterpreter

type CharStringInterpreter struct {

	// Closure tracking
	UsedGlobalSubrs map[int]bool
	UsedLocalSubrs  map[int]bool
	// contains filtered or unexported fields
}

CharStringInterpreter interprets CFF Type 2 CharStrings to find subroutine usage.

func NewCharStringInterpreter

func NewCharStringInterpreter(globalSubrs, localSubrs [][]byte) *CharStringInterpreter

NewCharStringInterpreter creates a new interpreter for finding subroutine usage.

func (*CharStringInterpreter) FindUsedSubroutines

func (i *CharStringInterpreter) FindUsedSubroutines(charstring []byte) error

FindUsedSubroutines executes a CharString to find all subroutine calls. This is a simplified interpreter that only tracks subr calls, not actual drawing.

type ClassDef

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

ClassDef maps glyph IDs to class values.

func ParseClassDef

func ParseClassDef(data []byte, offset int) (*ClassDef, error)

ParseClassDef parses a ClassDef table.

func (*ClassDef) GetClass

func (cd *ClassDef) GetClass(glyph GlyphID) int

GetClass returns the class for a glyph ID. Returns 0 (default class) if glyph not found.

func (*ClassDef) Mapping

func (cd *ClassDef) Mapping() map[GlyphID]uint16

Mapping returns a map from glyph ID to class for all glyphs in this ClassDef.

type Cmap

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

Cmap provides Unicode to glyph ID mapping.

func ParseCmap

func ParseCmap(data []byte) (*Cmap, error)

ParseCmap parses a cmap table.

func (*Cmap) CollectMapping added in v0.0.3

func (c *Cmap) CollectMapping() map[rune]GlyphID

CollectMapping returns a map of all Unicode codepoints to glyph IDs.

func (*Cmap) CollectReverseMapping added in v0.0.3

func (c *Cmap) CollectReverseMapping() map[GlyphID]rune

CollectReverseMapping returns a map of glyph IDs to Unicode codepoints. If multiple codepoints map to the same glyph, the last one wins.

func (*Cmap) IsSymbol added in v0.0.4

func (c *Cmap) IsSymbol() bool

IsSymbol returns true if this is a Symbol-encoded font (Platform 3, Encoding 0).

func (*Cmap) Lookup

func (c *Cmap) Lookup(cp Codepoint) (GlyphID, bool)

Lookup returns the glyph ID for a codepoint. For Symbol fonts, applies PUA mapping based on font page. Source: HarfBuzz hb-ot-cmap-table.hh accelerator_t constructor

func (*Cmap) LookupVariation

func (c *Cmap) LookupVariation(cp Codepoint, vs Codepoint) (GlyphID, bool)

LookupVariation returns the glyph ID for a codepoint with variation selector. Returns the glyph ID and true ONLY if a specific variant was found in cmap format 14. If no variant is found (or no format 14 table), returns (0, false). The caller should fall back to GSUB for combining base + VS when this returns false.

func (*Cmap) SetFontPage added in v0.0.4

func (c *Cmap) SetFontPage(fontPage uint16)

SetFontPage sets the font page from OS/2 table for Arabic PUA mapping. For OS/2 version 0, this is fsSelection & 0xFF00. Source: HarfBuzz hb-ot-os2-table.hh:333-342

type Codepoint

type Codepoint = uint32

Codepoint represents a Unicode codepoint.

const DottedCircle Codepoint = 0x25CC

DottedCircle is the Unicode codepoint for the dotted circle character. It is inserted between invalid vowel sequences.

func ArabicPUASimpMap added in v0.0.4

func ArabicPUASimpMap(u Codepoint) Codepoint

ArabicPUASimpMap maps a Unicode codepoint to its PUA equivalent. Returns 0 if no mapping exists.

func ArabicPUATradMap added in v0.0.4

func ArabicPUATradMap(u Codepoint) Codepoint

ArabicPUATradMap maps a Unicode codepoint to its PUA equivalent. Returns 0 if no mapping exists.

func BidiMirror added in v0.0.6

func BidiMirror(cp Codepoint) Codepoint

BidiMirror returns the mirroring codepoint for RTL text, or the same codepoint if no mirror exists. HarfBuzz equivalent: hb_ucd_mirroring() in hb-ucd.cc

func Compose added in v0.0.4

func Compose(first, second Codepoint) (composed Codepoint, ok bool)

Compose returns the canonical composition of two codepoints. Returns false if no composition exists. HarfBuzz equivalent: hb_ucd_compose()

func Decompose added in v0.0.4

func Decompose(cp Codepoint) (first, second Codepoint, ok bool)

Decompose returns the canonical decomposition of a codepoint. Returns false if no decomposition exists. HarfBuzz equivalent: hb_ucd_decompose()

func SymbolPUAMap added in v0.0.4

func SymbolPUAMap(u Codepoint) Codepoint

SymbolPUAMap maps a codepoint for standard Symbol fonts. For codepoints 0x00-0xFF, maps to U+F000+codepoint (PUA). Source: HarfBuzz _hb_symbol_pua_map in hb-ot-cmap-table.hh

type CompositeComponent

type CompositeComponent struct {
	GlyphID GlyphID
	Flags   uint16
	Arg1    int16
	Arg2    int16
	// Transform matrix components (optional)
	Scale   float32
	ScaleX  float32
	ScaleY  float32
	Scale01 float32
	Scale10 float32
}

CompositeComponent represents a component in a composite glyph.

type Condition added in v0.0.4

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

Condition represents a single condition. Currently only Format 1 (ConditionAxisRange) is defined. HarfBuzz: struct Condition in hb-ot-layout-common.hh:4209

func (*Condition) Evaluate added in v0.0.4

func (c *Condition) Evaluate(coords []int) bool

Evaluate returns true if the condition is satisfied for the given coordinates. HarfBuzz: Condition::evaluate() / ConditionAxisRange::evaluate()

type ConditionSet added in v0.0.4

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

ConditionSet represents a set of conditions that must ALL be true (AND logic). HarfBuzz: struct ConditionSet in hb-ot-layout-common.hh:4305

func (*ConditionSet) Evaluate added in v0.0.4

func (cs *ConditionSet) Evaluate(coords []int) bool

Evaluate returns true if ALL conditions in the set are satisfied. HarfBuzz: ConditionSet::evaluate() in hb-ot-layout-common.hh:4340

type ContextMatchFunc added in v0.0.5

type ContextMatchFunc func(info *GlyphInfo) bool

ContextMatchFunc is a callback that checks whether a glyph matches at a given position. It is used by NextContextMatch/PrevContextMatch to implement the 3-way match logic from HarfBuzz's skipping_iterator_t::match(). Returns true if the glyph matches the expected value.

type ContextPos

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

ContextPos represents a Context Positioning subtable (GPOS Type 7). It matches input sequences and applies nested positioning lookups. HarfBuzz equivalent: ContextPos in OT/Layout/GPOS/ContextPos.hh

func (*ContextPos) Apply

func (cp *ContextPos) Apply(ctx *OTApplyContext) bool

Apply applies context positioning.

type ContextRule

type ContextRule struct {
	Input         []GlyphID      // Input sequence (starting from second glyph)
	LookupRecords []LookupRecord // Lookups to apply
}

ContextRule represents a single context rule.

type ContextSubst

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

ContextSubst represents a Context Substitution subtable (GSUB Type 5). It matches input sequences and applies nested lookups.

func (*ContextSubst) Apply

func (cs *ContextSubst) Apply(ctx *OTApplyContext) int

Apply applies the context substitution.

type Coverage

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

Coverage represents an OpenType Coverage table. It maps glyph IDs to coverage indices.

func ParseCoverage

func ParseCoverage(data []byte, offset int) (*Coverage, error)

ParseCoverage parses a Coverage table from data at the given offset.

func (*Coverage) GetCoverage

func (c *Coverage) GetCoverage(glyph GlyphID) uint32

GetCoverage returns the coverage index for a glyph ID, or NotCovered if not found.

func (*Coverage) Glyphs

func (c *Coverage) Glyphs() []GlyphID

Glyphs returns all glyphs covered by this coverage table.

type CursivePos

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

CursivePos represents a Cursive Attachment subtable (GPOS Type 3). It connects glyphs in cursive scripts (like Arabic) by aligning exit anchors with entry anchors of adjacent glyphs.

func (*CursivePos) Apply

func (cp *CursivePos) Apply(ctx *OTApplyContext) bool

Apply applies cursive positioning. It connects the current glyph's entry anchor to the previous glyph's exit anchor.

func (*CursivePos) Coverage

func (cp *CursivePos) Coverage() *Coverage

Coverage returns the coverage table for this subtable.

func (*CursivePos) EntryExitRecords

func (cp *CursivePos) EntryExitRecords() []EntryExitRecord

EntryExitRecords returns the entry/exit anchor records.

type Decomposition added in v0.0.4

type Decomposition struct {
	First  Codepoint
	Second Codepoint // 0 if single-character decomposition
}

Decomposition represents a canonical decomposition.

type DeltaSetIndexMap added in v0.0.3

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

DeltaSetIndexMap maps glyph IDs to variation indices.

func (*DeltaSetIndexMap) Map added in v0.0.3

func (dm *DeltaSetIndexMap) Map(glyph uint32) uint32

Map returns the variation index for a glyph. Returns 16.16 format: (outer << 16) | inner

type Direction

type Direction int

Direction represents text direction. HarfBuzz: hb_direction_t in hb-common.h:238-242 Values use bit-encoding for fast checks:

  • Bit 2 (0x04): always set for valid directions
  • Bit 1 (0x02): vertical (0=horizontal, 1=vertical)
  • Bit 0 (0x01): backward (0=forward, 1=backward)
const (
	DirectionInvalid Direction = 0 // HB_DIRECTION_INVALID
	DirectionLTR     Direction = 4 // HB_DIRECTION_LTR (horizontal, forward)
	DirectionRTL     Direction = 5 // HB_DIRECTION_RTL (horizontal, backward)
	DirectionTTB     Direction = 6 // HB_DIRECTION_TTB (vertical, forward)
	DirectionBTT     Direction = 7 // HB_DIRECTION_BTT (vertical, backward)
)

func GetHorizontalDirection added in v0.0.4

func GetHorizontalDirection(script Tag) Direction

GetHorizontalDirection returns the horizontal direction for a script tag. HarfBuzz equivalent: hb_script_get_horizontal_direction() in hb-common.cc:523-613 Script tags are ISO 15924 format (uppercase-first): 'Arab', 'Hebr', etc.

func GuessDirection

func GuessDirection(s string) Direction

GuessDirection guesses text direction from the content.

func (Direction) IsBackward added in v0.0.4

func (d Direction) IsBackward() bool

IsBackward returns true if the direction is backward (RTL or BTT). HarfBuzz: HB_DIRECTION_IS_BACKWARD(dir) = ((dir & ~2U) == 5)

func (Direction) IsForward added in v0.0.4

func (d Direction) IsForward() bool

IsForward returns true if the direction is forward (LTR or TTB). HarfBuzz: HB_DIRECTION_IS_FORWARD(dir) = ((dir & ~2U) == 4)

func (Direction) IsHorizontal

func (d Direction) IsHorizontal() bool

IsHorizontal returns true if the direction is horizontal (LTR or RTL). HarfBuzz: HB_DIRECTION_IS_HORIZONTAL(dir) = ((dir & ~1U) == 4)

func (Direction) IsValid added in v0.0.4

func (d Direction) IsValid() bool

IsValid returns true if the direction is valid (LTR, RTL, TTB, or BTT). HarfBuzz: HB_DIRECTION_IS_VALID(dir) = ((dir & ~3U) == 4)

func (Direction) IsVertical added in v0.0.4

func (d Direction) IsVertical() bool

IsVertical returns true if the direction is vertical (TTB or BTT). HarfBuzz: HB_DIRECTION_IS_VERTICAL(dir) = ((dir & ~1U) == 6)

func (Direction) Reverse added in v0.0.4

func (d Direction) Reverse() Direction

Reverse returns the opposite direction (LTR↔RTL, TTB↔BTT). HarfBuzz: HB_DIRECTION_REVERSE(dir) = (dir ^ 1)

type EntryExitRecord

type EntryExitRecord struct {
	EntryAnchor *Anchor // May be nil
	ExitAnchor  *Anchor // May be nil
}

EntryExitRecord holds entry and exit anchors for cursive attachment.

type Face

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

Face represents a font face with parsed tables for metrics. This is a higher-level abstraction that caches parsed tables.

func LoadFace

func LoadFace(r io.Reader, index int) (*Face, error)

LoadFace loads a font from an io.Reader and returns a Face.

func LoadFaceFromData

func LoadFaceFromData(data []byte, index int) (*Face, error)

LoadFaceFromData loads a font from byte data and returns a Face.

func NewFace

func NewFace(font *Font) (*Face, error)

NewFace creates a new Face from a Font, parsing required tables.

func (*Face) Ascender

func (f *Face) Ascender() int16

Ascender returns the typographic ascender in font units.

func (*Face) BBox

func (f *Face) BBox() (xMin, yMin, xMax, yMax int16)

BBox returns the font bounding box.

func (*Face) CapHeight

func (f *Face) CapHeight() int16

CapHeight returns the cap height in font units.

func (*Face) Cmap

func (f *Face) Cmap() *Cmap

Cmap returns the cmap table.

func (*Face) Descender

func (f *Face) Descender() int16

Descender returns the typographic descender in font units (usually negative).

func (*Face) FamilyName

func (f *Face) FamilyName() string

FamilyName returns the font family name.

func (*Face) FindVariationAxis added in v0.0.3

func (f *Face) FindVariationAxis(tag Tag) (AxisInfo, bool)

FindVariationAxis finds a variation axis by its tag.

func (*Face) Fvar added in v0.0.3

func (f *Face) Fvar() *Fvar

Fvar returns the parsed fvar table, or nil if not present.

func (*Face) GetHExtents

func (f *Face) GetHExtents() FontExtents

GetHExtents returns horizontal font extents.

func (*Face) GlyphOutline added in v0.0.7

func (f *Face) GlyphOutline(gid GlyphID) (GlyphOutline, bool)

GlyphOutline extracts the outline (path segments) for a glyph. Returns the outline and true if the glyph has outline data. For empty glyphs (e.g. space), returns an empty outline and false. Supports both TrueType (glyf table, quadratic) and CFF (cubic) outlines.

func (*Face) HasVariations added in v0.0.3

func (f *Face) HasVariations() bool

HasVariations returns true if the font is a variable font.

func (*Face) HorizontalAdvance

func (f *Face) HorizontalAdvance(glyph GlyphID) float32

HorizontalAdvance returns the horizontal advance for a glyph in font units.

func (*Face) IsCFF

func (f *Face) IsCFF() bool

IsCFF returns true if the font uses CFF outlines.

func (*Face) IsFixedPitch

func (f *Face) IsFixedPitch() bool

IsFixedPitch returns true if the font is monospaced.

func (*Face) IsItalic

func (f *Face) IsItalic() bool

IsItalic returns true if the font is italic.

func (*Face) ItalicAngle

func (f *Face) ItalicAngle() int32

ItalicAngle returns the italic angle in degrees (fixed-point 16.16).

func (*Face) LineGap

func (f *Face) LineGap() int16

LineGap returns the line gap in font units.

func (*Face) NamedInstances added in v0.0.3

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

NamedInstances returns all named instances (e.g., "Bold", "Light"). Returns nil for non-variable fonts.

func (*Face) PostscriptName

func (f *Face) PostscriptName() string

PostscriptName returns the PostScript name of the font.

func (*Face) Upem

func (f *Face) Upem() uint16

Upem returns the units per em.

func (*Face) VariationAxes added in v0.0.3

func (f *Face) VariationAxes() []AxisInfo

VariationAxes returns information about all variation axes. Returns nil for non-variable fonts.

func (*Face) WeightClass

func (f *Face) WeightClass() uint16

WeightClass returns the font weight class (100-900).

func (*Face) XHeight

func (f *Face) XHeight() int16

XHeight returns the x-height in font units.

type Feature

type Feature struct {
	Tag   Tag    // Feature tag (e.g., TagKern, TagLiga)
	Value uint32 // 0 = off, 1 = on, >1 for alternates
	Start uint   // Cluster start (inclusive), FeatureGlobalStart for beginning
	End   uint   // Cluster end (exclusive), FeatureGlobalEnd for end

	// Internal flags matching HarfBuzz F_PER_SYLLABLE and F_MANUAL_ZWJ.
	// HarfBuzz: hb_ot_map_feature_flags_t in hb-ot-map.hh
	PerSyllable bool // F_PER_SYLLABLE: constrain lookup application to syllable boundaries
	ManualZWJ   bool // F_MANUAL_ZWJ: disable automatic ZWJ handling (AutoZWJ = !ManualZWJ)
	Random      bool // F_RANDOM: use random alternate selection (for 'rand' feature)
}

Feature represents an OpenType feature with optional range. This matches HarfBuzz's hb_feature_t structure.

func DefaultFeatures

func DefaultFeatures() []Feature

DefaultFeatures returns the default features for shaping. HarfBuzz equivalent: common_features[] in hb-ot-shape.cc:295-305 Note: 'locl' is applied separately in applyGSUB to ensure it only uses LangSys features.

func FeatureFromString

func FeatureFromString(s string) (Feature, bool)

FeatureFromString parses a feature string like HarfBuzz. Supported formats:

  • "kern" -> kern=1 (on)
  • "kern=1" -> kern=1 (on)
  • "kern=0" -> kern=0 (off)
  • "-kern" -> kern=0 (off)
  • "+kern" -> kern=1 (on)
  • "aalt=2" -> aalt=2 (alternate #2)
  • "kern[3:5]" -> kern=1 for clusters 3-5
  • "kern[3:5]=0" -> kern=0 for clusters 3-5
  • "kern[3:]" -> kern=1 from cluster 3 to end
  • "kern[:5]" -> kern=1 from start to cluster 5

Returns false if the string cannot be parsed.

func NewFeature

func NewFeature(tag Tag, value uint32) Feature

NewFeature creates a feature that applies globally (entire buffer).

func NewFeatureOff

func NewFeatureOff(tag Tag) Feature

NewFeatureOff creates a feature that is disabled globally.

func NewFeatureOn

func NewFeatureOn(tag Tag) Feature

NewFeatureOn creates a feature that is enabled globally.

func ParseFeatures

func ParseFeatures(s string) []Feature

ParseFeatures parses a comma-separated list of features.

func (Feature) IsGlobal

func (f Feature) IsGlobal() bool

IsGlobal returns true if the feature applies to the entire buffer.

func (Feature) String

func (f Feature) String() string

String returns a string representation of the feature.

type FeatureList

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

FeatureList represents a GSUB/GPOS FeatureList.

func (*FeatureList) Count

func (f *FeatureList) Count() int

Count returns the number of features.

func (*FeatureList) FindFeature

func (f *FeatureList) FindFeature(tag Tag) []uint16

FindFeature finds a feature by tag and returns its lookup indices.

func (*FeatureList) FindFeatureByIndices added in v0.0.4

func (f *FeatureList) FindFeatureByIndices(tag Tag, featureIndices []uint16) []uint16

FindFeatureByIndices returns lookup indices for a feature tag, considering only the specified feature indices. This is the correct way to query features when respecting Script/Language systems.

func (*FeatureList) FindFeatureByIndicesWithVariations added in v0.0.4

func (f *FeatureList) FindFeatureByIndicesWithVariations(tag Tag, featureIndices []uint16, fv *FeatureVariations, variationsIndex uint32) []uint16

FindFeatureByIndicesWithVariations returns lookup indices for a feature tag, considering FeatureVariations substitutions. HarfBuzz: hb_ot_map_t::collect_lookups() with feature_substitutes_map

func (*FeatureList) FindFeatureWithVariations added in v0.0.4

func (f *FeatureList) FindFeatureWithVariations(tag Tag, fv *FeatureVariations, variationsIndex uint32) []uint16

FindFeatureWithVariations returns lookup indices for a feature tag, considering FeatureVariations. This is a global search that considers all features with the matching tag.

func (*FeatureList) FindFirstFeature added in v0.0.4

func (f *FeatureList) FindFirstFeature(tag Tag) []uint16

FindFirstFeature finds the first feature with the given tag and returns its lookup indices. This is useful when a font has multiple features with the same tag (e.g., for different scripts) and you want to use the default/first one (typically the default script's feature).

func (*FeatureList) GetFeature

func (f *FeatureList) GetFeature(index int) (*FeatureRecord, error)

GetFeature returns the feature record at the given index.

type FeatureMap added in v0.0.4

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

FeatureMap maps feature tags to their mask values. This is used to determine which mask a lookup should use.

func NewFeatureMap added in v0.0.4

func NewFeatureMap() *FeatureMap

NewFeatureMap creates a new feature map with default mask allocations.

func (*FeatureMap) GetMask added in v0.0.4

func (fm *FeatureMap) GetMask(tag Tag) uint32

GetMask returns the mask for a feature tag. Features not in the map default to MaskGlobal.

type FeatureRecord

type FeatureRecord struct {
	Tag     Tag
	Lookups []uint16
}

FeatureRecord represents a parsed feature record with its lookup indices. This is the internal representation from the font's FeatureList table.

type FeatureTableSubstitution added in v0.0.4

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

FeatureTableSubstitution maps feature indices to alternate lookup lists. HarfBuzz: struct FeatureTableSubstitution in hb-ot-layout-common.hh:4479

type FeatureVariations added in v0.0.4

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

FeatureVariations represents the FeatureVariations table in GSUB/GPOS v1.1+. It allows fonts to substitute feature lookups based on variation axis values.

func ParseFeatureVariations added in v0.0.4

func ParseFeatureVariations(data []byte, offset int) (*FeatureVariations, error)

ParseFeatureVariations parses a FeatureVariations table from data at the given offset.

func (*FeatureVariations) FindIndex added in v0.0.4

func (fv *FeatureVariations) FindIndex(coords []int) uint32

FindIndex finds the first matching FeatureVariationRecord for the given normalized coordinates (in F2DOT14 format). Returns VariationsNotFoundIndex if no record matches. HarfBuzz: FeatureVariations::find_index() in hb-ot-layout-common.hh:4690

func (*FeatureVariations) GetSubstituteLookups added in v0.0.4

func (fv *FeatureVariations) GetSubstituteLookups(variationsIndex uint32, featureIndex uint16) []uint16

GetSubstituteLookups returns the substitute lookup indices for a feature at the given variationsIndex. Returns nil if no substitution exists for this feature. HarfBuzz: FeatureTableSubstitution::find_substitute() in hb-ot-layout-common.hh:4585

func (*FeatureVariations) RecordCount added in v0.0.4

func (fv *FeatureVariations) RecordCount() int

GetRecord returns the number of FeatureVariationRecords.

type Font

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

Font represents an OpenType font.

func ParseFont

func ParseFont(data []byte, index int) (*Font, error)

ParseFont parses an OpenType font from data. For TrueType Collections (.ttc) or DFONTs, use index to select a font.

func (*Font) GetGlyphFromName added in v0.0.4

func (f *Font) GetGlyphFromName(name string) (GlyphID, bool)

GetGlyphFromName converts a glyph name to a glyph ID. Supports multiple formats:

  • Direct post/CFF table lookup ("A", "B", "uni0622.fina")
  • Numeric glyph index ("123")
  • gidDDD syntax ("gid123")
  • uniUUUU syntax with cmap lookup ("uni0622")

Returns false if the name cannot be resolved. HarfBuzz equivalent: hb_ot_get_glyph_from_name() in hb-ot-font.cc:849-872

func (*Font) GetGlyphName added in v0.0.4

func (f *Font) GetGlyphName(glyph GlyphID) string

GetGlyphName returns the glyph name for a given glyph ID. Tries post table first, then CFF table, then falls back to "gidNNN". HarfBuzz equivalent: hb_ot_get_glyph_name() in hb-ot-font.cc:833-846

func (*Font) HasGlyph added in v0.0.4

func (f *Font) HasGlyph(cp Codepoint) bool

HasGlyph returns true if the font has a glyph for the given codepoint. HarfBuzz equivalent: hb_font_t::has_glyph() (hb-font.hh)

func (*Font) HasGlyphNames added in v0.0.4

func (f *Font) HasGlyphNames() bool

HasGlyphNames returns true if the font has a post table with glyph names. Returns false for post table version 3.0 (which has no glyph names).

func (*Font) HasTable

func (f *Font) HasTable(tag Tag) bool

HasTable returns true if the font has the given table.

func (*Font) NumGlyphs

func (f *Font) NumGlyphs() int

NumGlyphs returns the number of glyphs in the font. Returns 0 if maxp table is missing or invalid.

func (*Font) TableData

func (f *Font) TableData(tag Tag) ([]byte, error)

TableData returns the raw data for a table.

func (*Font) TableParser

func (f *Font) TableParser(tag Tag) (*Parser, error)

TableParser returns a parser for the given table.

type FontDict

type FontDict struct {
	Private [2]int // [size, offset]
}

FontDict contains per-font dictionary data (for CID fonts).

type FontExtents

type FontExtents struct {
	Ascender  int16 // Typographic ascender
	Descender int16 // Typographic descender (usually negative)
	LineGap   int16 // Line spacing gap
}

FontExtents contains font-wide extent values. This matches HarfBuzz's hb_font_extents_t.

type Fvar added in v0.0.3

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

Fvar represents a parsed fvar (Font Variations) table.

func ParseFvar added in v0.0.3

func ParseFvar(data []byte) (*Fvar, error)

ParseFvar parses an fvar table.

func (*Fvar) AxisCount added in v0.0.3

func (f *Fvar) AxisCount() int

AxisCount returns the number of variation axes.

func (*Fvar) AxisInfos added in v0.0.3

func (f *Fvar) AxisInfos() []AxisInfo

AxisInfos returns information about all variation axes.

func (*Fvar) FindAxis added in v0.0.3

func (f *Fvar) FindAxis(tag Tag) (AxisInfo, bool)

FindAxis finds an axis by its tag.

func (*Fvar) HasData added in v0.0.3

func (f *Fvar) HasData() bool

HasData returns true if the fvar table has variation data.

func (*Fvar) InstanceCount added in v0.0.3

func (f *Fvar) InstanceCount() int

InstanceCount returns the number of named instances.

func (*Fvar) NamedInstanceAt added in v0.0.3

func (f *Fvar) NamedInstanceAt(index int) (NamedInstance, bool)

NamedInstanceAt returns the named instance at the given index.

func (*Fvar) NamedInstances added in v0.0.3

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

NamedInstances returns all named instances.

func (*Fvar) NormalizeAxisValue added in v0.0.3

func (f *Fvar) NormalizeAxisValue(axisIndex int, value float32) float32

NormalizeAxisValue normalizes a user-space axis value to the range [-1, 1]. Values below default normalize to [-1, 0], values above to [0, 1].

func (*Fvar) NormalizeVariations added in v0.0.3

func (f *Fvar) NormalizeVariations(variations []Variation) []float32

NormalizeVariations converts user-space variations to normalized coordinates.

type GDEF

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

GDEF represents the Glyph Definition table.

func ParseGDEF

func ParseGDEF(data []byte) (*GDEF, error)

ParseGDEF parses the GDEF table from raw data.

func (*GDEF) GetAttachPoints

func (g *GDEF) GetAttachPoints(glyph GlyphID) []uint16

GetAttachPoints returns the attachment point indices for a glyph. Returns nil if the glyph has no attachment points defined.

func (*GDEF) GetGlyphClass

func (g *GDEF) GetGlyphClass(glyph GlyphID) int

GetGlyphClass returns the glyph class for a glyph ID. Returns GlyphClassUnclassified (0) if no class is defined.

func (*GDEF) GetLigCaretCount

func (g *GDEF) GetLigCaretCount(glyph GlyphID) int

GetLigCaretCount returns the number of caret positions for a ligature glyph. Returns 0 if the glyph has no caret positions defined.

func (*GDEF) GetLigCarets

func (g *GDEF) GetLigCarets(glyph GlyphID) []CaretValue

GetLigCarets returns the caret values for a ligature glyph. Returns nil if the glyph has no caret positions defined.

func (*GDEF) GetMarkAttachClass

func (g *GDEF) GetMarkAttachClass(glyph GlyphID) int

GetMarkAttachClass returns the mark attachment class for a glyph ID. Returns 0 if no class is defined.

func (*GDEF) HasAttachList

func (g *GDEF) HasAttachList() bool

HasAttachList returns true if the GDEF table has an attachment point list.

func (*GDEF) HasGlyphClasses

func (g *GDEF) HasGlyphClasses() bool

HasGlyphClasses returns true if the GDEF table has glyph class definitions.

func (*GDEF) HasLigCaretList

func (g *GDEF) HasLigCaretList() bool

HasLigCaretList returns true if the GDEF table has a ligature caret list.

func (*GDEF) HasMarkAttachClasses

func (g *GDEF) HasMarkAttachClasses() bool

HasMarkAttachClasses returns true if the GDEF table has mark attachment class definitions.

func (*GDEF) HasMarkGlyphSets

func (g *GDEF) HasMarkGlyphSets() bool

HasMarkGlyphSets returns true if the GDEF table has mark glyph sets (version >= 1.2).

func (*GDEF) IsBaseGlyph

func (g *GDEF) IsBaseGlyph(glyph GlyphID) bool

IsBaseGlyph returns true if the glyph is classified as a base glyph.

func (*GDEF) IsComponentGlyph

func (g *GDEF) IsComponentGlyph(glyph GlyphID) bool

IsComponentGlyph returns true if the glyph is classified as a component glyph.

func (*GDEF) IsInMarkGlyphSet

func (g *GDEF) IsInMarkGlyphSet(glyph GlyphID, setIndex int) bool

IsInMarkGlyphSet returns true if the glyph is in the specified mark glyph set.

func (*GDEF) IsLigatureGlyph

func (g *GDEF) IsLigatureGlyph(glyph GlyphID) bool

IsLigatureGlyph returns true if the glyph is classified as a ligature glyph.

func (*GDEF) IsMarkGlyph

func (g *GDEF) IsMarkGlyph(glyph GlyphID) bool

IsMarkGlyph returns true if the glyph is classified as a mark glyph.

func (*GDEF) MarkGlyphSetCount

func (g *GDEF) MarkGlyphSetCount() int

MarkGlyphSetCount returns the number of mark glyph sets.

func (*GDEF) Version

func (g *GDEF) Version() (uint16, uint16)

Version returns the GDEF table version as (major, minor).

type GPOS

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

GPOS represents the Glyph Positioning table.

func ParseGPOS

func ParseGPOS(data []byte) (*GPOS, error)

ParseGPOS parses a GPOS table from data.

func (*GPOS) ApplyKerning

func (g *GPOS) ApplyKerning(glyphs []GlyphID) []GlyphPos

ApplyKerning is a convenience method to apply pair positioning (kerning). DEPRECATED: Use ApplyLookupToBuffer for new code. This version does not use GDEF for glyph filtering.

func (*GPOS) ApplyKerningWithGDEF

func (g *GPOS) ApplyKerningWithGDEF(glyphs []GlyphID, gdef *GDEF) []GlyphPos

ApplyKerningWithGDEF applies pair positioning with GDEF-based glyph filtering. DEPRECATED: Use ApplyLookupToBuffer for new code.

func (*GPOS) ApplyLookup

func (g *GPOS) ApplyLookup(lookupIndex int, glyphs []GlyphID, positions []GlyphPos)

ApplyLookup applies a single lookup to the glyph/position arrays. DEPRECATED: Use ApplyLookupToBuffer for new code. This version does not use GDEF for glyph filtering.

func (*GPOS) ApplyLookupToBuffer added in v0.0.4

func (g *GPOS) ApplyLookupToBuffer(lookupIndex int, buf *Buffer, gdef *GDEF, font *Font)

ApplyLookupToBuffer applies a single lookup directly to a Buffer. HarfBuzz equivalent: apply() in hb-ot-layout-gsubgpos.hh Uses MaskGlobal so lookup applies to all glyphs (which have MaskGlobal by default).

func (*GPOS) ApplyLookupToBufferWithMask added in v0.0.4

func (g *GPOS) ApplyLookupToBufferWithMask(lookupIndex int, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font)

ApplyLookupToBufferWithMask applies a single lookup directly to a Buffer with mask-based filtering. HarfBuzz equivalent: apply() in hb-ot-layout-gsubgpos.hh with mask check in may_match()

The featureMask parameter specifies which glyphs this lookup should apply to. A glyph is skipped if (glyph.Mask & featureMask) == 0. Use MaskGlobal to apply to all glyphs (which have MaskGlobal set by default).

func (*GPOS) ApplyLookupWithDirection

func (g *GPOS) ApplyLookupWithDirection(lookupIndex int, glyphs []GlyphID, positions []GlyphPos, direction Direction)

ApplyLookupWithDirection applies a single lookup with the specified direction. DEPRECATED: Use ApplyLookupToBuffer for new code. This version does not use GDEF for glyph filtering.

func (*GPOS) ApplyLookupWithGDEF

func (g *GPOS) ApplyLookupWithGDEF(lookupIndex int, glyphs []GlyphID, positions []GlyphPos, direction Direction, gdef *GDEF)

ApplyLookupWithGDEF applies a single lookup with GDEF-based glyph filtering. DEPRECATED: Use ApplyLookupToBuffer for new code.

func (*GPOS) FindVariationsIndex added in v0.0.4

func (g *GPOS) FindVariationsIndex(coords []int) uint32

FindVariationsIndex finds the matching FeatureVariations record index for the given normalized coordinates (in F2DOT14 format). Returns VariationsNotFoundIndex if no record matches or no FeatureVariations table exists. HarfBuzz: hb_ot_layout_table_find_feature_variations() in hb-ot-layout.cc

func (*GPOS) GetFeatureVariations added in v0.0.4

func (g *GPOS) GetFeatureVariations() *FeatureVariations

GetFeatureVariations returns the FeatureVariations table, or nil if not present.

func (*GPOS) GetLookup

func (g *GPOS) GetLookup(index int) *GPOSLookup

GetLookup returns the lookup at the given index.

func (*GPOS) NumLookups

func (g *GPOS) NumLookups() int

NumLookups returns the number of lookups.

func (*GPOS) ParseFeatureList

func (g *GPOS) ParseFeatureList() (*FeatureList, error)

ParseFeatureList parses a FeatureList from a GPOS table.

func (*GPOS) ParseScriptList added in v0.0.4

func (g *GPOS) ParseScriptList() (*ScriptList, error)

ParseScriptList parses the ScriptList from a GPOS table.

type GPOSChainRule

type GPOSChainRule struct {
	Backtrack     []GlyphID          // Backtrack sequence (in reverse order)
	Input         []GlyphID          // Input sequence (starting from second glyph)
	Lookahead     []GlyphID          // Lookahead sequence
	LookupRecords []GPOSLookupRecord // Lookups to apply
}

GPOSChainRule represents a single chaining context positioning rule.

type GPOSContextRule

type GPOSContextRule struct {
	Input         []GlyphID          // Input sequence (starting from second glyph)
	LookupRecords []GPOSLookupRecord // Lookups to apply
}

GPOSContextRule represents a single rule in a context positioning rule set.

type GPOSLookup

type GPOSLookup struct {
	Type uint16
	Flag uint16

	MarkFilter uint16
	// contains filtered or unexported fields
}

GPOSLookup represents a GPOS lookup table.

func (*GPOSLookup) Subtables

func (l *GPOSLookup) Subtables() []GPOSSubtable

Subtables returns the subtables for this lookup.

type GPOSLookupRecord

type GPOSLookupRecord struct {
	SequenceIndex uint16 // Index into current glyph sequence (0-based)
	LookupIndex   uint16 // Lookup to apply
}

GPOSLookupRecord represents a lookup to apply at a specific position in a context.

type GPOSSubtable

type GPOSSubtable interface {
	// Apply applies the positioning to the glyphs at the current position.
	// Returns true if positioning was applied.
	Apply(ctx *OTApplyContext) bool
}

GPOSSubtable is the interface for GPOS lookup subtables.

type GSUB

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

GSUB represents the Glyph Substitution table.

func ParseGSUB

func ParseGSUB(data []byte) (*GSUB, error)

ParseGSUB parses a GSUB table from data.

func (*GSUB) ApplyFeatureToBuffer added in v0.0.4

func (g *GSUB) ApplyFeatureToBuffer(tag Tag, buf *Buffer, gdef *GDEF, font *Font)

ApplyFeatureToBuffer applies all lookups for a feature directly to a Buffer. HarfBuzz equivalent: hb_ot_layout_substitute_lookup() loop This preserves cluster information during substitution.

func (*GSUB) ApplyFeatureToBufferLangSysOnly added in v0.0.5

func (g *GSUB) ApplyFeatureToBufferLangSysOnly(tag Tag, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font, variationsIndex uint32)

ApplyFeatureToBufferLangSysOnly applies a feature only if it's found in the current script/language LangSys. Does NOT fall back to global feature search. This is used for 'locl' which should only apply when the font has it for the specific language. Tries the buffer's script first, then DFLT/dflt as fallback scripts.

func (*GSUB) ApplyFeatureToBufferRangeWithMask added in v0.0.4

func (g *GSUB) ApplyFeatureToBufferRangeWithMask(tag Tag, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font, start, end int)

ApplyFeatureToBufferRangeWithMask applies all lookups for a feature to a range of the Buffer. This is used for per-syllable feature application (F_PER_SYLLABLE in HarfBuzz). Only glyphs in the range [start, end) are considered for substitution. HarfBuzz equivalent: per_syllable flag in hb_ot_apply_context_t

func (*GSUB) ApplyFeatureToBufferRangeWithOpts added in v0.0.5

func (g *GSUB) ApplyFeatureToBufferRangeWithOpts(tag Tag, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font, start, end int, autoZWNJ, autoZWJ bool)

ApplyFeatureToBufferRangeWithOpts is like ApplyFeatureToBufferRangeWithMask but allows setting AutoZWNJ and AutoZWJ flags. These control whether ZWNJ/ZWJ are automatically skipped during matching (HarfBuzz: auto_zwnj, auto_zwj from F_MANUAL_ZWNJ/F_MANUAL_ZWJ).

func (*GSUB) ApplyFeatureToBufferWithMask added in v0.0.4

func (g *GSUB) ApplyFeatureToBufferWithMask(tag Tag, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font)

ApplyFeatureToBufferWithMask applies all lookups for a feature directly to a Buffer with mask filtering. This preserves cluster information during substitution. CRITICAL: Uses script/language-specific feature selection (like HarfBuzz)

func (*GSUB) ApplyFeatureToBufferWithMaskAndVariations added in v0.0.4

func (g *GSUB) ApplyFeatureToBufferWithMaskAndVariations(tag Tag, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font, variationsIndex uint32)

ApplyFeatureToBufferWithMaskAndVariations applies all lookups for a feature directly to a Buffer with mask filtering and FeatureVariations support. variationsIndex should be obtained from FindVariationsIndex() or VariationsNotFoundIndex if not applicable. HarfBuzz: hb_ot_layout_substitute_lookup() with feature_substitutes_map

func (*GSUB) ApplyFeatureToBufferWithOpts added in v0.0.6

func (g *GSUB) ApplyFeatureToBufferWithOpts(tag Tag, buf *Buffer, gdef *GDEF, font *Font, autoZWNJ, autoZWJ bool)

ApplyFeatureToBufferWithOpts applies all lookups for a feature directly to a Buffer with explicit AutoZWNJ and AutoZWJ flags. This is needed for shapers like Khmer that use F_MANUAL_JOINERS (autoZWNJ=false, autoZWJ=false). HarfBuzz equivalent: feature application with F_MANUAL_ZWNJ / F_MANUAL_ZWJ flags

func (*GSUB) ApplyFeatureWithCodepoints added in v0.0.4

func (g *GSUB) ApplyFeatureWithCodepoints(tag Tag, glyphs []GlyphID, codepoints []Codepoint, gdef *GDEF, font *Font) ([]GlyphID, []Codepoint)

ApplyFeatureWithCodepoints applies all lookups for a feature with GDEF-based filtering and support for default ignorable handling (like Variation Selectors). The codepoints slice should match glyphs in length, or can be nil if not needed.

func (*GSUB) ApplyFeatureWithGDEF

func (g *GSUB) ApplyFeatureWithGDEF(tag Tag, glyphs []GlyphID, gdef *GDEF, font *Font) []GlyphID

ApplyFeatureWithGDEF applies all lookups for a feature with GDEF-based glyph filtering. Note: This unions all features with the matching tag, which may not be correct for fonts with multiple features for different scripts/languages.

func (*GSUB) ApplyFeatureWithMask added in v0.0.4

func (g *GSUB) ApplyFeatureWithMask(tag Tag, glyphs []GlyphID, masks []uint32, featureMask uint32, gdef *GDEF, font *Font) ([]GlyphID, []uint32)

ApplyFeatureWithMask applies all lookups for a feature with mask-based filtering. This is the HarfBuzz-style approach where each glyph has a mask, and the lookup is only applied to glyphs where (mask & featureMask) != 0.

HarfBuzz equivalent: The mask check in hb-ot-layout-gsubgpos.hh

Parameters:

  • tag: The feature tag (e.g., 'isol', 'init', 'medi', 'fina')
  • glyphs: The current glyph sequence
  • masks: Mask for each glyph (must have same length as glyphs)
  • featureMask: The mask for this feature (used to filter which glyphs are affected)
  • gdef: GDEF table for glyph classification (may be nil)

Returns the modified glyph sequence and updated masks.

func (*GSUB) ApplyLookupReverseWithGDEF

func (g *GSUB) ApplyLookupReverseWithGDEF(lookupIndex int, glyphs []GlyphID, gdef *GDEF, font *Font) []GlyphID

ApplyLookupReverseWithGDEF applies this lookup in reverse order with GDEF-based glyph filtering. This is the intended way to use ReverseChainSingleSubst (GSUB Type 8).

func (*GSUB) ApplyLookupToBuffer added in v0.0.4

func (g *GSUB) ApplyLookupToBuffer(lookupIndex int, buf *Buffer, gdef *GDEF, font *Font)

ApplyLookupToBuffer applies a single GSUB lookup directly to a Buffer. HarfBuzz equivalent: hb_ot_layout_substitute_lookup() in hb-ot-layout.cc:2093-2098 Uses MaskGlobal so lookup applies to all glyphs (which have MaskGlobal by default). This preserves cluster information during substitution.

func (*GSUB) ApplyLookupToBufferRangeWithMask added in v0.0.4

func (g *GSUB) ApplyLookupToBufferRangeWithMask(lookupIndex int, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font, start, end int)

ApplyLookupToBufferRangeWithMask applies a single lookup to a range of the Buffer. Only positions in [start, end) are considered as starting positions for matches. Uses HarfBuzz defaults for auto_zwnj=true, auto_zwj=true.

func (*GSUB) ApplyLookupToBufferWithMask added in v0.0.4

func (g *GSUB) ApplyLookupToBufferWithMask(lookupIndex int, buf *Buffer, gdef *GDEF, featureMask uint32, font *Font)

ApplyLookupToBufferWithMask applies a single GSUB lookup directly to a Buffer with mask-based filtering.

HarfBuzz equivalent: Combines multiple HarfBuzz functions:

  • hb_ot_layout_substitute_lookup() in hb-ot-layout.cc:2093-2098
  • apply_string() / apply_forward() in hb-ot-layout.cc:1917-1947
  • Mask filtering: (info[j].mask & c->lookup_mask) in hb-ot-layout.cc:1930

The featureMask parameter corresponds to lookup_mask in hb_ot_apply_context_t. A glyph is skipped if (glyph.Mask & featureMask) == 0. Use MaskGlobal to apply to all glyphs (which have MaskGlobal set by default). This preserves cluster information during substitution (unlike array-based methods).

func (*GSUB) ApplyLookupWithCodepoints added in v0.0.4

func (g *GSUB) ApplyLookupWithCodepoints(lookupIndex int, glyphs []GlyphID, codepoints []Codepoint, gdef *GDEF, font *Font) ([]GlyphID, []Codepoint)

ApplyLookupWithCodepoints applies a single lookup with GDEF-based filtering and codepoint tracking for default ignorable handling.

func (*GSUB) ApplyLookupWithGDEF

func (g *GSUB) ApplyLookupWithGDEF(lookupIndex int, glyphs []GlyphID, gdef *GDEF, font *Font) []GlyphID

ApplyLookupWithGDEF applies a single lookup with GDEF-based glyph filtering.

func (*GSUB) ApplyLookupWithMask added in v0.0.4

func (g *GSUB) ApplyLookupWithMask(lookupIndex int, glyphs []GlyphID, masks []uint32, featureMask uint32, gdef *GDEF, font *Font) ([]GlyphID, []uint32)

ApplyLookupWithMask applies a single lookup with mask-based filtering. This is the HarfBuzz-style approach where each glyph has a mask, and the lookup is only applied to glyphs where (mask & featureMask) != 0.

HarfBuzz equivalent: The mask check in match_glyph() / may_match() in hb-ot-layout-gsubgpos.hh

Parameters:

  • lookupIndex: The GSUB lookup index
  • glyphs: The current glyph sequence
  • masks: Mask for each glyph (must have same length as glyphs)
  • featureMask: The mask for the current feature
  • gdef: GDEF table for glyph classification (may be nil)
  • font: Font object for scaling information (may be nil)

Returns the modified glyph sequence and updated masks.

func (*GSUB) FindBestLanguage added in v0.0.5

func (g *GSUB) FindBestLanguage(scriptTag Tag, languageTags []Tag) Tag

FindBestLanguage finds the first language tag from a list of candidates that the font actually supports in its GSUB table. Returns the matching Tag, or the first candidate if none match.

func (*GSUB) FindChosenScriptTag added in v0.0.4

func (g *GSUB) FindChosenScriptTag(scriptTag Tag) Tag

FindChosenScriptTag returns the actual script tag found in the font's GSUB table. This is needed for Indic old-spec vs new-spec detection. HarfBuzz equivalent: plan->map.chosen_script[0] in hb-ot-shaper-indic.cc:324 Returns 0 if no matching script is found.

func (*GSUB) FindVariationsIndex added in v0.0.4

func (g *GSUB) FindVariationsIndex(coords []int) uint32

FindVariationsIndex finds the matching FeatureVariations record index for the given normalized coordinates (in F2DOT14 format). Returns VariationsNotFoundIndex if no record matches or no FeatureVariations table exists. HarfBuzz: hb_ot_layout_table_find_feature_variations() in hb-ot-layout.cc

func (*GSUB) GetFeatureVariations added in v0.0.4

func (g *GSUB) GetFeatureVariations() *FeatureVariations

GetFeatureVariations returns the FeatureVariations table, or nil if not present.

func (*GSUB) GetLookup

func (g *GSUB) GetLookup(index int) *GSUBLookup

GetLookup returns the lookup at the given index.

func (*GSUB) NumLookups

func (g *GSUB) NumLookups() int

NumLookups returns the number of lookups in the GSUB table.

func (*GSUB) ParseFeatureList

func (g *GSUB) ParseFeatureList() (*FeatureList, error)

ParseFeatureList parses a FeatureList from a GSUB/GPOS table.

func (*GSUB) ParseScriptList added in v0.0.4

func (g *GSUB) ParseScriptList() (*ScriptList, error)

ParseScriptList parses the ScriptList from a GSUB table.

func (*GSUB) WouldSubstituteFeature added in v0.0.4

func (g *GSUB) WouldSubstituteFeature(featureTag Tag, glyphs []GlyphID, zeroContext bool) bool

WouldSubstituteFeature checks if a feature would substitute the given glyph sequence. HarfBuzz equivalent: hb_indic_would_substitute_feature_t::would_substitute() in hb-ot-shaper-indic.cc:99-107

type GSUBLookup

type GSUBLookup struct {
	Type uint16
	Flag uint16

	MarkFilter uint16 // For flag & 0x10
	// contains filtered or unexported fields
}

GSUBLookup represents a GSUB lookup table.

func (*GSUBLookup) Subtables

func (l *GSUBLookup) Subtables() []GSUBSubtable

Subtables returns the lookup subtables.

func (*GSUBLookup) WouldSubstitute added in v0.0.4

func (l *GSUBLookup) WouldSubstitute(glyphs []GlyphID, zeroContext bool) bool

WouldSubstitute checks if a lookup would apply to the given glyph sequence. HarfBuzz equivalent: hb_ot_layout_lookup_would_substitute() in hb-ot-layout.cc:1547-1560

Parameters: - glyphs: The sequence of glyph IDs to test - zeroContext: If true, ignore context rules (only match direct substitutions)

Returns true if any subtable in the lookup would match the input sequence.

type GSUBSubtable

type GSUBSubtable interface {
	// Apply applies the substitution to the glyph at the current position.
	// Returns the number of glyphs consumed (0 if not applied).
	// HarfBuzz equivalent: subtable dispatch in hb-ot-layout-gsubgpos.hh
	Apply(ctx *OTApplyContext) int
}

GSUBSubtable is the interface for GSUB lookup subtables.

type GeneralCategory added in v0.0.4

type GeneralCategory uint8

GeneralCategory represents the Unicode General_Category property. HarfBuzz equivalent: hb_unicode_general_category_t in hb-unicode.h

The values are ordered to match HarfBuzz's enum for compatibility.

const (
	GCControl            GeneralCategory = iota // Cc
	GCFormat                                    // Cf
	GCUnassigned                                // Cn
	GCPrivateUse                                // Co
	GCSurrogate                                 // Cs
	GCLowercaseLetter                           // Ll
	GCModifierLetter                            // Lm
	GCOtherLetter                               // Lo
	GCTitlecaseLetter                           // Lt
	GCUppercaseLetter                           // Lu
	GCSpacingMark                               // Mc
	GCEnclosingMark                             // Me
	GCNonSpacingMark                            // Mn
	GCDecimalNumber                             // Nd
	GCLetterNumber                              // Nl
	GCOtherNumber                               // No
	GCConnectPunctuation                        // Pc
	GCDashPunctuation                           // Pd
	GCClosePunctuation                          // Pe
	GCFinalPunctuation                          // Pf
	GCInitialPunctuation                        // Pi
	GCOtherPunctuation                          // Po
	GCOpenPunctuation                           // Ps
	GCCurrencySymbol                            // Sc
	GCModifierSymbol                            // Sk
	GCMathSymbol                                // Sm
	GCOtherSymbol                               // So
	GCLineSeparator                             // Zl
	GCParagraphSeparator                        // Zp
	GCSpaceSeparator                            // Zs
)

type Glyf

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

Glyf represents the parsed glyf table (glyph data).

func ParseGlyf

func ParseGlyf(data []byte, loca *Loca) (*Glyf, error)

ParseGlyf parses the glyf table using a loca table.

func ParseGlyfFromFont

func ParseGlyfFromFont(font *Font) (*Glyf, error)

ParseGlyfFromFont parses both glyf and loca tables from a font.

func (*Glyf) GetComponents

func (g *Glyf) GetComponents(gid GlyphID) []GlyphID

GetComponents returns the component glyph IDs for a composite glyph. For simple glyphs, returns nil.

func (*Glyf) GetContourPointCount added in v0.0.6

func (g *Glyf) GetContourPointCount(gid GlyphID) int

GetContourPointCount returns the number of contour points for a glyph. For empty glyphs (like space) returns 0. For simple glyphs returns the number of outline points. For composite glyphs, recursively counts component points. HarfBuzz equivalent: get_points() in OT/glyf/Glyph.hh

func (*Glyf) GetGlyph

func (g *Glyf) GetGlyph(gid GlyphID) *GlyphData

GetGlyph returns the glyph data for a glyph ID.

func (*Glyf) GetGlyphBytes

func (g *Glyf) GetGlyphBytes(gid GlyphID) []byte

GetGlyphBytes returns the raw bytes for a glyph.

func (*Glyf) GetGlyphExtents added in v0.0.4

func (g *Glyf) GetGlyphExtents(gid GlyphID) (GlyphExtents, bool)

GetGlyphExtents returns the extents (bounding box) for a glyph. Returns false if the glyph has no outline (e.g., space) or doesn't exist.

type GlyphData

type GlyphData struct {
	Data             []byte
	NumberOfContours int16 // -1 for composite, >= 0 for simple
}

GlyphData represents the raw data for a single glyph.

func (*GlyphData) IsComposite

func (gd *GlyphData) IsComposite() bool

IsComposite returns true if the glyph is a composite glyph.

type GlyphDeltas added in v0.0.3

type GlyphDeltas struct {
	// XDeltas and YDeltas contain the accumulated delta values for each point.
	// The length matches the number of points in the glyph (including phantom points).
	// float64 is used for precision during accumulation across multiple tuple variations.
	XDeltas []float64
	YDeltas []float64
}

GlyphDeltas represents the variation deltas for a single glyph.

type GlyphExtents

type GlyphExtents struct {
	XBearing int16 // Left side of glyph from origin
	YBearing int16 // Top side of glyph from origin
	Width    int16 // Width of glyph
	Height   int16 // Height of glyph (usually negative)
}

GlyphExtents contains glyph extent values.

type GlyphID

type GlyphID = uint16

GlyphID represents a glyph index.

type GlyphInfo

type GlyphInfo struct {
	Codepoint  Codepoint // Original Unicode codepoint (0 if synthetic)
	GlyphID    GlyphID   // Glyph index in the font
	Cluster    int       // Cluster index (maps back to original text position)
	GlyphClass int       // GDEF glyph class (if available)
	Mask       uint32    // Feature mask - determines which features apply to this glyph

	// GlyphProps holds glyph properties for GSUB/GPOS processing.
	// HarfBuzz equivalent: glyph_props() in hb-ot-layout.hh
	// Flags:
	//   0x02 = BASE_GLYPH (from GDEF class 1)
	//   0x04 = LIGATURE (from GDEF class 2)
	//   0x08 = MARK (from GDEF class 3)
	//   0x10 = SUBSTITUTED (glyph was substituted by GSUB)
	//   0x20 = LIGATED (glyph is result of ligature substitution)
	//   0x40 = MULTIPLIED (glyph is component of multiple substitution)
	GlyphProps uint16

	// LigProps holds ligature properties (lig_id and lig_comp).
	// HarfBuzz equivalent: lig_props() in hb-ot-layout.hh
	// Upper 3 bits: lig_id (identifies which ligature this belongs to)
	// Lower 5 bits: lig_comp (component index within ligature, 0 = the ligature itself)
	LigProps uint8

	// Syllable holds the syllable index for complex script shaping.
	// HarfBuzz equivalent: syllable() in hb-buffer.hh
	// Used by Indic, Khmer, Myanmar, USE shapers to constrain GSUB lookups
	// to operate only within syllable boundaries (F_PER_SYLLABLE flag).
	Syllable uint8

	// ModifiedCCC holds an overridden combining class, used by Arabic reorder_marks.
	// HarfBuzz equivalent: _hb_glyph_info_set_modified_combining_class()
	// When non-zero, this value is used instead of the standard Unicode CCC.
	// Arabic MCMs (modifier combining marks) get their CCC changed to 22/26
	// after being reordered to the beginning of the mark sequence.
	ModifiedCCC uint8

	// IndicCategory holds the Indic character category for Indic shaping.
	// HarfBuzz equivalent: indic_category() stored in var1 via HB_BUFFER_ALLOCATE_VAR
	// This is preserved through GSUB substitutions because GlyphInfo is copied as a whole.
	IndicCategory uint8

	// IndicPosition holds the Indic character position for Indic shaping.
	// HarfBuzz equivalent: indic_position() stored in var1 via HB_BUFFER_ALLOCATE_VAR
	// This is preserved through GSUB substitutions because GlyphInfo is copied as a whole.
	IndicPosition uint8

	// ArabicShapingAction holds the Arabic shaping action for STCH (stretching) feature.
	// HarfBuzz equivalent: arabic_shaping_action() stored via ot_shaper_var_u8_auxiliary()
	// Values: arabicActionSTCH_FIXED, arabicActionSTCH_REPEATING (set by recordStch)
	ArabicShapingAction uint8

	// MyanmarCategory holds the Myanmar character category for Myanmar shaping.
	// HarfBuzz equivalent: myanmar_category() stored via ot_shaper_var_u8_category()
	MyanmarCategory uint8

	// MyanmarPosition holds the Myanmar character position for Myanmar shaping.
	// HarfBuzz equivalent: myanmar_position() stored via ot_shaper_var_u8_auxiliary()
	MyanmarPosition uint8

	// USECategory holds the USE character category for USE shaping.
	// HarfBuzz equivalent: use_category() stored in var2.u8[3] via HB_BUFFER_ALLOCATE_VAR
	// Stored directly on GlyphInfo so it survives GSUB operations.
	USECategory uint8

	// HangulFeature holds the Hangul Jamo feature type for Hangul shaping.
	// HarfBuzz equivalent: hangul_shaping_feature() stored via ot_shaper_var_u8_auxiliary()
	// Values: 0=none, 1=LJMO, 2=VJMO, 3=TJMO
	HangulFeature uint8
}

GlyphInfo holds information about a shaped glyph. HarfBuzz equivalent: hb_glyph_info_t in hb-buffer.h

func (*GlyphInfo) GetLigComp added in v0.0.4

func (g *GlyphInfo) GetLigComp() uint8

GetLigComp returns the ligature component index for this glyph. Returns 0 if this is the ligature itself (IS_LIG_BASE set). HarfBuzz equivalent: _hb_glyph_info_get_lig_comp() in hb-ot-layout.hh:493

func (*GlyphInfo) GetLigID added in v0.0.4

func (g *GlyphInfo) GetLigID() uint8

GetLigID returns the ligature ID for this glyph. HarfBuzz equivalent: _hb_glyph_info_get_lig_id() in hb-ot-layout.hh:481

func (*GlyphInfo) GetLigNumComps added in v0.0.4

func (g *GlyphInfo) GetLigNumComps() int

GetLigNumComps returns the number of components in a ligature. HarfBuzz equivalent: _hb_glyph_info_get_lig_num_comps() in hb-ot-layout.hh:501

func (*GlyphInfo) IsBaseGlyph added in v0.0.4

func (g *GlyphInfo) IsBaseGlyph() bool

IsBaseGlyph returns true if this glyph is a base glyph (GDEF class 1). HarfBuzz equivalent: _hb_glyph_info_is_base_glyph() in hb-ot-layout.hh:537

func (*GlyphInfo) IsLigated added in v0.0.4

func (g *GlyphInfo) IsLigated() bool

IsLigated returns true if this glyph is the result of a ligature substitution. HarfBuzz equivalent: _hb_glyph_info_ligated() in hb-ot-layout.hh:561

func (*GlyphInfo) IsLigature added in v0.0.4

func (g *GlyphInfo) IsLigature() bool

IsLigature returns true if this glyph is a ligature (GDEF class 2). HarfBuzz equivalent: _hb_glyph_info_is_ligature() in hb-ot-layout.hh:543

func (*GlyphInfo) IsMark added in v0.0.4

func (g *GlyphInfo) IsMark() bool

IsMark returns true if this glyph is a mark (GDEF class 3). HarfBuzz equivalent: _hb_glyph_info_is_mark() in hb-ot-layout.hh:549

func (*GlyphInfo) IsMultiplied added in v0.0.4

func (g *GlyphInfo) IsMultiplied() bool

IsMultiplied returns true if this glyph is a component of a multiple substitution. HarfBuzz equivalent: _hb_glyph_info_multiplied() in hb-ot-layout.hh:565

func (*GlyphInfo) SetLigPropsForComponent added in v0.0.4

func (g *GlyphInfo) SetLigPropsForComponent(compIdx int)

SetLigPropsForComponent sets lig_props for a component of a multiple substitution. HarfBuzz equivalent: _hb_glyph_info_set_lig_props_for_component() in hb-ot-layout.hh:475 which calls _hb_glyph_info_set_lig_props_for_mark(info, 0, comp)

func (*GlyphInfo) SetLigPropsForLigature added in v0.0.4

func (g *GlyphInfo) SetLigPropsForLigature(ligID uint8, numComps int)

SetLigPropsForLigature sets lig_props for a ligature glyph. HarfBuzz equivalent: _hb_glyph_info_set_lig_props_for_ligature() in hb-ot-layout.hh:459

func (*GlyphInfo) SetLigPropsForMark added in v0.0.4

func (g *GlyphInfo) SetLigPropsForMark(ligID uint8, ligComp int)

SetLigPropsForMark sets lig_props for a mark glyph attached to a ligature. HarfBuzz equivalent: _hb_glyph_info_set_lig_props_for_mark() in hb-ot-layout.hh:467

type GlyphOutline added in v0.0.7

type GlyphOutline struct {
	Segments []Segment
}

GlyphOutline contains the path segments for a glyph's outline.

type GlyphPoint added in v0.0.3

type GlyphPoint struct {
	X, Y int16
}

GlyphPoint represents a point for IUP interpolation.

type GlyphPos

type GlyphPos struct {
	XAdvance int16 // Horizontal advance
	YAdvance int16 // Vertical advance
	XOffset  int16 // Horizontal offset
	YOffset  int16 // Vertical offset

	// Attachment chain for mark/cursive positioning.
	// HarfBuzz: var.i16[0] via attach_chain() macro in OT/Layout/GPOS/Common.hh
	// Relative offset to attached glyph: negative = backwards, positive = forward.
	// Zero means no attachment.
	AttachChain int16

	// Attachment type for mark/cursive positioning.
	// HarfBuzz: var.u8[2] via attach_type() macro in OT/Layout/GPOS/Common.hh
	AttachType uint8
}

GlyphPos holds positioning information for a shaped glyph. HarfBuzz equivalent: hb_glyph_position_t in hb-buffer.h

type Gvar added in v0.0.3

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

Gvar represents a parsed gvar (Glyph Variations) table. It contains variation data for TrueType glyph outlines.

func ParseGvar added in v0.0.3

func ParseGvar(data []byte) (*Gvar, error)

ParseGvar parses a gvar table.

func (*Gvar) AxisCount added in v0.0.3

func (g *Gvar) AxisCount() int

AxisCount returns the number of variation axes.

func (*Gvar) GetGlyphDeltas added in v0.0.3

func (g *Gvar) GetGlyphDeltas(glyphID GlyphID, normalizedCoords []int, numPoints int) *GlyphDeltas

GetGlyphDeltas computes the delta values for a glyph at the given normalized coordinates. The coordinates should be in F2DOT14 format. numPoints is the number of points in the glyph (including 4 phantom points). Note: This version doesn't perform proper IUP interpolation for sparse deltas. Use GetGlyphDeltasWithCoords for proper IUP support.

func (*Gvar) GetGlyphDeltasWithCoords added in v0.0.3

func (g *Gvar) GetGlyphDeltasWithCoords(glyphID GlyphID, normalizedCoords []int, numPoints int, origCoords []GlyphPoint) *GlyphDeltas

GetGlyphDeltasWithCoords computes the delta values for a glyph at the given normalized coordinates with proper IUP interpolation. origCoords contains the original point coordinates for IUP interpolation. If nil, a simplified interpolation is used.

func (*Gvar) GlyphCount added in v0.0.3

func (g *Gvar) GlyphCount() int

GlyphCount returns the number of glyphs with variation data.

func (*Gvar) HasData added in v0.0.3

func (g *Gvar) HasData() bool

HasData returns true if the gvar table has valid data.

type Head struct {
	Version            uint32
	FontRevision       uint32
	CheckSumAdjustment uint32
	MagicNumber        uint32
	Flags              uint16
	UnitsPerEm         uint16
	Created            int64
	Modified           int64
	XMin               int16
	YMin               int16
	XMax               int16
	YMax               int16
	MacStyle           uint16
	LowestRecPPEM      uint16
	FontDirectionHint  int16
	IndexToLocFormat   int16
	GlyphDataFormat    int16
}

Head represents the font header table.

func ParseHead

func ParseHead(data []byte) (*Head, error)

ParseHead parses the head table.

type Hhea

type Hhea struct {
	Version             uint32
	Ascender            int16
	Descender           int16
	LineGap             int16
	AdvanceWidthMax     uint16
	MinLeftSideBearing  int16
	MinRightSideBearing int16
	XMaxExtent          int16
	CaretSlopeRise      int16
	CaretSlopeRun       int16
	CaretOffset         int16
	MetricDataFormat    int16
	NumberOfHMetrics    uint16
}

Hhea represents the horizontal header table.

func ParseHhea

func ParseHhea(data []byte) (*Hhea, error)

ParseHhea parses the hhea (horizontal header) table.

type Hmtx

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

Hmtx represents the horizontal metrics table.

func ParseHmtx

func ParseHmtx(data []byte, numberOfHMetrics, numGlyphs int) (*Hmtx, error)

ParseHmtx parses the hmtx table. It requires numberOfHMetrics from hhea and numGlyphs from maxp.

func ParseHmtxFromFont

func ParseHmtxFromFont(font *Font) (*Hmtx, error)

ParseHmtxFromFont is a convenience function that parses hmtx from a font, automatically reading hhea and maxp for required values.

func (*Hmtx) GetAdvanceWidth

func (h *Hmtx) GetAdvanceWidth(glyph GlyphID) uint16

GetAdvanceWidth returns the advance width for a glyph.

func (*Hmtx) GetLsb

func (h *Hmtx) GetLsb(glyph GlyphID) int16

GetLsb returns the left side bearing for a glyph.

func (*Hmtx) GetMetrics

func (h *Hmtx) GetMetrics(glyph GlyphID) (advanceWidth uint16, lsb int16)

GetMetrics returns both advance width and lsb for a glyph.

type Hvar added in v0.0.3

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

Hvar represents a parsed HVAR (Horizontal Metrics Variations) table. It allows adjusting glyph advances based on variation axis settings.

func ParseHvar added in v0.0.3

func ParseHvar(data []byte) (*Hvar, error)

ParseHvar parses an HVAR table.

func (*Hvar) GetAdvanceDelta added in v0.0.3

func (h *Hvar) GetAdvanceDelta(glyph GlyphID, normalizedCoords []int) float64

GetAdvanceDelta returns the advance delta for a glyph at the given normalized coordinates. The coordinates should be in F2DOT14 format (scaled by 16384, where 1.0 = 16384).

func (*Hvar) HasData added in v0.0.3

func (h *Hvar) HasData() bool

HasData returns true if the HVAR table has valid data.

type IndicCategory added in v0.0.4

type IndicCategory uint8

IndicCategory represents the category of an Indic character. HarfBuzz equivalent: indic_category_t in hb-ot-shaper-indic-machine.hh

const (
	ICatX            IndicCategory = 0  // Other
	ICatC            IndicCategory = 1  // Consonant
	ICatV            IndicCategory = 2  // Vowel
	ICatN            IndicCategory = 3  // Nukta
	ICatH            IndicCategory = 4  // Halant/Virama
	ICatZWNJ         IndicCategory = 5  // Zero Width Non-Joiner
	ICatZWJ          IndicCategory = 6  // Zero Width Joiner
	ICatM            IndicCategory = 7  // Matra (vowel sign)
	ICatSM           IndicCategory = 8  // Syllable Modifier (anusvara, visarga)
	ICatA            IndicCategory = 9  // Vedic Accent / VD (Vedic Sign)
	ICatPLACEHOLDER  IndicCategory = 10 // Placeholder (number, etc.)
	ICatDOTTEDCIRCLE IndicCategory = 11 // Dotted Circle (U+25CC)
	ICatRS           IndicCategory = 12 // Reordering Spacing Mark (rare)
	ICatMPst         IndicCategory = 13 // Post-base Matra
	ICatRepha        IndicCategory = 14 // Repha (Malayalam)
	ICatRa           IndicCategory = 15 // Ra consonant (special for Reph formation)
	ICatCM           IndicCategory = 16 // Consonant Medial
	ICatSymbol       IndicCategory = 17 // Symbol
	ICatCS           IndicCategory = 18 // Consonant with Stacker
	ICatSMPst        IndicCategory = 57 // Post-base Syllable Modifier
)

func GetIndicCategory added in v0.0.4

func GetIndicCategory(cp Codepoint) IndicCategory

GetIndicCategory returns the Indic category for a codepoint.

type IndicConfig added in v0.0.4

type IndicConfig struct {
	Script Tag

	// Virama codepoint for this script (halant/virama)
	Virama Codepoint

	// HasOldSpec indicates if this script uses old Indic spec shaping
	// (pre-OpenType 1.8 behavior)
	HasOldSpec bool

	// RephPos indicates where reph should be positioned
	RephPos IndicPosition

	// RephMode indicates how reph is formed
	RephMode RephMode

	// BlwfMode indicates how below-forms are handled
	BlwfMode BlwfMode

	// BasePos indicates how to find the base consonant
	BasePos BasePos
}

IndicConfig holds script-specific configuration. HarfBuzz equivalent: indic_config_t in hb-ot-shaper-indic.hh

type IndicFeatureIndex added in v0.0.4

type IndicFeatureIndex int

IndicFeatureIndex is an index into the indicFeatures array and maskArray. HarfBuzz equivalent: enum in hb-ot-shaper-indic.cc:202-223 Must be in the same order as indicFeatures array.

type IndicInfo added in v0.0.4

type IndicInfo struct {
	Category IndicCategory
	Position IndicPosition
	Syllable uint8 // Syllable index (serial << 4 | type)
}

IndicInfo holds the Indic category and position for a glyph. This is stored in GlyphInfo as additional shaping data.

type IndicPlan added in v0.0.4

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

IndicPlan holds pre-computed data for Indic shaping. HarfBuzz equivalent: indic_shape_plan_t in hb-ot-shaper-indic.cc:289-308

type IndicPosition added in v0.0.4

type IndicPosition uint8

IndicPosition represents the visual position of a character in a syllable. HarfBuzz equivalent: ot_position_t in hb-ot-shaper-indic.hh

const (
	IPosStart      IndicPosition = 0
	IPosRaToBeReph IndicPosition = 1  // Ra that will become Reph
	IPosPreM       IndicPosition = 2  // Pre-base Matra
	IPosPreC       IndicPosition = 3  // Pre-base Consonant
	IPosBaseC      IndicPosition = 4  // Base Consonant
	IPosAfterMain  IndicPosition = 5  // After main consonant
	IPosAboveC     IndicPosition = 6  // Above base consonant
	IPosBeforeSub  IndicPosition = 7  // Before sub-joined consonant
	IPosBelowC     IndicPosition = 8  // Below base consonant
	IPosAfterSub   IndicPosition = 9  // After sub-joined consonant
	IPosBeforePost IndicPosition = 10 // Before post-base consonant
	IPosPostC      IndicPosition = 11 // Post-base Consonant
	IPosAfterPost  IndicPosition = 12 // After post-base consonant
	IPosSMVD       IndicPosition = 13 // Syllable Modifier / Vedic
	IPosEnd        IndicPosition = 14
)

type IndicShapingInfo added in v0.0.4

type IndicShapingInfo struct {
	Category IndicCategory
	Position IndicPosition
	Syllable uint8
}

IndicShapingInfo holds per-glyph shaping information.

type IndicSyllableType added in v0.0.4

type IndicSyllableType uint8

IndicSyllableType represents the type of Indic syllable. HarfBuzz equivalent: indic_syllable_type_t

const (
	IndicConsonantSyllable IndicSyllableType = 0
	IndicVowelSyllable     IndicSyllableType = 1
	IndicStandaloneCluster IndicSyllableType = 2
	IndicSymbolCluster     IndicSyllableType = 3
	IndicBrokenCluster     IndicSyllableType = 4
	IndicNonIndicCluster   IndicSyllableType = 5
)

type ItemVariationStore added in v0.0.3

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

ItemVariationStore holds variation data for different regions.

func (*ItemVariationStore) GetDelta added in v0.0.3

func (vs *ItemVariationStore) GetDelta(varIdx uint32, coords []int) float64

GetDelta returns the delta value for a variation index at the given normalized coordinates.

type JoiningForm added in v0.0.4

type JoiningForm uint8

JoiningForm represents the joining form for topographical features.

const (
	JoiningFormIsol JoiningForm = iota
	JoiningFormInit
	JoiningFormMedi
	JoiningFormFina
	JoiningFormNone
)

type JoiningType added in v0.0.4

type JoiningType uint8

JoiningType represents the Arabic joining behavior of a character.

func GetJoiningTypeDebug added in v0.0.4

func GetJoiningTypeDebug(u Codepoint) JoiningType

GetJoiningTypeDebug returns the joining type for a Unicode codepoint (exported for debugging).

type Kern added in v0.0.4

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

Kern represents the TrueType 'kern' table. This provides kerning as a fallback when GPOS is not available.

func ParseKern added in v0.0.4

func ParseKern(data []byte, numGlyphs int) (*Kern, error)

ParseKern parses a TrueType kern table.

func (*Kern) HasKerning added in v0.0.4

func (k *Kern) HasKerning() bool

HasKerning returns true if any kerning data is available.

func (*Kern) KernPair added in v0.0.4

func (k *Kern) KernPair(left, right GlyphID) int16

KernPair returns the kerning value for a glyph pair. It checks all subtables and returns the first non-zero value.

type KhmerCategory added in v0.0.4

type KhmerCategory uint8

KhmerCategory represents character categories for Khmer shaping. These values match HarfBuzz's hb-ot-shaper-khmer-machine.rl

const (
	K_Other        KhmerCategory = 0  // Non-Khmer characters (default)
	K_C            KhmerCategory = 1  // Consonant
	K_V            KhmerCategory = 2  // Independent vowel
	K_N            KhmerCategory = 3  // Number (not in Ragel, but we need it)
	K_H            KhmerCategory = 4  // Coeng (halant equivalent)
	K_ZWNJ         KhmerCategory = 5  // Zero-width non-joiner
	K_ZWJ          KhmerCategory = 6  // Zero-width joiner
	K_Placeholder  KhmerCategory = 10 // Placeholder
	K_DottedCircle KhmerCategory = 11 // Dotted circle
	K_Ra           KhmerCategory = 15 // Ra (special treatment for Robatic)
	K_VAbv         KhmerCategory = 20 // Vowel above
	K_VBlw         KhmerCategory = 21 // Vowel below
	K_VPre         KhmerCategory = 22 // Vowel pre (left)
	K_VPst         KhmerCategory = 23 // Vowel post (right)
	K_Robatic      KhmerCategory = 25 // Robatic consonants
	K_Xgroup       KhmerCategory = 26 // Consonant modifiers above
	K_Ygroup       KhmerCategory = 27 // Consonant modifiers post
)

type KhmerSyllableType added in v0.0.4

type KhmerSyllableType uint8

KhmerSyllableType defines syllable types for Khmer.

const (
	KhmerConsonantSyllable KhmerSyllableType = iota
	KhmerBrokenCluster
	KhmerNonKhmerCluster
)

type LangSys added in v0.0.4

type LangSys struct {
	RequiredFeature int      // -1 if none
	FeatureIndices  []uint16 // indices into FeatureList
}

LangSys represents a Language System table with its feature indices.

type LigCaretList

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

LigCaretList contains ligature caret positions.

type LigGlyph

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

LigGlyph contains caret values for a ligature glyph.

type Ligature

type Ligature struct {
	LigGlyph   GlyphID   // The resulting ligature glyph
	Components []GlyphID // Component glyphs (starting from second)
}

Ligature represents a single ligature rule.

type LigatureArray

type LigatureArray struct {
	Attachments []*LigatureAttach
}

LigatureArray contains LigatureAttach tables for multiple ligatures.

type LigatureAttach

type LigatureAttach struct {
	ComponentCount int         // Number of ligature components
	ClassCount     int         // Number of mark classes
	Anchors        [][]*Anchor // [component][class] -> Anchor (may be nil)
}

LigatureAttach contains anchors for one ligature glyph. It's organized as a matrix where: - Rows correspond to ligature components (in writing order) - Columns correspond to mark classes

func (*LigatureAttach) GetAnchor

func (la *LigatureAttach) GetAnchor(componentIndex, markClass int) *Anchor

GetAnchor returns the anchor for a given component index and mark class.

type LigatureSubst

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

LigatureSubst represents a Ligature Substitution subtable.

func (*LigatureSubst) Apply

func (l *LigatureSubst) Apply(ctx *OTApplyContext) int

Apply applies the ligature substitution.

func (*LigatureSubst) Coverage

func (l *LigatureSubst) Coverage() *Coverage

Coverage returns the coverage table.

func (*LigatureSubst) LigatureSets

func (l *LigatureSubst) LigatureSets() [][]Ligature

LigatureSets returns the ligature sets.

type Loca

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

Loca represents the parsed loca table (index to location).

func ParseLoca

func ParseLoca(data []byte, numGlyphs int, indexToLocFormat int16) (*Loca, error)

ParseLoca parses the loca table. indexToLocFormat: 0 = short (16-bit), 1 = long (32-bit)

func (*Loca) GetOffset

func (l *Loca) GetOffset(gid GlyphID) (uint32, uint32, bool)

GetOffset returns the offset and length for a glyph. Returns (offset, length, ok)

func (*Loca) IsShort

func (l *Loca) IsShort() bool

IsShort returns true if using short (16-bit) format.

func (*Loca) NumGlyphs

func (l *Loca) NumGlyphs() int

NumGlyphs returns the number of glyphs.

type LongHorMetric

type LongHorMetric struct {
	AdvanceWidth uint16
	Lsb          int16 // Left side bearing
}

LongHorMetric contains the advance width and left side bearing for a glyph.

type LongVerMetric added in v0.0.6

type LongVerMetric struct {
	AdvanceHeight uint16
	Tsb           int16 // Top side bearing
}

LongVerMetric contains the advance height and top side bearing for a glyph.

type LookupMap added in v0.0.4

type LookupMap struct {
	Index       uint16 // Lookup index in GSUB/GPOS table
	Mask        uint32 // Feature mask - only apply to glyphs where (glyph.mask & mask) != 0
	FeatureTag  Tag    // The feature tag this lookup belongs to
	AutoZWNJ    bool   // Automatically handle ZWNJ (Zero Width Non-Joiner)
	AutoZWJ     bool   // Automatically handle ZWJ (Zero Width Joiner)
	Random      bool   // Random feature (for 'rand' feature)
	PerSyllable bool   // Apply per syllable (for Indic/USE shapers)
}

LookupMap represents a single lookup with its associated properties. HarfBuzz equivalent: hb_ot_map_t::lookup_map_t in hb-ot-map.hh:72-87

type LookupRecord

type LookupRecord struct {
	SequenceIndex uint16 // Index into current glyph sequence (0-based)
	LookupIndex   uint16 // Lookup to apply
}

LookupRecord specifies a lookup to apply at a specific position.

type MarkArray

type MarkArray struct {
	Records []MarkRecord
}

MarkArray contains an array of MarkRecords.

type MarkBasePos

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

MarkBasePos represents a Mark-to-Base Attachment subtable (GPOS Type 4). It positions mark glyphs relative to base glyphs using anchor points.

func (*MarkBasePos) Apply

func (m *MarkBasePos) Apply(ctx *OTApplyContext) bool

HarfBuzz equivalent: MarkBasePosFormat1_2::apply in OT/Layout/GPOS/MarkBasePosFormat1.hh

func (*MarkBasePos) BaseArray

func (m *MarkBasePos) BaseArray() *BaseArray

BaseArray returns the base array.

func (*MarkBasePos) BaseCoverage

func (m *MarkBasePos) BaseCoverage() *Coverage

BaseCoverage returns the base coverage table.

func (*MarkBasePos) ClassCount

func (m *MarkBasePos) ClassCount() uint16

ClassCount returns the number of mark classes.

func (*MarkBasePos) MarkArray

func (m *MarkBasePos) MarkArray() *MarkArray

MarkArray returns the mark array.

func (*MarkBasePos) MarkCoverage

func (m *MarkBasePos) MarkCoverage() *Coverage

MarkCoverage returns the mark coverage table.

type MarkGlyphSetsDef

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

MarkGlyphSetsDef contains mark glyph set definitions.

type MarkLigPos

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

MarkLigPos represents a Mark-to-Ligature Attachment subtable (GPOS Type 5). It positions mark glyphs relative to ligature glyphs. Each ligature can have multiple components, and each component has its own anchor points.

func (*MarkLigPos) Apply

func (m *MarkLigPos) Apply(ctx *OTApplyContext) bool

Apply applies the mark-to-ligature positioning. HarfBuzz equivalent: MarkLigPosFormat1_2::apply() in OT/Layout/GPOS/MarkLigPosFormat1.hh:95-166

This searches backwards for a non-mark glyph (the ligature base), determines which ligature component the mark belongs to using lig_id/lig_comp, then positions the mark at the appropriate component anchor.

func (*MarkLigPos) ClassCount

func (m *MarkLigPos) ClassCount() uint16

ClassCount returns the number of mark classes.

func (*MarkLigPos) LigatureArray

func (m *MarkLigPos) LigatureArray() *LigatureArray

LigatureArray returns the ligature array.

func (*MarkLigPos) LigatureCoverage

func (m *MarkLigPos) LigatureCoverage() *Coverage

LigatureCoverage returns the ligature coverage table.

func (*MarkLigPos) MarkArray

func (m *MarkLigPos) MarkArray() *MarkArray

MarkArray returns the mark array.

func (*MarkLigPos) MarkCoverage

func (m *MarkLigPos) MarkCoverage() *Coverage

MarkCoverage returns the mark coverage table.

type MarkMarkPos

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

MarkMarkPos represents a Mark-to-Mark Attachment subtable (GPOS Type 6). It positions mark glyphs (mark1) relative to preceding mark glyphs (mark2). This is used for stacking diacritics, e.g., placing an accent on top of another accent.

func (*MarkMarkPos) Apply

func (m *MarkMarkPos) Apply(ctx *OTApplyContext) bool

Apply applies the mark-to-mark positioning. It finds the preceding mark glyph (mark2) and positions the current mark (mark1) relative to it.

func (*MarkMarkPos) ClassCount

func (m *MarkMarkPos) ClassCount() uint16

ClassCount returns the number of mark classes.

func (*MarkMarkPos) Mark1Array

func (m *MarkMarkPos) Mark1Array() *MarkArray

Mark1Array returns the mark array for mark1 glyphs.

func (*MarkMarkPos) Mark1Coverage

func (m *MarkMarkPos) Mark1Coverage() *Coverage

Mark1Coverage returns the coverage table for the attaching mark (mark1).

func (*MarkMarkPos) Mark2Array

func (m *MarkMarkPos) Mark2Array() *BaseArray

Mark2Array returns the anchor array for mark2 glyphs.

func (*MarkMarkPos) Mark2Coverage

func (m *MarkMarkPos) Mark2Coverage() *Coverage

Mark2Coverage returns the coverage table for the base mark (mark2).

type MarkRecord

type MarkRecord struct {
	Class  uint16  // Mark class
	Anchor *Anchor // Anchor for this mark
}

MarkRecord associates a mark glyph with a class and anchor.

type MayMatchResult added in v0.0.4

type MayMatchResult int

MayMatchResult represents the result of may_match(). HarfBuzz equivalent: may_match_t in matcher_t

const (
	MatchNo    MayMatchResult = iota // Definitely no match
	MatchYes                         // Definitely a match
	MatchMaybe                       // Maybe a match (needs further check)
)

type MaySkipResult added in v0.0.4

type MaySkipResult int

MaySkipResult represents the result of may_skip(). HarfBuzz equivalent: may_skip_t in matcher_t

const (
	SkipNo    MaySkipResult = iota // Don't skip
	SkipYes                        // Skip this glyph
	SkipMaybe                      // Maybe skip (default ignorable)
)

type MultipleSubst

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

MultipleSubst represents a Multiple Substitution subtable (1 -> n).

func (*MultipleSubst) Apply

func (m *MultipleSubst) Apply(ctx *OTApplyContext) int

Apply applies the multiple substitution.

func (*MultipleSubst) Mapping

func (m *MultipleSubst) Mapping() map[GlyphID][]GlyphID

Mapping returns the input->output mapping for glyph closure computation.

type MyanmarCategory added in v0.0.4

type MyanmarCategory uint8

MyanmarCategory represents character categories for Myanmar shaping. These values match HarfBuzz's hb-ot-shaper-myanmar-machine.rl exports. HarfBuzz equivalent: myanmar_category_t

const (
	M_Other        MyanmarCategory = 0  // Non-Myanmar characters
	M_C            MyanmarCategory = 1  // Consonant
	M_IV           MyanmarCategory = 2  // Independent vowel
	M_DB           MyanmarCategory = 3  // Dot below
	M_H            MyanmarCategory = 4  // Halant (Myanmar virama U+1039)
	M_ZWNJ         MyanmarCategory = 5  // Zero-width non-joiner
	M_ZWJ          MyanmarCategory = 6  // Zero-width joiner
	M_SM           MyanmarCategory = 8  // Visarga and Shan tones
	M_A            MyanmarCategory = 9  // Anusvara
	M_GB           MyanmarCategory = 10 // Placeholder (generic base)
	M_DottedCircle MyanmarCategory = 11 // Dotted circle
	M_Ra           MyanmarCategory = 15 // Myanmar Ra (U+101B)
	M_CS           MyanmarCategory = 18 // Consonant preceding Kinzi
	M_VAbv         MyanmarCategory = 20 // Vowel above
	M_VBlw         MyanmarCategory = 21 // Vowel below
	M_VPre         MyanmarCategory = 22 // Vowel pre (left)
	M_VPst         MyanmarCategory = 23 // Vowel post (right)
	M_As           MyanmarCategory = 32 // Asat (U+103A)
	M_MH           MyanmarCategory = 35 // Medial Ha (U+103E)
	M_MR           MyanmarCategory = 36 // Medial Ra (U+103C)
	M_MW           MyanmarCategory = 37 // Medial Wa, Shan Wa (U+103D, U+1082)
	M_MY           MyanmarCategory = 38 // Medial Ya, Mon Na, Mon Ma (U+103B, U+105E, U+105F)
	M_PT           MyanmarCategory = 39 // Pwo and other tones
	M_VS           MyanmarCategory = 40 // Variation selectors
	M_ML           MyanmarCategory = 41 // Medial Mon La (U+1060)
	M_SMPst        MyanmarCategory = 57 // Post-syllable SM
)

type MyanmarPosition added in v0.0.4

type MyanmarPosition uint8

MyanmarPosition represents visual positions in a syllable. HarfBuzz equivalent: ot_position_t in hb-ot-shaper-indic.hh

const (
	M_POS_START             MyanmarPosition = 0
	M_POS_RA_TO_BECOME_REPH MyanmarPosition = 1
	M_POS_PRE_M             MyanmarPosition = 2
	M_POS_PRE_C             MyanmarPosition = 3
	M_POS_BASE_C            MyanmarPosition = 4
	M_POS_AFTER_MAIN        MyanmarPosition = 5
	M_POS_ABOVE_C           MyanmarPosition = 6
	M_POS_BEFORE_SUB        MyanmarPosition = 7
	M_POS_BELOW_C           MyanmarPosition = 8
	M_POS_AFTER_SUB         MyanmarPosition = 9
	M_POS_BEFORE_POST       MyanmarPosition = 10
	M_POS_POST_C            MyanmarPosition = 11
	M_POS_AFTER_POST        MyanmarPosition = 12
	M_POS_SMVD              MyanmarPosition = 13
	M_POS_END               MyanmarPosition = 14
)

type MyanmarSyllableType added in v0.0.4

type MyanmarSyllableType uint8

MyanmarSyllableType defines syllable types for Myanmar. HarfBuzz equivalent: myanmar_syllable_type_t

const (
	MyanmarConsonantSyllable MyanmarSyllableType = 0
	MyanmarBrokenCluster     MyanmarSyllableType = 1
	MyanmarNonMyanmarCluster MyanmarSyllableType = 2
)

type Name

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

Name represents the name table.

func ParseName

func ParseName(data []byte) (*Name, error)

ParseName parses the name table.

func (*Name) FamilyName

func (n *Name) FamilyName() string

FamilyName returns the font family name (nameID 1).

func (*Name) FullName

func (n *Name) FullName() string

FullName returns the full font name (nameID 4).

func (*Name) Get

func (n *Name) Get(nameID uint16) string

Get returns the string for a nameID.

func (*Name) PostScriptName

func (n *Name) PostScriptName() string

PostScriptName returns the PostScript name (nameID 6).

type NamedInstance added in v0.0.3

type NamedInstance struct {
	Index            int
	SubfamilyNameID  uint16
	PostScriptNameID uint16 // 0 if not present
	Coords           []float32
}

NamedInstance represents a predefined style like "Bold" or "Light".

type NormalizationMode added in v0.0.4

type NormalizationMode int

NormalizationMode controls how normalization is performed. HarfBuzz equivalent: hb_ot_shape_normalization_mode_t

const (
	// NormalizationModeNone skips normalization
	NormalizationModeNone NormalizationMode = iota
	// NormalizationModeDecomposed keeps characters decomposed (NFD)
	NormalizationModeDecomposed
	// NormalizationModeComposedDiacritics recomposes diacritics but not base-to-base
	NormalizationModeComposedDiacritics
	// NormalizationModeAuto automatically selects mode based on font/shaper
	NormalizationModeAuto
)

type NormalizeContext added in v0.0.4

type NormalizeContext struct {
	Plan   *ShapePlan
	Buffer *Buffer
	Font   *Font
	Shaper *Shaper
}

NormalizeContext provides context for decompose/compose callbacks. HarfBuzz equivalent: hb_ot_shape_normalize_context_t in hb-ot-shape-normalize.hh:54-65

type OS2

type OS2 struct {
	Version             uint16
	XAvgCharWidth       int16
	UsWeightClass       uint16
	UsWidthClass        uint16
	FsType              uint16
	YSubscriptXSize     int16
	YSubscriptYSize     int16
	YSubscriptXOffset   int16
	YSubscriptYOffset   int16
	YSuperscriptXSize   int16
	YSuperscriptYSize   int16
	YSuperscriptXOffset int16
	YSuperscriptYOffset int16
	YStrikeoutSize      int16
	YStrikeoutPosition  int16
	SFamilyClass        int16
	Panose              [10]byte
	UlUnicodeRange1     uint32
	UlUnicodeRange2     uint32
	UlUnicodeRange3     uint32
	UlUnicodeRange4     uint32
	AchVendID           [4]byte
	FsSelection         uint16
	UsFirstCharIndex    uint16
	UsLastCharIndex     uint16
	STypoAscender       int16
	STypoDescender      int16
	STypoLineGap        int16
	UsWinAscent         uint16
	UsWinDescent        uint16
	// Version 1+
	UlCodePageRange1 uint32
	UlCodePageRange2 uint32
	// Version 2+
	SxHeight      int16
	SCapHeight    int16
	UsDefaultChar uint16
	UsBreakChar   uint16
	UsMaxContext  uint16
}

OS2 represents the OS/2 table.

func ParseOS2

func ParseOS2(data []byte) (*OS2, error)

ParseOS2 parses the OS/2 table.

type OTApplyContext added in v0.0.4

type OTApplyContext struct {
	// Core components
	// HarfBuzz: hb_buffer_t *buffer, hb_font_t *font
	Buffer    *Buffer
	Font      *Font
	GDEF      *GDEF
	TableType TableType // 0=GSUB, 1=GPOS

	// Direction for RTL handling
	// HarfBuzz: hb_direction_t direction
	Direction Direction

	// Lookup properties
	// HarfBuzz: hb_mask_t lookup_mask, unsigned lookup_props
	//
	// FeatureMask is the mask for the current feature.
	// HarfBuzz name: lookup_mask
	// Legacy name: FeatureMask (from GSUBContext/GPOSContext)
	// When 0, mask filtering is disabled (applies to all glyphs).
	FeatureMask uint32

	// LookupFlag contains the lookup flags from the lookup table.
	// HarfBuzz name: lookup_props
	// Legacy name: LookupFlag (from GSUBContext/GPOSContext)
	LookupFlag uint16

	// LookupIndex is the current lookup index.
	// HarfBuzz: lookup_index
	LookupIndex int

	// Mark filtering
	// HarfBuzz: Uses lookup_props with MarkFilteringSet flag
	MarkFilteringSet int // Mark filtering set index (-1 if not used)

	// ZWNJ/ZWJ handling
	// HarfBuzz: bool auto_zwnj, bool auto_zwj in hb_ot_apply_context_t:735-736
	AutoZWNJ bool // Automatically handle ZWNJ (default: true)
	AutoZWJ  bool // Automatically handle ZWJ (default: true)

	// Syllable tracking
	// HarfBuzz: bool per_syllable, unsigned new_syllables in hb_ot_apply_context_t:737-739
	PerSyllable   bool  // Apply lookup per-syllable (GSUB only)
	NewSyllables  int   // New syllable value for substituted glyphs (-1 = don't change)
	MatchSyllable uint8 // Reference syllable for per-syllable matching (0 = no constraint)

	// Per-syllable range constraints
	// When PerSyllable is true, these define the valid range for context matching
	RangeStart int // Start of current syllable range (inclusive)
	RangeEnd   int // End of current syllable range (exclusive)

	// Random feature support
	// HarfBuzz: bool random in hb_ot_apply_context_t:738
	Random bool

	// Recursion control
	// HarfBuzz: unsigned nesting_level_left in hb_ot_apply_context_t:732
	NestingLevel int // Current nesting level for nested lookups

	// RecurseFunc is the callback for recursive lookup application.
	// HarfBuzz equivalent: recurse_func_t recurse_func in hb_ot_apply_context_t:733
	// This is set by the caller (GPOS/GSUB) to enable nested lookup calls.
	RecurseFunc func(ctx *OTApplyContext, lookupIndex int) bool

	// Match positions for context/chaining lookups
	// HarfBuzz: hb_vector_t<uint32_t> match_positions
	MatchPositions []int

	// GPOS-specific: last base glyph tracking
	// HarfBuzz: signed last_base, unsigned last_base_until in hb_ot_apply_context_t:741-742
	LastBase      int // Index of last base glyph (-1 if none)
	LastBaseUntil int // Valid until this index

	// Has glyph classes from GDEF
	// HarfBuzz: bool has_glyph_classes
	HasGlyphClasses bool
}

OTApplyContext provides context for applying OpenType lookups. HarfBuzz equivalent: hb_ot_apply_context_t in hb-ot-layout-gsubgpos.hh:678-746

This struct uses HarfBuzz field names but also provides compatibility aliases for the legacy GSUBContext/GPOSContext field names.

func NewOTApplyContext added in v0.0.4

func NewOTApplyContext(tableType TableType, buf *Buffer, font *Font, gdef *GDEF) *OTApplyContext

NewOTApplyContext creates a new apply context. HarfBuzz equivalent: hb_ot_apply_context_t constructor in hb-ot-layout-gsubgpos.hh:747-776

func (*OTApplyContext) AdjustPosition added in v0.0.4

func (ctx *OTApplyContext) AdjustPosition(index int, vr *ValueRecord)

AdjustPosition adjusts the position at the given index with a ValueRecord. HarfBuzz equivalent: applies ValueRecord values directly to position.

func (*OTApplyContext) CheckGlyphProperty added in v0.0.4

func (ctx *OTApplyContext) CheckGlyphProperty(info *GlyphInfo) bool

CheckGlyphProperty checks if a glyph matches the lookup properties. HarfBuzz equivalent: check_glyph_property() in hb-ot-layout-gsubgpos.hh:829-844

func (*OTApplyContext) DeleteGlyph added in v0.0.4

func (ctx *OTApplyContext) DeleteGlyph()

DeleteGlyph deletes the current glyph by skipping it without output. HarfBuzz equivalent: replace_glyphs(1, 0, NULL)

In the output buffer pattern, deletion means: - Consume 1 input glyph (idx++) - Produce 0 output glyphs (no outputGlyph call)

func (*OTApplyContext) IsDefaultIgnorableAt added in v0.0.4

func (ctx *OTApplyContext) IsDefaultIgnorableAt(index int) bool

IsDefaultIgnorableAt returns true if the glyph at index is a default ignorable.

func (*OTApplyContext) IsVariationSelectorAt added in v0.0.4

func (ctx *OTApplyContext) IsVariationSelectorAt(index int) bool

IsVariationSelectorAt returns true if the glyph at index is a variation selector.

func (*OTApplyContext) LigatePositions added in v0.0.4

func (ctx *OTApplyContext) LigatePositions(ligGlyph GlyphID, positions []int)

LigatePositions replaces glyphs at specific positions with a ligature. HarfBuzz equivalent: ligate_input() in hb-ot-layout-gsubgpos.hh:1450-1563

func (*OTApplyContext) MatchPropertiesMark added in v0.0.4

func (ctx *OTApplyContext) MatchPropertiesMark(info *GlyphInfo, glyphProps uint16) bool

MatchPropertiesMark checks mark attachment properties. HarfBuzz equivalent: match_properties_mark() in hb-ot-layout-gsubgpos.hh:806-824

func (*OTApplyContext) MayMatch added in v0.0.4

func (ctx *OTApplyContext) MayMatch(index int, contextMatch bool) MayMatchResult

MayMatch checks if a glyph may match based on mask and syllable. HarfBuzz equivalent: matcher_t::may_match() in hb-ot-layout-gsubgpos.hh:434-445

func (*OTApplyContext) MayMatchInfo added in v0.0.5

func (ctx *OTApplyContext) MayMatchInfo(info *GlyphInfo, contextMatch bool) MayMatchResult

MayMatchInfo is like MayMatch but takes a GlyphInfo pointer directly. This is needed for backtrack matching which uses the output buffer, not input.

func (*OTApplyContext) MaySkip added in v0.0.4

func (ctx *OTApplyContext) MaySkip(index int, contextMatch bool) MaySkipResult

MaySkip checks if a glyph should be skipped. HarfBuzz equivalent: matcher_t::may_skip() in hb-ot-layout-gsubgpos.hh:453-470

func (*OTApplyContext) MaySkipInfo added in v0.0.4

func (ctx *OTApplyContext) MaySkipInfo(info *GlyphInfo, contextMatch bool) MaySkipResult

MaySkipInfo is like MaySkip but takes a GlyphInfo pointer directly. This is needed for backtrack matching which uses the output buffer, not input. HarfBuzz: prev() in skipping_iterator_t uses out_info, not info.

func (*OTApplyContext) MergeClusters added in v0.0.4

func (ctx *OTApplyContext) MergeClusters(start, end int)

MergeClusters merges clusters in the range [start, end).

func (*OTApplyContext) NextContextGlyph added in v0.0.4

func (ctx *OTApplyContext) NextContextGlyph(startIndex int) int

NextContextGlyph finds the next non-skippable glyph for context matching. This simplified version does NOT implement the 3-way match logic. For proper HarfBuzz-compatible context matching, use NextContextMatch instead.

func (*OTApplyContext) NextContextMatch added in v0.0.5

func (ctx *OTApplyContext) NextContextMatch(startIndex int, matchFn ContextMatchFunc) int

NextContextMatch finds the next context glyph that matches, implementing HarfBuzz's 3-way match logic (hb-ot-layout-gsubgpos.hh:562-578):

SKIP_YES                        → skip (continue to next)
SKIP_NO  + match                → MATCH (return position)
SKIP_NO  + no match             → NOT_MATCH (return -1, rule fails)
SKIP_MAYBE + match              → MATCH (return position)
SKIP_MAYBE + no match           → SKIP (continue to next)

This is critical for default ignorables like ZWJ: they have SKIP_MAYBE and if they don't match the expected class/coverage, they should be skipped over, not cause the entire rule to fail.

func (*OTApplyContext) NextGlyph added in v0.0.4

func (ctx *OTApplyContext) NextGlyph(startIndex int) int

NextGlyph finds the next glyph that should not be skipped. HarfBuzz equivalent: skipping_iterator_t::next() with iter_input (context_match=false) The mask IS checked here.

func (*OTApplyContext) NextInputMatch added in v0.0.6

func (ctx *OTApplyContext) NextInputMatch(startIndex int, matchFn ContextMatchFunc) int

NextInputMatch finds the next input glyph that matches, implementing HarfBuzz's 3-way match logic for input (non-context) matching. HarfBuzz equivalent: match_input() using iter_input with context_match=false.

This is like NextContextMatch but with contextMatch=false, which means:

  • ZWNJ is NOT automatically skipped (respects auto_zwnj)
  • Mask IS checked (lookup_mask, not -1)
  • Hidden default ignorables (CGJ) that have been unhidden ARE skipped via SkipMaybe

The 3-way logic:

SKIP_YES                        → skip (continue to next)
SKIP_NO  + match                → MATCH (return position)
SKIP_NO  + no match             → NOT_MATCH (return -1, rule fails)
SKIP_MAYBE + match              → MATCH (return position)
SKIP_MAYBE + no match           → SKIP (continue to next)

func (*OTApplyContext) OutputGlyphForComponent added in v0.0.4

func (ctx *OTApplyContext) OutputGlyphForComponent(newGlyph GlyphID, classGuess int)

OutputGlyphForComponent outputs a glyph as part of a multiple substitution. HarfBuzz equivalent: output_glyph_for_component() in hb-ot-layout-gsubgpos.hh:901-906

HarfBuzz: Calls buffer->output_glyph() which uses replace_glyphs(0, 1, ...) This inserts a new glyph inheriting properties from the current glyph.

func (*OTApplyContext) PrevContextGlyph added in v0.0.4

func (ctx *OTApplyContext) PrevContextGlyph(startIndex int) int

PrevContextGlyph finds the previous non-skippable glyph for context matching. This simplified version does NOT implement the 3-way match logic. For proper HarfBuzz-compatible context matching, use PrevContextMatch instead.

func (*OTApplyContext) PrevContextMatch added in v0.0.5

func (ctx *OTApplyContext) PrevContextMatch(startIndex int, matchFn ContextMatchFunc) int

PrevContextMatch finds the previous context glyph that matches, with 3-way match logic. See NextContextMatch for detailed documentation.

func (*OTApplyContext) PrevGlyph added in v0.0.4

func (ctx *OTApplyContext) PrevGlyph(startIndex int) int

PrevGlyph finds the previous glyph that should not be skipped, implementing HarfBuzz's 3-way match logic from skipping_iterator_t::prev(). HarfBuzz equivalent: skipping_iterator_t::prev() with iter_input (context_match=false)

Unlike the simplified ShouldSkipGlyph, this properly handles the case where a default ignorable (SkipMaybe) has no explicit match (MatchMaybe) → SKIP. This is critical for GPOS lookups like CursivePos that need to skip over default ignorable glyphs (.notdef from ZWNJ/CGJ) between real glyphs.

func (*OTApplyContext) RandomNumber added in v0.0.6

func (ctx *OTApplyContext) RandomNumber() uint32

RandomNumber generates a pseudo-random number using the buffer's random state. HarfBuzz equivalent: random_number() in hb-ot-layout-gsubgpos.hh:797-801 Uses minstd_rand: state = state * 48271 % 2147483647

func (*OTApplyContext) Recurse added in v0.0.4

func (ctx *OTApplyContext) Recurse(lookupIndex int) bool

Recurse applies a nested lookup. HarfBuzz equivalent: recurse() in hb_ot_apply_context_t (hb-ot-layout-gsubgpos.hh:704-724)

This method: - Checks if RecurseFunc is set - Checks nesting level to prevent infinite recursion - Decrements nesting level before calling, restores after - Returns false if recursion is not possible or lookup fails

func (*OTApplyContext) ReplaceGlyph added in v0.0.4

func (ctx *OTApplyContext) ReplaceGlyph(newGlyph GlyphID)

ReplaceGlyph replaces the current glyph with a new one and advances. HarfBuzz equivalent: replace_glyph() in hb-ot-layout-gsubgpos.hh:885-889

HarfBuzz: Calls buffer->replace_glyph() which uses replace_glyphs(1, 1, ...) This copies all properties (including cluster) from the current glyph.

func (*OTApplyContext) ReplaceGlyphInplace added in v0.0.4

func (ctx *OTApplyContext) ReplaceGlyphInplace(newGlyph GlyphID)

ReplaceGlyphInplace replaces the current glyph without advancing. HarfBuzz equivalent: replace_glyph_inplace() in hb-ot-layout-gsubgpos.hh:890-894

func (*OTApplyContext) ReplaceGlyphWithLigature added in v0.0.4

func (ctx *OTApplyContext) ReplaceGlyphWithLigature(newGlyph GlyphID, classGuess int)

ReplaceGlyphWithLigature replaces the current glyph with a ligature glyph. HarfBuzz equivalent: replace_glyph_with_ligature() in hb-ot-layout-gsubgpos.hh:895-900

HarfBuzz: Calls buffer->replace_glyph() which uses replace_glyphs(1, 1, ...) This copies all properties (including cluster) from the current glyph.

func (*OTApplyContext) ReplaceGlyphs added in v0.0.4

func (ctx *OTApplyContext) ReplaceGlyphs(newGlyphs []GlyphID)

ReplaceGlyphs replaces the current glyph with multiple glyphs. HarfBuzz equivalent: Sequence::apply() in OT/Layout/GSUB/Sequence.hh:34-130

This is used for Multiple Substitution (1 -> N).

func (*OTApplyContext) SetAutoZWJ added in v0.0.4

func (ctx *OTApplyContext) SetAutoZWJ(autoZWJ bool)

SetAutoZWJ sets the auto-ZWJ flag. HarfBuzz equivalent: set_auto_zwj() in hb-ot-layout-gsubgpos.hh:785

func (*OTApplyContext) SetAutoZWNJ added in v0.0.4

func (ctx *OTApplyContext) SetAutoZWNJ(autoZWNJ bool)

SetAutoZWNJ sets the auto-ZWNJ flag. HarfBuzz equivalent: set_auto_zwnj() in hb-ot-layout-gsubgpos.hh:786

func (*OTApplyContext) SetLookupMask added in v0.0.4

func (ctx *OTApplyContext) SetLookupMask(mask uint32)

SetLookupMask sets the lookup mask (feature mask). HarfBuzz equivalent: set_lookup_mask() in hb-ot-layout-gsubgpos.hh:784

func (*OTApplyContext) SetLookupProps added in v0.0.4

func (ctx *OTApplyContext) SetLookupProps(props uint16)

SetLookupProps sets the lookup properties (flags). HarfBuzz equivalent: set_lookup_props() in hb-ot-layout-gsubgpos.hh:791-795

func (*OTApplyContext) SetMarkFilteringSet added in v0.0.4

func (ctx *OTApplyContext) SetMarkFilteringSet(set int)

SetMarkFilteringSet sets the mark filtering set index. Validates the index and disables the flag if invalid (like HarfBuzz sanitize_lookup_props). HarfBuzz equivalent: sanitize_lookup_props() in GDEF.hh:1017-1028

func (*OTApplyContext) SetPerSyllable added in v0.0.4

func (ctx *OTApplyContext) SetPerSyllable(perSyllable bool)

SetPerSyllable sets the per-syllable flag. HarfBuzz equivalent: set_per_syllable() in hb-ot-layout-gsubgpos.hh:787

func (*OTApplyContext) SetRandom added in v0.0.4

func (ctx *OTApplyContext) SetRandom(random bool)

SetRandom sets the random flag for random features. HarfBuzz equivalent: set_random() in hb-ot-layout-gsubgpos.hh:788

func (*OTApplyContext) ShouldSkipContextGlyph added in v0.0.4

func (ctx *OTApplyContext) ShouldSkipContextGlyph(index int) bool

ShouldSkipContextGlyph returns true if the glyph should be skipped during context matching. HarfBuzz equivalent: uses iter_context which is initialized with context_match=true This means the mask is NOT checked (mask = -1 in HarfBuzz). HarfBuzz: hb-ot-layout-gsubgpos.hh:781 - iter_context.init(this, true)

HarfBuzz match() logic (hb-ot-layout-gsubgpos.hh:562-578):

if (skip == SKIP_YES) return SKIP;
if (match == MATCH_YES || (match == MATCH_MAYBE && skip == SKIP_NO)) return MATCH;
if (skip == SKIP_NO) return NOT_MATCH;
return SKIP;  // SKIP_MAYBE with non-YES match -> SKIP

func (*OTApplyContext) ShouldSkipGlyph added in v0.0.4

func (ctx *OTApplyContext) ShouldSkipGlyph(index int) bool

ShouldSkipGlyph returns true if the glyph at index should be skipped. This is the simplified interface for backward compatibility. HarfBuzz equivalent: combination of may_skip() and may_match()

type OTMap added in v0.0.4

type OTMap struct {
	// Lookups organized by table (0=GSUB, 1=GPOS)
	// HarfBuzz: hb_sorted_vector_t<lookup_map_t> lookups[2]
	GSUBLookups []LookupMap
	GPOSLookups []LookupMap

	// Global mask applied to all glyphs
	// HarfBuzz: hb_mask_t global_mask
	GlobalMask uint32

	// Feature mask allocations for per-cluster range features.
	// HarfBuzz equivalent: hb_ot_map_t::features (sorted vector of feature_map_t)
	FeatureMasks map[Tag]featureMaskEntry
	// contains filtered or unexported fields
}

OTMap organizes lookups for GSUB and GPOS tables. HarfBuzz equivalent: hb_ot_map_t in hb-ot-map.hh:42-166

func CompileMap added in v0.0.4

func CompileMap(gsub *GSUB, gpos *GPOS, features []Feature, scriptTag Tag, languageTag Tag) *OTMap

CompileMap creates an OTMap from feature list and requested features. HarfBuzz equivalent: hb_ot_map_builder_t::compile() in hb-ot-map.cc:183-391

This implements HarfBuzz's full feature merging algorithm: 1. Collect all features into featureInfo list with sequence numbers 2. Sort by tag (stable by sequence), merge duplicates per HarfBuzz rules 3. Allocate mask bits for non-global features 4. Find lookups in GSUB/GPOS using script/language-specific feature indices 5. Assign masks to lookups

func NewOTMap added in v0.0.4

func NewOTMap() *OTMap

NewOTMap creates a new empty OT map.

func (*OTMap) AddGPOSFeature added in v0.0.4

func (m *OTMap) AddGPOSFeature(tag Tag, mask uint32, required bool)

AddGPOSFeature adds a GPOS feature to the map with the given mask.

func (*OTMap) AddGPOSLookup added in v0.0.4

func (m *OTMap) AddGPOSLookup(index uint16, mask uint32, featureTag Tag)

AddGPOSLookup adds a GPOS lookup to the map. HarfBuzz equivalent: adding to lookups[1] in hb_ot_map_builder_t::compile()

func (*OTMap) AddGSUBFeature added in v0.0.4

func (m *OTMap) AddGSUBFeature(tag Tag, mask uint32, required bool)

AddGSUBFeature adds a GSUB feature to the map with the given mask. The 'required' parameter indicates if this feature is mandatory.

func (*OTMap) AddGSUBLookup added in v0.0.4

func (m *OTMap) AddGSUBLookup(index uint16, mask uint32, featureTag Tag)

AddGSUBLookup adds a GSUB lookup to the map. HarfBuzz equivalent: adding to lookups[0] in hb_ot_map_builder_t::compile()

func (*OTMap) ApplyGPOS added in v0.0.4

func (m *OTMap) ApplyGPOS(gpos *GPOS, buf *Buffer, font *Font, gdef *GDEF)

ApplyGPOS applies all GPOS lookups in the map to the buffer. HarfBuzz equivalent: hb_ot_map_t::apply() with GPOS proxy in hb-ot-layout.cc:2010-2060

func (*OTMap) ApplyGSUB added in v0.0.4

func (m *OTMap) ApplyGSUB(gsub *GSUB, buf *Buffer, font *Font, gdef *GDEF)

ApplyGSUB applies all GSUB lookups in the map to the buffer. HarfBuzz equivalent: hb_ot_map_t::apply() with GSUB proxy in hb-ot-layout.cc:2010-2060

type OTShaper added in v0.0.4

type OTShaper struct {
	// Name identifies this shaper (for debugging)
	Name string

	// CollectFeatures is called during plan compilation.
	// Shapers should add their features to the plan's map.
	// HarfBuzz: collect_features (hb-ot-shaper.hh:74)
	CollectFeatures func(plan *ShapePlan)

	// OverrideFeatures is called after common features are added.
	// Shapers can override or modify features here.
	// HarfBuzz: override_features (hb-ot-shaper.hh:82)
	OverrideFeatures func(plan *ShapePlan)

	// DataCreate is called at the end of plan compilation.
	// Returns shaper-specific data that will be stored in the plan.
	// HarfBuzz: data_create (hb-ot-shaper.hh:90)
	DataCreate func(plan *ShapePlan) interface{}

	// DataDestroy is called when the plan is destroyed.
	// HarfBuzz: data_destroy (hb-ot-shaper.hh:98)
	DataDestroy func(data interface{})

	// PreprocessText is called before shaping starts.
	// Shapers can modify the buffer text here.
	// HarfBuzz: preprocess_text (hb-ot-shaper.hh:106)
	PreprocessText func(plan *ShapePlan, buf *Buffer, font *Font)

	// PostprocessGlyphs is called after shaping ends.
	// Shapers can modify glyphs here.
	// HarfBuzz: postprocess_glyphs (hb-ot-shaper.hh:115)
	PostprocessGlyphs func(plan *ShapePlan, buf *Buffer, font *Font)

	// Decompose is called during normalization.
	// Returns the decomposition of a codepoint (a, b) or ok=false if not decomposable.
	// HarfBuzz: decompose (hb-ot-shaper.hh:124)
	Decompose func(c *NormalizeContext, ab Codepoint) (a, b Codepoint, ok bool)

	// Compose is called during normalization.
	// Returns the composition of (a, b) or ok=false if not composable.
	// HarfBuzz: compose (hb-ot-shaper.hh:133)
	Compose func(c *NormalizeContext, a, b Codepoint) (ab Codepoint, ok bool)

	// SetupMasks is called to set feature masks on glyphs.
	// Shapers should use the plan's map to get masks and set them on the buffer.
	// HarfBuzz: setup_masks (hb-ot-shaper.hh:144)
	SetupMasks func(plan *ShapePlan, buf *Buffer, font *Font)

	// ReorderMarks is called to reorder combining marks.
	// HarfBuzz: reorder_marks (hb-ot-shaper.hh:153)
	ReorderMarks func(plan *ShapePlan, buf *Buffer, start, end int)

	// GPOSTag - If not zero, must match GPOS script tag for GPOS to be applied.
	// HarfBuzz: gpos_tag (hb-ot-shaper.hh:162)
	GPOSTag Tag

	// NormalizationPreference controls how normalization is performed.
	// HarfBuzz: normalization_preference (hb-ot-shaper.hh:164)
	NormalizationPreference NormalizationMode

	// ZeroWidthMarks controls how zero-width marks are handled.
	// HarfBuzz: zero_width_marks (hb-ot-shaper.hh:166)
	ZeroWidthMarks ZeroWidthMarksType

	// FallbackPosition enables fallback positioning when GPOS is not available.
	// HarfBuzz: fallback_position (hb-ot-shaper.hh:168)
	FallbackPosition bool
}

OTShaper defines the interface for script-specific shapers. HarfBuzz equivalent: hb_ot_shaper_t in hb-ot-shaper.hh:67-169

All function fields are optional (nil means use default behavior). This design matches HarfBuzz where NULL function pointers are allowed.

func SelectShaper added in v0.0.4

func SelectShaper(script Tag, direction Direction) *OTShaper

SelectShaper returns the appropriate shaper for the given script and direction. HarfBuzz equivalent: hb_ot_shaper_categorize() in hb-ot-shaper.hh:176-350 Script tags are ISO 15924 format (uppercase-first): 'Arab', 'Hebr', etc. Note: For Indic scripts, prefer SelectShaperWithFont which considers the font's script tag.

func SelectShaperWithFont added in v0.0.4

func SelectShaperWithFont(script Tag, direction Direction, fontScriptTag Tag) *OTShaper

SelectShaperWithFont returns the appropriate shaper based on script, direction, and font script tag. HarfBuzz equivalent: hb_ot_shaper_categorize() in hb-ot-shaper.hh:176-350

This function implements the critical logic from HarfBuzz where Indic scripts with script tag version 3 (e.g., 'knd3', 'dev3') use the USE shaper instead of the Indic shaper. See hb-ot-shaper.hh:242-245:

else if ((gsub_script & 0x000000FF) == '3')
    return &_hb_ot_shaper_use;

Parameters:

  • script: The Unicode script tag (e.g., 'Knda' for Kannada)
  • direction: Text direction
  • fontScriptTag: The actual script tag found in the font's GSUB table (e.g., 'knd3')

type OutlinePoint added in v0.0.7

type OutlinePoint struct{ X, Y float32 }

OutlinePoint represents a 2D point in glyph outline coordinates.

type PairClassRecord

type PairClassRecord struct {
	Value1 ValueRecord
	Value2 ValueRecord
}

PairClassRecord holds positioning values for a class pair.

type PairPos

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

PairPos represents a Pair Positioning subtable.

func (*PairPos) Apply

func (pp *PairPos) Apply(ctx *OTApplyContext) bool

Apply applies pair positioning (kerning). HarfBuzz: PairPosFormat1/PairPosFormat2::apply in GPOS/PairPos*.hh Uses skippy_iter (iter_input) to find the second glyph, skipping marks/bases/ligatures per the lookup flag. This is critical for correct kerning in fonts where marks (or even space with mark class) appear between kerning pairs.

func (*PairPos) Class1Count

func (pp *PairPos) Class1Count() uint16

Class1Count returns the number of classes for first glyphs (format 2 only).

func (*PairPos) Class2Count

func (pp *PairPos) Class2Count() uint16

Class2Count returns the number of classes for second glyphs (format 2 only).

func (*PairPos) ClassDef1

func (pp *PairPos) ClassDef1() *ClassDef

ClassDef1 returns the class definition for first glyphs (format 2 only).

func (*PairPos) ClassDef2

func (pp *PairPos) ClassDef2() *ClassDef

ClassDef2 returns the class definition for second glyphs (format 2 only).

func (*PairPos) ClassMatrix

func (pp *PairPos) ClassMatrix() [][]PairClassRecord

ClassMatrix returns the class matrix (format 2 only).

func (*PairPos) Coverage

func (pp *PairPos) Coverage() *Coverage

Coverage returns the coverage table for this subtable.

func (*PairPos) Format

func (pp *PairPos) Format() uint16

Format returns the subtable format (1 or 2).

func (*PairPos) PairSets

func (pp *PairPos) PairSets() [][]PairValueRecord

PairSets returns the pair sets (format 1 only).

func (*PairPos) ValueFormat1

func (pp *PairPos) ValueFormat1() uint16

ValueFormat1 returns the value format for the first glyph.

func (*PairPos) ValueFormat2

func (pp *PairPos) ValueFormat2() uint16

ValueFormat2 returns the value format for the second glyph.

type PairValueRecord

type PairValueRecord struct {
	SecondGlyph GlyphID
	Value1      ValueRecord
	Value2      ValueRecord
}

PairValueRecord holds a pair of glyphs and their positioning values.

type Parser

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

Parser provides methods for reading binary OpenType data.

func NewParser

func NewParser(data []byte) *Parser

NewParser creates a parser for the given data.

func (*Parser) Bytes

func (p *Parser) Bytes(n int) ([]byte, error)

Bytes returns n bytes at the current offset and advances.

func (*Parser) Data

func (p *Parser) Data() []byte

Data returns the underlying byte slice.

func (*Parser) I16

func (p *Parser) I16() (int16, error)

I16 reads a big-endian int16 and advances.

func (*Parser) I16At

func (p *Parser) I16At(off int) (int16, error)

I16At reads a big-endian int16 at the given offset (doesn't advance).

func (*Parser) I32

func (p *Parser) I32() (int32, error)

I32 reads a big-endian int32 and advances.

func (*Parser) Offset

func (p *Parser) Offset() int

Offset returns the current offset.

func (*Parser) Remaining

func (p *Parser) Remaining() int

Remaining returns the number of bytes remaining.

func (*Parser) SetOffset

func (p *Parser) SetOffset(off int) error

SetOffset sets the current offset.

func (*Parser) Skip

func (p *Parser) Skip(n int) error

Skip advances the offset by n bytes.

func (*Parser) SubParser

func (p *Parser) SubParser(off, length int) (*Parser, error)

SubParser returns a parser for a sub-range of the data.

func (*Parser) SubParserFromOffset

func (p *Parser) SubParserFromOffset(off int) (*Parser, error)

SubParserFromOffset returns a parser starting at off to end of data.

func (*Parser) Tag

func (p *Parser) Tag() (Tag, error)

Tag reads a 4-byte tag and advances.

func (*Parser) U8

func (p *Parser) U8() (uint8, error)

U8 reads a uint8 and advances.

func (*Parser) U16

func (p *Parser) U16() (uint16, error)

U16 reads a big-endian uint16 and advances.

func (*Parser) U16At

func (p *Parser) U16At(off int) (uint16, error)

U16At reads a big-endian uint16 at the given offset (doesn't advance).

func (*Parser) U32

func (p *Parser) U32() (uint32, error)

U32 reads a big-endian uint32 and advances.

func (*Parser) U32At

func (p *Parser) U32At(off int) (uint32, error)

U32At reads a big-endian uint32 at the given offset (doesn't advance).

type Post

type Post struct {
	Version            uint32
	ItalicAngle        int32 // Fixed-point 16.16
	UnderlinePosition  int16
	UnderlineThickness int16
	IsFixedPitch       uint32
}

Post represents the post table.

func ParsePost

func ParsePost(data []byte) (*Post, error)

ParsePost parses the post table (minimal parsing for metrics).

func (*Post) ItalicAngleDegrees

func (p *Post) ItalicAngleDegrees() float64

ItalicAngleDegrees returns the italic angle in degrees.

type PostTable added in v0.0.4

type PostTable struct {
	Version            uint32
	ItalicAngle        int32
	UnderlinePosition  int16
	UnderlineThickness int16
	IsFixedPitch       uint32
	// contains filtered or unexported fields
}

PostTable represents a fully parsed post table with glyph name support. This extends the basic Post struct in metrics.go with full format 2.0 support.

func ParsePostTable added in v0.0.4

func ParsePostTable(data []byte) (*PostTable, error)

ParsePostTable parses the post table with full glyph name support. HarfBuzz equivalent: hb-ot-post-table.hh accelerator_t::init()

func (*PostTable) GetGlyphFromName added in v0.0.4

func (p *PostTable) GetGlyphFromName(name string) (GlyphID, bool)

GetGlyphFromName returns the glyph ID for a given glyph name. Returns false if the name is not found. HarfBuzz equivalent: hb-ot-post-table.hh accelerator_t::get_glyph_from_name()

func (*PostTable) GetGlyphName added in v0.0.4

func (p *PostTable) GetGlyphName(glyph GlyphID) string

GetGlyphName returns the glyph name for a given glyph ID. Returns empty string if no name is available. HarfBuzz equivalent: hb-ot-post-table.hh accelerator_t::get_glyph_name()

func (*PostTable) HasGlyphNames added in v0.0.4

func (p *PostTable) HasGlyphNames() bool

HasGlyphNames returns true if the post table contains glyph names.

type PrivateDict

type PrivateDict struct {
	BlueValues       []int
	OtherBlues       []int
	FamilyBlues      []int
	FamilyOtherBlues []int
	StdHW            int
	StdVW            int
	StemSnapH        []int // Stem snap widths (horizontal)
	StemSnapV        []int // Stem snap widths (vertical)
	Subrs            int   // Offset to Local Subrs (relative to Private DICT)
	DefaultWidthX    int
	NominalWidthX    int
	BlueScale        float64
	BlueShift        int
	BlueFuzz         int
}

PrivateDict contains private dictionary data.

type ReorderMarksCallback added in v0.0.4

type ReorderMarksCallback func(info []GlyphInfo, start, end int)

ReorderMarksCallback is a function that performs script-specific mark reordering. HarfBuzz equivalent: hb_ot_shaper_t::reorder_marks callback Parameters:

  • info: The slice of glyph info to reorder
  • start: Start index of the mark sequence
  • end: End index of the mark sequence (exclusive)

type RephMode added in v0.0.4

type RephMode uint8

RephMode indicates how reph is formed for a script. HarfBuzz equivalent: reph_mode_t

const (
	RephModeImplicit RephMode = iota // Reph formed implicitly (Ra+H)
	RephModeExplicit                 // Reph formed explicitly (Ra+H+ZWJ)
	RephModeLogRepha                 // Reph formed by logical repha
)

type ReverseChainSingleSubst

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

ReverseChainSingleSubst represents a Reverse Chaining Context Single Substitution subtable (GSUB Type 8). It is designed to be applied in reverse (from end to beginning of buffer). Unlike ChainContextSubst, it only performs single glyph substitution (no nested lookups).

func (*ReverseChainSingleSubst) Apply

Apply applies the reverse chaining context single substitution. This lookup is intended to be applied in reverse (from end to beginning of buffer). It replaces the current glyph if it matches the coverage and context.

type ScratchFlags added in v0.0.4

type ScratchFlags uint32

ScratchFlags are temporary flags used during shaping.

const (
	// ScratchFlagArabicHasStch indicates buffer has STCH glyphs that need post-processing.
	ScratchFlagArabicHasStch ScratchFlags = 1 << 0
)

type Script added in v0.0.4

type Script uint8

Script constants matching HarfBuzz's hb_script_t enum order. HarfBuzz equivalent: hb_script_t in hb-common.h

const (
	ScriptCommon                Script = 0   // Zyyy
	ScriptInherited             Script = 1   // Zinh
	ScriptUnknown               Script = 2   // Zzzz
	ScriptArabic                Script = 3   // Arab
	ScriptArmenian              Script = 4   // Armn
	ScriptBengali               Script = 5   // Beng
	ScriptCyrillic              Script = 6   // Cyrl
	ScriptDevanagari            Script = 7   // Deva
	ScriptGeorgian              Script = 8   // Geor
	ScriptGreek                 Script = 9   // Grek
	ScriptGujarati              Script = 10  // Gujr
	ScriptGurmukhi              Script = 11  // Guru
	ScriptHangul                Script = 12  // Hang
	ScriptHan                   Script = 13  // Hani
	ScriptHebrew                Script = 14  // Hebr
	ScriptHiragana              Script = 15  // Hira
	ScriptKannada               Script = 16  // Knda
	ScriptKatakana              Script = 17  // Kana
	ScriptLao                   Script = 18  // Laoo
	ScriptLatin                 Script = 19  // Latn
	ScriptMalayalam             Script = 20  // Mlym
	ScriptOriya                 Script = 21  // Orya
	ScriptTamil                 Script = 22  // Taml
	ScriptTelugu                Script = 23  // Telu
	ScriptThai                  Script = 24  // Thai
	ScriptTibetan               Script = 25  // Tibt
	ScriptBopomofo              Script = 26  // Bopo
	ScriptBraille               Script = 27  // Brai
	ScriptCanadianSyllabics     Script = 28  // Cans
	ScriptCherokee              Script = 29  // Cher
	ScriptEthiopic              Script = 30  // Ethi
	ScriptKhmer                 Script = 31  // Khmr
	ScriptMongolian             Script = 32  // Mong
	ScriptMyanmar               Script = 33  // Mymr
	ScriptOgham                 Script = 34  // Ogam
	ScriptRunic                 Script = 35  // Runr
	ScriptSinhala               Script = 36  // Sinh
	ScriptSyriac                Script = 37  // Syrc
	ScriptThaana                Script = 38  // Thaa
	ScriptYi                    Script = 39  // Yiii
	ScriptDeseret               Script = 40  // Dsrt
	ScriptGothic                Script = 41  // Goth
	ScriptOldItalic             Script = 42  // Ital
	ScriptBuhid                 Script = 43  // Buhd
	ScriptHanunoo               Script = 44  // Hano
	ScriptTagalog               Script = 45  // Tglg
	ScriptTagbanwa              Script = 46  // Tagb
	ScriptCypriot               Script = 47  // Cprt
	ScriptLimbu                 Script = 48  // Limb
	ScriptLinearB               Script = 49  // Linb
	ScriptOsmanya               Script = 50  // Osma
	ScriptShavian               Script = 51  // Shaw
	ScriptTaiLe                 Script = 52  // Tale
	ScriptUgaritic              Script = 53  // Ugar
	ScriptBuginese              Script = 54  // Bugi
	ScriptCoptic                Script = 55  // Copt
	ScriptGlagolitic            Script = 56  // Glag
	ScriptKharoshthi            Script = 57  // Khar
	ScriptNewTaiLue             Script = 58  // Talu
	ScriptOldPersian            Script = 59  // Xpeo
	ScriptSylotiNagri           Script = 60  // Sylo
	ScriptTifinagh              Script = 61  // Tfng
	ScriptBalinese              Script = 62  // Bali
	ScriptCuneiform             Script = 63  // Xsux
	ScriptNko                   Script = 64  // Nkoo
	ScriptPhagsPa               Script = 65  // Phag
	ScriptPhoenician            Script = 66  // Phnx
	ScriptCarian                Script = 67  // Cari
	ScriptCham                  Script = 68  // Cham
	ScriptKayahLi               Script = 69  // Kali
	ScriptLepcha                Script = 70  // Lepc
	ScriptLycian                Script = 71  // Lyci
	ScriptLydian                Script = 72  // Lydi
	ScriptOlChiki               Script = 73  // Olck
	ScriptRejang                Script = 74  // Rjng
	ScriptSaurashtra            Script = 75  // Saur
	ScriptSundanese             Script = 76  // Sund
	ScriptVai                   Script = 77  // Vaii
	ScriptAvestan               Script = 78  // Avst
	ScriptBamum                 Script = 79  // Bamu
	ScriptEgyptianHieroglyphs   Script = 80  // Egyp
	ScriptImperialAramaic       Script = 81  // Armi
	ScriptInscriptionalPahlavi  Script = 82  // Phli
	ScriptInscriptionalParthian Script = 83  // Prti
	ScriptJavanese              Script = 84  // Java
	ScriptKaithi                Script = 85  // Kthi
	ScriptLisu                  Script = 86  // Lisu
	ScriptMeeteiMayek           Script = 87  // Mtei
	ScriptOldSouthArabian       Script = 88  // Sarb
	ScriptOldTurkic             Script = 89  // Orkh
	ScriptSamaritan             Script = 90  // Samr
	ScriptTaiTham               Script = 91  // Lana
	ScriptTaiViet               Script = 92  // Tavt
	ScriptBatak                 Script = 93  // Batk
	ScriptBrahmi                Script = 94  // Brah
	ScriptMandaic               Script = 95  // Mand
	ScriptChakma                Script = 96  // Cakm
	ScriptMeroiticCursive       Script = 97  // Merc
	ScriptMeroiticHieroglyphs   Script = 98  // Mero
	ScriptMiao                  Script = 99  // Plrd
	ScriptSharada               Script = 100 // Shrd
	ScriptSoraSompeng           Script = 101 // Sora
	ScriptTakri                 Script = 102 // Takr
	ScriptBassaVah              Script = 103 // Bass
	ScriptCaucasianAlbanian     Script = 104 // Aghb
	ScriptDuployan              Script = 105 // Dupl
	ScriptElbasan               Script = 106 // Elba
	ScriptGrantha               Script = 107 // Gran
	ScriptKhojki                Script = 108 // Khoj
	ScriptKhudawadi             Script = 109 // Sind
	ScriptLinearA               Script = 110 // Lina
	ScriptMahajani              Script = 111 // Mahj
	ScriptManichaean            Script = 112 // Mani
	ScriptMendeKikakui          Script = 113 // Mend
	ScriptModi                  Script = 114 // Modi
	ScriptMro                   Script = 115 // Mroo
	ScriptNabataean             Script = 116 // Nbat
	ScriptOldNorthArabian       Script = 117 // Narb
	ScriptOldPermic             Script = 118 // Perm
	ScriptPahawhHmong           Script = 119 // Hmng
	ScriptPalmyrene             Script = 120 // Palm
	ScriptPauCinHau             Script = 121 // Pauc
	ScriptPsalterPahlavi        Script = 122 // Phlp
	ScriptSiddham               Script = 123 // Sidd
	ScriptTirhuta               Script = 124 // Tirh
	ScriptWarangCiti            Script = 125 // Wara
	ScriptAhom                  Script = 126 // Ahom
	ScriptAnatolianHieroglyphs  Script = 127 // Hluw
	ScriptHatran                Script = 128 // Hatr
	ScriptMultani               Script = 129 // Mult
	ScriptOldHungarian          Script = 130 // Hung
	ScriptSignwriting           Script = 131 // Sgnw
	ScriptAdlam                 Script = 132 // Adlm
	ScriptBhaiksuki             Script = 133 // Bhks
	ScriptMarchen               Script = 134 // Marc
	ScriptOsage                 Script = 135 // Osge
	ScriptTangut                Script = 136 // Tang
	ScriptNewa                  Script = 137 // Newa
	ScriptMasaramGondi          Script = 138 // Gonm
	ScriptNushu                 Script = 139 // Nshu
	ScriptSoyombo               Script = 140 // Soyo
	ScriptZanabazarSquare       Script = 141 // Zanb
	ScriptDogra                 Script = 142 // Dogr
	ScriptGunjalaGondi          Script = 143 // Gong
	ScriptHanifiRohingya        Script = 144 // Rohg
	ScriptMakasar               Script = 145 // Maka
	ScriptMedefaidrin           Script = 146 // Medf
	ScriptOldSogdian            Script = 147 // Sogo
	ScriptSogdian               Script = 148 // Sogd
	ScriptElymaic               Script = 149 // Elym
	ScriptNandinagari           Script = 150 // Nand
	ScriptNyiakengPuachueHmong  Script = 151 // Hmnp
	ScriptWancho                Script = 152 // Wcho
	ScriptChorasmian            Script = 153 // Chrs
	ScriptDivesAkuru            Script = 154 // Diak
	ScriptKhitanSmallScript     Script = 155 // Kits
	ScriptYezidi                Script = 156 // Yezi
	ScriptCyproMinoan           Script = 157 // Cpmn
	ScriptOldUyghur             Script = 158 // Ougr
	ScriptTangsa                Script = 159 // Tnsa
	ScriptToto                  Script = 160 // Toto
	ScriptVithkuqi              Script = 161 // Vith
	ScriptMath                  Script = 162 // Zmth
	ScriptKawi                  Script = 163 // Kawi
	ScriptNagMundari            Script = 164 // Nagm
	ScriptGaray                 Script = 165 // Gara
	ScriptGurungKhema           Script = 166 // Gukh
	ScriptKiratRai              Script = 167 // Krai
	ScriptOlOnal                Script = 168 // Onao
	ScriptSunuwar               Script = 169 // Sunu
	ScriptTodhri                Script = 170 // Todr
	ScriptTuluTigalari          Script = 171 // Tutg
	ScriptBeriaErfe             Script = 172 // Berf
	ScriptSidetic               Script = 173 // Sidt
	ScriptTaiYo                 Script = 174 // Tayo
	ScriptTolongSiki            Script = 175 // Tols
)

func GetScript added in v0.0.4

func GetScript(cp Codepoint) Script

GetScript returns the Script for a codepoint. HarfBuzz equivalent: hb_ucd_script() using _hb_ucd_sc()

type ScriptList added in v0.0.4

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

ScriptList represents the ScriptList table.

func (*ScriptList) FindBestLanguage added in v0.0.5

func (sl *ScriptList) FindBestLanguage(scriptTag Tag, languageTags []Tag) Tag

FindBestLanguage finds the first language tag from a list of candidates that the font's script table actually supports. Returns the matching Tag, or 0 if none match. This is used to resolve BCP47 language tags that map to multiple OT tags (e.g., "zh-mo" → [ZHTM, ZHH]).

func (*ScriptList) FindChosenScriptTag added in v0.0.4

func (sl *ScriptList) FindChosenScriptTag(scriptTag Tag) Tag

FindChosenScriptTag returns the actual script tag found in the font. This is needed for Indic old-spec vs new-spec detection. HarfBuzz equivalent: plan->map.chosen_script[0] in hb-ot-shaper-indic.cc:324 Returns 0 if no matching script is found.

func (*ScriptList) GetDefaultScript added in v0.0.4

func (sl *ScriptList) GetDefaultScript() *LangSys

GetDefaultScript returns the default LangSys using HarfBuzz fallback order. HarfBuzz equivalent: hb_ot_layout_table_select_script() in hb-ot-layout.cc:561-608 Tries: DFLT, dflt, latn in that order.

func (*ScriptList) GetLangSys added in v0.0.4

func (sl *ScriptList) GetLangSys(scriptTag Tag, languageTag Tag) *LangSys

GetLangSys returns the LangSys for a specific script and language combination. HarfBuzz equivalent: hb_ot_layout_collect_features_map() in hb-ot-map.cc:244-248

const OT::LangSys &l = g.get_script (script_index).get_lang_sys (language_index);

If languageTag is 0 or the language is not found, returns the default LangSys. Returns nil if the script is not found.

func (*ScriptList) GetScript added in v0.0.4

func (sl *ScriptList) GetScript(scriptTag Tag) *LangSys

GetScript returns the LangSys for a script tag (using default language). Returns nil if the script is not found.

type Segment added in v0.0.7

type Segment struct {
	Op   SegmentOp
	Args [3]OutlinePoint
}

Segment represents a single path segment in a glyph outline.

type SegmentOp added in v0.0.7

type SegmentOp uint8

SegmentOp represents the type of a path segment operation.

const (
	// SegmentMoveTo moves the current point to a new position (starts a new contour).
	SegmentMoveTo SegmentOp = iota
	// SegmentLineTo draws a straight line to the endpoint.
	SegmentLineTo
	// SegmentQuadTo draws a quadratic Bézier curve. Args: [0]=control, [1]=endpoint.
	SegmentQuadTo
	// SegmentCubeTo draws a cubic Bézier curve. Args: [0]=ctrl1, [1]=ctrl2, [2]=endpoint.
	SegmentCubeTo
)

type SegmentProperties added in v0.0.4

type SegmentProperties struct {
	Direction Direction
	Script    Tag
	Language  Tag
}

SegmentProperties holds text segment properties. HarfBuzz equivalent: hb_segment_properties_t

type ShapePlan added in v0.0.4

type ShapePlan struct {
	// Shaper is the script-specific shaper for this plan
	Shaper *OTShaper

	// Map contains the compiled lookup map
	Map *OTMap

	// Props contains segment properties (direction, script, language)
	Props SegmentProperties

	// ShaperData holds shaper-specific data created by DataCreate
	ShaperData interface{}

	// Cached masks for common features
	FracMask uint32
	NumrMask uint32
	DnomMask uint32
	HasFrac  bool

	RTLMMask uint32
	HasVert  bool

	KernMask         uint32
	RequestedKerning bool
	// contains filtered or unexported fields
}

ShapePlan holds a compiled shaping plan. HarfBuzz equivalent: hb_ot_shape_plan_t in hb-ot-shape.hh

The plan is compiled once and can be reused for multiple shaping calls. This improves performance by avoiding repeated feature lookups.

type Shaper

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

Shaper holds font data and performs text shaping.

func NewShaper

func NewShaper(font *Font) (*Shaper, error)

NewShaper creates a shaper from a parsed font. HarfBuzz equivalent: hb_font_create() + hb_shape_plan_create() in hb-font.cc, hb-shape-plan.cc

func NewShaperFromFace added in v0.0.4

func NewShaperFromFace(face *Face) (*Shaper, error)

NewShaperFromFace creates a shaper from an existing Face. This is useful when you already have a Face with metrics. HarfBuzz equivalent: hb_font_t holds both face and shaping data

func (*Shaper) DebugArabicFallbackPlan added in v0.0.4

func (s *Shaper) DebugArabicFallbackPlan()

DebugArabicFallbackPlan prints debug information about the Arabic fallback plan.

func (*Shaper) DesignCoords added in v0.0.3

func (s *Shaper) DesignCoords() []float32

DesignCoords returns the current design-space coordinates. Returns nil for non-variable fonts.

func (*Shaper) Font

func (s *Shaper) Font() *Font

Font returns the font associated with this shaper.

func (*Shaper) Fvar added in v0.0.3

func (s *Shaper) Fvar() *Fvar

Fvar returns the parsed fvar table, or nil if not present.

func (*Shaper) GDEF

func (s *Shaper) GDEF() *GDEF

GDEF returns the GDEF table (may be nil).

func (*Shaper) GetDefaultFeatures

func (s *Shaper) GetDefaultFeatures() []Feature

DefaultFeatures returns the current default features.

func (*Shaper) GetGlyphHAdvanceVar added in v0.0.6

func (s *Shaper) GetGlyphHAdvanceVar(glyph GlyphID) uint16

GetGlyphHAdvanceVar returns the horizontal advance for a glyph, including HVAR/gvar variation deltas if active. Exported for font-size scaling in test runners that need to match HarfBuzz's scaling order.

func (*Shaper) GetGlyphVOrigin added in v0.0.6

func (s *Shaper) GetGlyphVOrigin(glyph GlyphID) (x, y int16)

GetGlyphVOrigin returns the vertical origin (x, y) for a glyph in font units. Exported for use by test runners that need to replicate HarfBuzz's scaling order.

func (*Shaper) HasArabicFallbackPlan added in v0.0.4

func (s *Shaper) HasArabicFallbackPlan() bool

HasArabicFallbackPlan returns true if the shaper has an Arabic fallback plan. Used for debugging and testing.

func (*Shaper) HasGDEF

func (s *Shaper) HasGDEF() bool

HasGDEF returns true if the shaper has GDEF data.

func (*Shaper) HasGPOS

func (s *Shaper) HasGPOS() bool

HasGPOS returns true if the shaper has GPOS data.

func (*Shaper) HasGSUB

func (s *Shaper) HasGSUB() bool

HasGSUB returns true if the shaper has GSUB data.

func (*Shaper) HasHmtx

func (s *Shaper) HasHmtx() bool

HasHmtx returns true if the shaper has hmtx data.

func (*Shaper) HasHvar added in v0.0.3

func (s *Shaper) HasHvar() bool

HasHvar returns true if the font has HVAR data for variable advances.

func (*Shaper) HasVariations added in v0.0.3

func (s *Shaper) HasVariations() bool

HasVariations returns true if the font is a variable font.

func (*Shaper) Hvar added in v0.0.3

func (s *Shaper) Hvar() *Hvar

Hvar returns the parsed HVAR table, or nil if not present.

func (*Shaper) NormalizedCoords added in v0.0.3

func (s *Shaper) NormalizedCoords() []float32

NormalizedCoords returns the current normalized coordinates (range [-1, 1]). Returns nil for non-variable fonts.

func (*Shaper) SetDefaultFeatures

func (s *Shaper) SetDefaultFeatures(features []Feature)

SetDefaultFeatures sets the default features to apply when Shape is called with nil.

func (*Shaper) SetNamedInstance added in v0.0.3

func (s *Shaper) SetNamedInstance(index int)

SetNamedInstance sets the variation to a named instance (e.g., "Bold", "Light").

func (*Shaper) SetSyntheticBold added in v0.0.6

func (s *Shaper) SetSyntheticBold(x, y float32, inPlace bool)

SetSyntheticBold sets synthetic bold parameters. x and y are embolden strengths in em-units (e.g. 0.02). If inPlace is true, advances and origins are not modified (only extents/drawing). HarfBuzz equivalent: hb_font_set_synthetic_bold()

func (*Shaper) SetSyntheticSlant added in v0.0.6

func (s *Shaper) SetSyntheticSlant(slant float32)

SetSyntheticSlant sets the synthetic slant value. HarfBuzz equivalent: hb_font_set_synthetic_slant() Slant has no effect on shaping positions; it only affects extents and drawing.

func (*Shaper) SetVariation added in v0.0.3

func (s *Shaper) SetVariation(tag Tag, value float32)

SetVariation sets a single variation axis value. Note: This is less efficient than SetVariations for setting multiple axes.

func (*Shaper) SetVariations added in v0.0.3

func (s *Shaper) SetVariations(variations []Variation)

SetVariations sets the variation axis values. This overrides all existing variations. Axes not included will be set to their default values.

func (*Shaper) Shape

func (s *Shaper) Shape(buf *Buffer, features []Feature)

Shape shapes the text in the buffer using the specified features. If features is nil, default features are used. This is the main shaping entry point, similar to HarfBuzz's hb_shape().

HarfBuzz equivalent: hb_shape() -> hb_shape_full() -> hb_ot_shape_internal() in hb-shape.cc and hb-ot-shape.cc

func (*Shaper) ShapeString

func (s *Shaper) ShapeString(text string) ([]GlyphID, []GlyphPos)

ShapeString is a convenience function that shapes a string and returns the glyph IDs and positions.

func (*Shaper) SyntheticBold added in v0.0.6

func (s *Shaper) SyntheticBold() (x, y float32, inPlace bool)

SyntheticBold returns the current synthetic bold parameters.

func (*Shaper) SyntheticSlant added in v0.0.6

func (s *Shaper) SyntheticSlant() float32

SyntheticSlant returns the current synthetic slant value.

type SimpleGlyphPoint added in v0.0.3

type SimpleGlyphPoint struct {
	X       int16
	Y       int16
	OnCurve bool
}

SimpleGlyphPoint represents a point in a simple glyph outline.

func ParseSimpleGlyph added in v0.0.3

func ParseSimpleGlyph(data []byte) ([]SimpleGlyphPoint, int, error)

ParseSimpleGlyph parses a simple glyph and returns its points. This includes phantom points (4 points at the end for metrics).

type SinglePos

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

SinglePos represents a Single Positioning subtable.

func (*SinglePos) Apply

func (sp *SinglePos) Apply(ctx *OTApplyContext) bool

Apply applies single positioning.

func (*SinglePos) Coverage

func (sp *SinglePos) Coverage() *Coverage

Coverage returns the coverage table for this subtable.

func (*SinglePos) Format

func (sp *SinglePos) Format() uint16

Format returns the subtable format (1 or 2).

func (*SinglePos) ValueFormat

func (sp *SinglePos) ValueFormat() uint16

ValueFormat returns the value format flags.

func (*SinglePos) ValueRecord

func (sp *SinglePos) ValueRecord() ValueRecord

ValueRecord returns the value record (format 1 only).

func (*SinglePos) ValueRecords

func (sp *SinglePos) ValueRecords() []ValueRecord

ValueRecords returns the per-glyph value records (format 2 only).

type SingleSubst

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

SingleSubst represents a Single Substitution subtable.

func (*SingleSubst) Apply

func (s *SingleSubst) Apply(ctx *OTApplyContext) int

Apply applies the single substitution.

func (*SingleSubst) Mapping

func (s *SingleSubst) Mapping() map[GlyphID]GlyphID

Mapping returns all input->output glyph mappings for this substitution.

type SyllableAccessor added in v0.0.4

type SyllableAccessor interface {
	// GetSyllable returns the syllable byte (upper 4 bits = serial, lower 4 bits = type)
	GetSyllable(i int) uint8
	// GetCategory returns the shaper-specific category for a glyph
	GetCategory(i int) uint8
	// SetCategory sets the shaper-specific category for a glyph
	SetCategory(i int, cat uint8)
	// Len returns the number of glyphs
	Len() int
}

SyllableAccessor provides methods to access syllable information for dotted circle insertion. Different shapers (Indic, USE, Khmer) use different syllable storage mechanisms.

type TableType added in v0.0.4

type TableType int

TableType indicates which OpenType table we're processing. HarfBuzz equivalent: table_index in hb_ot_apply_context_t

const (
	TableGSUB TableType = 0 // GSUB table
	TableGPOS TableType = 1 // GPOS table
)

type Tag

type Tag uint32

Tag is a 4-byte OpenType tag.

func GetScriptTag added in v0.0.4

func GetScriptTag(cp Codepoint) Tag

GetScriptTag returns the OpenType script tag for a Unicode codepoint. Uses the UCD (Unicode Character Database) table for accurate script detection. HarfBuzz equivalent: unicode->script() in hb-unicode.hh

func LanguageToTag added in v0.0.4

func LanguageToTag(lang string) []Tag

LanguageToTag converts a BCP 47 language tag to OpenType language system tags. Returns nil if no mapping exists. HarfBuzz equivalent: hb_ot_tags_from_language() in hb-ot-tag.cc

func MakeTag

func MakeTag(a, b, c, d byte) Tag

MakeTag creates a Tag from 4 bytes.

func ScriptToTag added in v0.0.4

func ScriptToTag(sc Script) Tag

ScriptToTag returns the OpenType tag for a Script.

func (Tag) String

func (t Tag) String() string

String returns the tag as a 4-character string.

type TopDict

type TopDict struct {
	Version     int // SID
	Notice      int // SID
	FullName    int // SID
	FamilyName  int // SID
	Weight      int // SID
	FontBBox    [4]int
	CharStrings int    // Offset to CharStrings INDEX
	Private     [2]int // [size, offset]
	Charset     int    // Offset to Charset
	Encoding    int    // Offset to Encoding

	// CID fonts
	ROS      [3]int // Registry, Ordering, Supplement (SIDs)
	FDArray  int
	FDSelect int
	IsCID    bool
}

TopDict contains top-level font dictionary data.

type USECategory added in v0.0.4

type USECategory uint8
const (
	USE_O     USECategory = 0  // OTHER
	USE_B     USECategory = 1  // BASE
	USE_V     USECategory = 2  // VOWEL (no position)
	USE_VM    USECategory = 3  // VOWEL_MOD (no position)
	USE_N     USECategory = 4  // BASE_NUM
	USE_GB    USECategory = 5  // BASE_OTHER (Generic Base)
	USE_CGJ   USECategory = 6  // CGJ (Combining Grapheme Joiner)
	USE_F     USECategory = 7  // FINAL (no position)
	USE_FM    USECategory = 8  // FINAL_MOD (no position)
	USE_M     USECategory = 9  // MEDIAL (no position)
	USE_CM    USECategory = 10 // CONS_MOD (no position)
	USE_SUB   USECategory = 11 // CONS_SUB
	USE_H     USECategory = 12 // HALANT
	USE_HN    USECategory = 13 // HALANT_NUM
	USE_ZWNJ  USECategory = 14 // ZWNJ
	USE_SM    USECategory = 15 // SYLLABLE_MOD (no position)
	USE_WJ    USECategory = 16 // Word_Joiner
	USE_R     USECategory = 18 // REPHA
	USE_VPre  USECategory = 22 // VOWEL PRE
	USE_VMPre USECategory = 23 // VOWEL_MOD PRE
	USE_FAbv  USECategory = 24 // FINAL ABOVE
	USE_FBlw  USECategory = 25 // FINAL BELOW
	USE_FPst  USECategory = 26 // FINAL POST
	USE_MAbv  USECategory = 27 // MEDIAL ABOVE
	USE_MBlw  USECategory = 28 // MEDIAL BELOW
	USE_MPst  USECategory = 29 // MEDIAL POST
	USE_MPre  USECategory = 30 // MEDIAL PRE
	USE_CMAbv USECategory = 31 // CONS_MOD ABOVE
	USE_CMBlw USECategory = 32 // CONS_MOD BELOW
	USE_VAbv  USECategory = 33 // VOWEL ABOVE
	USE_VBlw  USECategory = 34 // VOWEL BELOW
	USE_VPst  USECategory = 35 // VOWEL POST
	USE_VMAbv USECategory = 37 // VOWEL_MOD ABOVE
	USE_VMBlw USECategory = 38 // VOWEL_MOD BELOW
	USE_VMPst USECategory = 39 // VOWEL_MOD POST
	USE_SMAbv USECategory = 41 // SYLLABLE_MOD ABOVE
	USE_SMBlw USECategory = 42 // SYLLABLE_MOD BELOW
	USE_CS    USECategory = 43 // CONS_WITH_STACKER
	USE_IS    USECategory = 44 // INVISIBLE_STACKER
	USE_FMAbv USECategory = 45 // FINAL_MOD ABOVE
	USE_FMBlw USECategory = 46 // FINAL_MOD BELOW
	USE_FMPst USECategory = 47 // FINAL_MOD POST
	USE_Sk    USECategory = 48 // SAKOT
	USE_G     USECategory = 49 // HIEROGLYPH
	USE_J     USECategory = 50 // HIEROGLYPH_JOINER
	USE_SB    USECategory = 51 // HIEROGLYPH_SEGMENT_BEGIN
	USE_SE    USECategory = 52 // HIEROGLYPH_SEGMENT_END
	USE_HVM   USECategory = 53 // HALANT_OR_VOWEL_MODIFIER
	USE_HM    USECategory = 54 // HIEROGLYPH_MOD
	USE_HR    USECategory = 55 // HIEROGLYPH_MIRROR
	USE_RK    USECategory = 56 // REORDERING_KILLER
)

type USESyllableInfo added in v0.0.4

type USESyllableInfo struct {
	Category     USECategory
	SyllableType USESyllableType
	Syllable     uint8     // Syllable index (upper 4 bits = serial, lower 4 bits = type)
	Codepoint    Codepoint // Original codepoint, needed for ZWNJ filtering
}

USESyllableInfo holds syllable information for a glyph.

type USESyllableType added in v0.0.4

type USESyllableType uint8

USESyllableType defines the types of syllables in USE. HarfBuzz equivalent: use_syllable_type_t in hb-ot-shaper-use-machine.hh:43-53

const (
	USE_ViramaTerminatedCluster USESyllableType = iota
	USE_SakotTerminatedCluster
	USE_StandardCluster
	USE_NumberJoinerTerminatedCluster
	USE_NumeralCluster
	USE_SymbolCluster
	USE_HieroglyphCluster
	USE_BrokenCluster
	USE_NonCluster
)

func (USESyllableType) String added in v0.0.4

func (t USESyllableType) String() string

String returns the name of the syllable type.

type VORG added in v0.0.6

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

VORG represents the Vertical Origin table (used by CFF/CFF2 fonts). It provides the vertical origin Y coordinate for glyphs.

func ParseVORG added in v0.0.6

func ParseVORG(data []byte) (*VORG, error)

ParseVORG parses the VORG table.

func (*VORG) GetVertOriginY added in v0.0.6

func (v *VORG) GetVertOriginY(glyph GlyphID) int16

GetVertOriginY returns the vertical origin Y for a glyph. Uses binary search on the sorted entries, falls back to defaultVertOriginY.

type ValueRecord

type ValueRecord struct {
	XPlacement int16 // Horizontal adjustment for placement
	YPlacement int16 // Vertical adjustment for placement
	XAdvance   int16 // Horizontal adjustment for advance
	YAdvance   int16 // Vertical adjustment for advance
}

ValueRecord holds positioning values.

func (*ValueRecord) IsZero

func (vr *ValueRecord) IsZero() bool

IsZero returns true if all values are zero.

type VarRegionList added in v0.0.3

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

VarRegionList holds the list of variation regions.

func (*VarRegionList) Evaluate added in v0.0.3

func (rl *VarRegionList) Evaluate(regionIndex int, coords []int) float64

Evaluate computes the scalar for a region at the given normalized coordinates. Coordinates are in F2DOT14 format (1.0 = 16384).

type Variation added in v0.0.3

type Variation struct {
	Tag   Tag
	Value float32
}

Variation represents a single axis value setting.

type Vhea added in v0.0.6

type Vhea struct {
	Version              uint32
	Ascender             int16  // Vertical typographic ascender
	Descender            int16  // Vertical typographic descender
	LineGap              int16  // Vertical typographic line gap
	AdvanceHeightMax     uint16 // Maximum advance height
	MinTopSideBearing    int16
	MinBottomSideBearing int16
	YMaxExtent           int16
	CaretSlopeRise       int16
	CaretSlopeRun        int16
	CaretOffset          int16
	MetricDataFormat     int16
	NumberOfVMetrics     uint16
}

Vhea represents the vertical header table.

func ParseVhea added in v0.0.6

func ParseVhea(data []byte) (*Vhea, error)

ParseVhea parses the vhea (vertical header) table.

type Vmtx added in v0.0.6

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

Vmtx represents the vertical metrics table.

func ParseVmtx added in v0.0.6

func ParseVmtx(data []byte, numberOfVMetrics, numGlyphs int) (*Vmtx, error)

ParseVmtx parses the vmtx table. It requires numberOfVMetrics from vhea and numGlyphs from maxp.

func (*Vmtx) GetAdvanceHeight added in v0.0.6

func (v *Vmtx) GetAdvanceHeight(glyph GlyphID) uint16

GetAdvanceHeight returns the advance height for a glyph.

func (*Vmtx) GetTsb added in v0.0.6

func (v *Vmtx) GetTsb(glyph GlyphID) int16

GetTsb returns the top side bearing for a glyph.

type VowelConstraint added in v0.0.4

type VowelConstraint struct {
	Codepoints []Codepoint
}

VowelConstraint represents a prohibited vowel sequence. If this sequence is found, a dotted circle should be inserted.

type ZeroWidthMarksType added in v0.0.4

type ZeroWidthMarksType int

ZeroWidthMarksType controls how zero-width marks are handled. HarfBuzz equivalent: hb_ot_shape_zero_width_marks_type_t in hb-ot-shaper.hh:44-48

const (
	// ZeroWidthMarksNone - Don't zero mark advances
	ZeroWidthMarksNone ZeroWidthMarksType = iota
	// ZeroWidthMarksByGDEFEarly - Zero mark advances early (before GPOS)
	ZeroWidthMarksByGDEFEarly
	// ZeroWidthMarksByGDEFLate - Zero mark advances late (after GPOS)
	ZeroWidthMarksByGDEFLate
)

Jump to

Keyboard shortcuts

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