opentype

package module
v0.0.0-...-a6d0fa7 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2023 License: Artistic-2.0 Imports: 17 Imported by: 2

README

OpenType

Add to go project with:

go get gitlab.com/font8/opentype

In your Go code:

r, err := os.Open("fontfile.ttf")
font, err := opentype.OpenFont(r)

END

Documentation

Index

Constants

View Source
const TerpLimitNesting = 10
View Source
const XS = 0

Shifts that select X-axis or Y-axis in ReadCoord()

View Source
const YS = 1

Variables

View Source
var CFFStandardString = []string{}/* 391 elements not displayed */
View Source
var MacStandardGlyph = []string{}/* 258 elements not displayed */

Functions

func ActionPrint

func ActionPrint(terp *Terp, code string)

func AlternateSubstitution

func AlternateSubstitution(bs []byte) interface{}

func AlternateSubstitutionFormat1

func AlternateSubstitutionFormat1(header *AlternateSubstRecord,
	r io.Reader,
	bs []byte,
) interface{}

func AsContours

func AsContours(ends []uint16, flags []byte, xs, ys []int16) []coff.Contour

Convert to sequence of Contour

func CFFCharsetMake

func CFFCharsetMake(n int, bs []byte) ([]int, error)

Section 13 - Charsets Low level primitive. Convert the bytes that represent the charset to a slice of n SIDs (String IDs, each one modelled as an int). The first SID is always 0 (for .notdef). This function prepends this 0, but it never appears in the representation. The output slice will be length n (or there is an error).

func COLRWrite

func COLRWrite(dir string, glyphs []ColrGlyph)

func ChainedSequenceContext

func ChainedSequenceContext(bs []byte) interface{}

func DataBlocksFromGlyf

func DataBlocksFromGlyf(font *T) ([][]byte, error)

Produce the slice of glyph data blocks from the `glyf` table.

func F64ToFixed

func F64ToFixed(f float64) int32

Convert float to OpenType 16.16 Fixed point. This is not exact. But it will round-trip.

func FeatureLookups

func FeatureLookups(bs []byte) []int

Convert binary representation of Feature Table into a list of lookups (Each lookup being an integer). Ignores the feature params (which are only used for certain features, see https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#feature-table

func FixedToF64

func FixedToF64(s int32) float64

Convert OpenType 16.16 Fixed point to floating point. This is exact.

func FloorLog2

func FloorLog2(x uint16) uint16

func Format12

func Format12(charmap map[rune]int) []byte

Compile a cmap format 12 subtable

func Format4

func Format4(charmap map[rune]int) []byte

Compile a format 4 subtable. Note that this will silently reject any non-BMP codes (not a bug, modern tools do this). f: find part in spec where sentinel is required Returns the bytes for a cmap format 4 subtable

func GlyfBytesToOutline

func GlyfBytesToOutline(block []byte) *coff.Outline

Convert byte-level TrueType representation to Outline.

func GlyfBytesToSimpleOutline

func GlyfBytesToSimpleOutline(
	r io.Reader, header GlyfHeaderRecord,
) *coff.Outline

func GlyfExpandFlags

func GlyfExpandFlags(r io.Reader, l int) []byte

Read the glyf flags from r into fully expanded form

func GlyfReadCoord

func GlyfReadCoord(r io.Reader, flags []byte, shift int) []int16

From the reader r, read out a sequence of coordinates (the returned value), under the control of flags. flags is used to determine the number of bytes to read for each coordinate (0, 1, or 2). shift (which should be XS or YS), is used to pick out the flags bits for the appropriate axis.

func Glyph

func Glyph(font *T) error

Implements the seefont glyph subcommand.

func GsubSubTableType

func GsubSubTableType(lookupType uint16, bs []byte) interface{}

Each GSUB Lookup sub table must be of the same type, described by a small enumerated int. https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#table-organization

func InterpretCharstring

func InterpretCharstring(
	root []byte, subr, gsubr [][]byte, action TerpAction,
)

Interprets (Type 2) charstring. This interpretation provides a skeleton, the actual drawing (or printing or flattening) is provided by `action`.

  • root is the starting byte stream (a glyph).
  • subr and gsubr are slices of the byte streams used for callsubr and callgsubr.

The contents of subr and gsubr will not be modified by this function, but also should not be modified by other code during this call. [Type2Spec] Appendix A most useful.

func LangSysFeatures

func LangSysFeatures(bs []byte) (*int, []int)

Convert binary representation of a LangSys table (a slice of bytes) to the optional required feature and the feature index list. Required feature is nil if no required feature (represented as 65535 in the binary).

func LigatureSubstApply

func LigatureSubstApply(sub LigatureSubst, input []int) (int, bool)

func LigatureSubstitution

func LigatureSubstitution(bs []byte) interface{}

func Loca

func Loca(loca *Table, long bool) <-chan int

Return a (chan yielding the) sequence of offsets into the glyf table. Offsets are byte offsets regardless of longFormat (shorts are converted).

func LookupGlyph

func LookupGlyph(lookup Lookup, glyph int) (int, error)

func LookupLigatureApply

func LookupLigatureApply(lookup Lookup, input []int) (
	liga int, acted bool, err error,
)

lookup should be a Lookup with LigatureSubst sub-table entries. input should be a proposed sequence of input glyphs. Result is a ligature if the lookup applied (0 if not); the acted bool is true if and only if the lokup applied; error is non-nil when there are errors.

func PostGlyphName

func PostGlyphName(names []string, index int) string

Return the glyph name for the given (glyph name) index. Standard names are returned for indexes 0 up to and including 257; The names slice is used for higher indexes.

func PostNames

func PostNames(post *Post) []string

func SIDRangeFlatten

func SIDRangeFlatten(ranges []SIDRange) []int

Convert a slice of SIDRange structs to a flat slice of SIDs.

func ScriptTable

func ScriptTable(bs []byte) (*Lang, []Lang)

Convert binary representation of a Script table to modelled Lang structs. The return value is the optional default language and a sequence of languages.

func SetFromCFF

func SetFromCFF(font *T) error

Set data and metadata from CFF

func SetGlyphData

func SetGlyphData(font *T) error

Set the font.GlyphData field.

func SingleSubstitution

func SingleSubstitution(bs []byte) interface{}

func TextCmap

func TextCmap(w io.Writer, charmap map[rune]int)

Write out to the file w the cmap in text format

func UTF16DecodeBE

func UTF16DecodeBE(bs []byte) string

func WriteCmap

func WriteCmap(w io.Writer, text io.Writer, charmap map[rune]int)

Write a complete binary cmap with all subtables to `w`; and write a text representation to `text`. Note the lack of flex: the caller has no choice over what subtable encodings are used. 3 subtables are written with Platform/Encoding: - 0/4 format 12 - 3/1 format 4 - 3/10 format 12 the format 12 subtables are shared by using the same offset.

Types

type AlternateSet

type AlternateSet []int

func AlternateSetMake

func AlternateSetMake(bs []byte) AlternateSet

type AlternateSubst

type AlternateSubst struct {
	Coverage      CoverageTable
	AlternateSets []AlternateSet
}

type AlternateSubstRecord

type AlternateSubstRecord struct {
	Format            uint16
	CoverageOffset    uint16
	AlternateSetCount uint16
}

type BaseGlyphRecord

type BaseGlyphRecord struct {
	GlyphID, FirstLayerIndex, NumLayers uint16
}

https://learn.microsoft.com/en-us/typography/opentype/spec/colr#baseglyph-and-layer-records

type CFF

type CFF struct {
	B                  []byte
	Major, Minor       int
	OffSize            int
	Name, TopDictIndex CFFIndex
	GsubrIndex, String CFFIndex

	Gsubr      [][]byte
	Subr       [][][]byte
	TopMap     []CFFMap
	PrivateMap []CFFMap
}

func CFFOpen

func CFFOpen(bs []byte) *CFF

func (*CFF) CharStrings

func (cff *CFF) CharStrings(top CFFMap) ([][]byte, string, error)

All the charstrings for a CFF font. And their type.

func (*CFF) CharsetSID

func (cff *CFF) CharsetSID(glyphCount int, top CFFMap) []int

Return the charset as a slice of SIDs (String IDs). Because a SID is mostly internal to a CFF font. most developers will want the more useful CharsetStrings() method.

func (*CFF) CharsetStrings

func (cff *CFF) CharsetStrings(i int) ([]string, error)

Return the charset strings, for font i. The result is a simple Go model which is a slice of strings, mapping from glyph index (starting at 0 for .notdef) to the glyph's name.

func (*CFF) GlyphCount

func (cff *CFF) GlyphCount(top CFFMap) int

The GlyphCount is implied by many structures. Here we use the number of CharStrings.

func (*CFF) Privatise

func (cff *CFF) Privatise()

Add the Private DICTs; and the Subrs which are contained with the Private block of bytes.

func (*CFF) SIDToStrings

func (cff *CFF) SIDToStrings(sid []int) []string

Convert SIDs to strings. The input sid is generally the output from CharsetSID.

func (*CFF) TopMaps

func (cff *CFF) TopMaps()

Realise the TopDict items as maps in the cff struct.

type CFF2Glyph

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

func (*CFF2Glyph) ToOutline

func (g *CFF2Glyph) ToOutline() *coff.Outline

type CFFDictItem

type CFFDictItem struct {
	// many of these are integeres, they are converted to float64 type
	Op   []float64
	Code string
}

func CFFDictMake

func CFFDictMake(bs []byte) []CFFDictItem

Convert the binary representation of a CFF DICT into a slice of modelled items (value, key pairs). Originally this only handled operators in TopDict, but now handles both Top and Private DICT operators. The spec makes it unclear what operators are allowed in what dictionaries.

type CFFHeader

type CFFHeader struct {
	Major, Minor, HdrSize, OffSize uint8
}

Section 6 - Header

type CFFIndex

type CFFIndex struct {
	B      []byte
	Offset []int
	Data   []uint8
	Item   [][]byte
}

func CFFIndexMake

func CFFIndexMake(bs []byte) (CFFIndex, int)

Make a CFFIndex from its binary representation returning a model for the index, and its binary size (so that you can skip the index and proceed to next item).

func (*CFFIndex) Itemise

func (index *CFFIndex) Itemise()

func (*CFFIndex) Length

func (index *CFFIndex) Length() int

Length of an index if the number of items in the index, which is one less than the length of the offset slice.

type CFFIndexHeader

type CFFIndexHeader struct {
	Count   uint16
	OffSize uint8
}

Section 5 - INDEX

type CFFMap

type CFFMap map[string][]float64

A simple go model for the DICT structures in a CFF.

func CFFDictAsMap

func CFFDictAsMap(d []CFFDictItem) CFFMap

Create a map from a slice of CFFDictItem. If there are any duplicate keys then the construction of the map overwrites them, meaning only the last of the duplicate keys will be used. Duplicate keys shouldn't happen in real-world fonts, but the alist-list structure doesn't prohibit it. The map's values share the slices ([]float64) with the input.

type COLRHeaderRecord

type COLRHeaderRecord struct {
	Version                uint16
	NumBaseGlyphRecords    uint16
	BaseGlyphRecordsOffset uint32
	LayerRecordsOffset     uint32
	NumLayerRecords        uint16
}

https://learn.microsoft.com/en-us/typography/opentype/spec/colr#colr-header

type ChainedSeqRule

type ChainedSeqRule struct {
	// The slice elements are Glyph IDs
	// :todo: check correct order on backtrack (it's reversed)
	Backtrack       []int
	Input           []int
	Lookahead       []int
	SequenceLookups []SequenceLookup
}

func ChainedSequenceRule

func ChainedSequenceRule(bs []byte) ChainedSeqRule

Return a single modelled ChainedSeqRule from the binary representation

type ChainedSeqRuleSet

type ChainedSeqRuleSet []ChainedSeqRule

type ChainedSequence

type ChainedSequence struct {
	Format uint16
	U      [3]uint16
}

ChainedSequenceContext shared by GPOS type 8 and GSUB type 6

type ChainedSequence1

type ChainedSequence1 struct {
	Format   int
	Coverage CoverageTable
	// 1 ruleset per covered glyph (notionally, according to
	// spec tho, the number of covered glyphs and the number of
	// rulesets should agree, but is not required).
	ChainedSeqRuleSet []ChainedSeqRuleSet
}

type ChainedSequence3

type ChainedSequence3 struct {
	Format int
	// :todo: check correct order on backtrack (it's reversed)
	BacktrackCoverage []CoverageTable
	InputCoverage     []CoverageTable
	LookaheadCoverage []CoverageTable
	SequenceLookups   []SequenceLookup
}

https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#chained-sequence-context-format-3-coverage-based-glyph-contexts

type ChainedSequenceContext1Record

type ChainedSequenceContext1Record struct {
	Format                 uint16 // 1 in this case
	CoverageOffset         uint16 // from beginning of this record
	ChainedSeqRuleSetCount uint16
}

https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2#chained-sequence-context-format-1-simple-glyph-contexts

type Cmap

type Cmap struct {
	Table
	Subtable []EncodingRecord
	Offset   []int
}

func NewCmap

func NewCmap(t Table) *Cmap

func (*Cmap) RangeTable

func (cmap *Cmap) RangeTable(offset int) *unicode.RangeTable

Return a unicode.RangeTable that covers the char code ranges of the segments.

func (*Cmap) Segments

func (cmap *Cmap) Segments(offset int) []Segment

Return the segments of the subtable at the given offset. Only for formats 4 and 12.0.

func (*Cmap) SubtableFormat

func (cmap *Cmap) SubtableFormat(offset int) int

Return the format of a cmap subtable as a int; a negative number is returned if the format is not an integer (format 12 and some others have a slot for fractional sub-format, but in 2023 it is only ever 0). Requires its offset (obtained from cmap.Offset).

func (*Cmap) Subtables

func (cmap *Cmap) Subtables() []EncodingRecord

type Cmap12GroupRecord

type Cmap12GroupRecord struct {
	StartCharCode, EndCharCode, StartGlyphID uint32
}

For Cmap Format 12

func (*Cmap12GroupRecord) Codes

func (g *Cmap12GroupRecord) Codes() []rune

func (*Cmap12GroupRecord) Items

func (g *Cmap12GroupRecord) Items() []CmapItem

func (*Cmap12GroupRecord) String

func (g *Cmap12GroupRecord) String() string

type Cmap12HeaderRecord

type Cmap12HeaderRecord struct {
	Format, Reserved uint16 // always 12
	Length           uint32
	Language         uint32
	NumGroups        uint32
}

type Cmap4Segment

type Cmap4Segment struct {
	StartCode, EndCode uint16
	Delta              int16
	Offset             uint16
	ComputedOffset     int
}

Models a segment of a cmap to glyph mapping https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-4-segment-mapping-to-delta-values

func (*Cmap4Segment) Codes

func (seg *Cmap4Segment) Codes() []rune

Convert to list of codes (the left-hand side of the map).

func (*Cmap4Segment) Items

func (seg *Cmap4Segment) Items() []CmapItem

Convert to list of items (one key,value pair per entry).

func (*Cmap4Segment) String

func (seg *Cmap4Segment) String() string

Convert to string representation.

type CmapHeaderRecord

type CmapHeaderRecord struct {
	Version, NumTables uint16
}

type CmapItem

type CmapItem struct {
	Code  rune
	Glyph int
}

A simple Go model for a single item of a cmap subtable; it maps a unicode codepoint to glyph index.

type ColrGlyph

type ColrGlyph struct {
	BaseGlyphIndex int
	Layers         []ColrLayer
}

Model for a ColrGlyph

type ColrLayer

type ColrLayer struct {
	GlyphIndex, Palette int
}

type CoverageRangeRecord

type CoverageRangeRecord struct {
	StartGlyphID, EndGlyphID, StartCoverageIndex uint16
}

https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#coverage-format-2

type CoverageTable

type CoverageTable []int

func Coverage

func Coverage(bs []byte) CoverageTable

Convert binary repreresentation of Coverage table to a simple slice of glyph indexes.

type CoverageTableHeader

type CoverageTableHeader struct {
	CoverageFormat uint16 // 1 or 2
	Count          uint16 // Number of items following

}

type EncodingRecord

type EncodingRecord struct {
	PlatformID uint16
	EncodingID uint16
	Offset     uint32
}

This is the record for the triple that encodes each subtable. In OpenType terminology (which is shorter and better) this is called an EncodingRecord. TrueType has the same record, but calls it subtable, and the EncodingID slot is called PlatformSpecificID. https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html

func (*EncodingRecord) Platform

func (sub *EncodingRecord) Platform() string

Return a string starting with 2 numbers separated by /: PLAT/END (eg 0/3 for Unicode BMP); if the platform/encoding combination is known a short description is appended to the returned string.

type Feature

type Feature struct {
	Tag    string
	Lookup []int
}

A feature is a tag (generally 4 ASCII bytes, such as "kern" or "liga"), and its lookups (each lookup identified by a small integer, the lookups themselves are stored elsewhere).

func Features

func Features(bs []byte) []Feature

https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#feature-list-table Convert binary representation of Feature List Table to slice of Feature.

type FeatureRecord

type FeatureRecord struct {
	Tag           [4]byte
	FeatureOffset uint16
}

type FeatureTableRecord

type FeatureTableRecord struct {
	FeatureParams, LookupIndexCount uint16
}

type Format4HeaderRecord

type Format4HeaderRecord struct {
	Format, Length, Language                           uint16
	SegCountX2, SearchRange, EntrySelector, RangeShift uint16
}

https://docs.microsoft.com/en-gb/typography/opentype/spec/cmap#format-4-segment-mapping-to-delta-values

type GlyfHeaderRecord

type GlyfHeaderRecord struct {
	NumberOfContours int16
	XMin, YMin       int16
	XMax, YMax       int16
}

Record (on disk format) for a single glyph in the glyf table. https://docs.microsoft.com/en-gb/typography/opentype/spec/glyf#glyph-headers

type GsubUnknown

type GsubUnknown struct {
	LookupType uint16
	// contains filtered or unexported fields
}

type HeadRecord

type HeadRecord struct {
	Version                         uint32
	FontRevision                    int32
	ChecksumAdjustment, MagicNumber uint32
	Flags                           uint16
	UnitsPerEm                      uint16
	Created, Modified               uint64
	XMin, YMin, XMax, YMax          int16
	MacStyle                        uint16
	LowestRecPPEM                   uint16
	FontDirectionHint               uint16
	IndexToLocFormat                int16
	GlyphDataFormat                 int16
}

https://docs.microsoft.com/en-gb/typography/opentype/spec/head

type HorizontalHeaderRecord

type HorizontalHeaderRecord struct {
	MajorVersion, MinorVersion                          uint16
	Ascender, Descender, LineGap                        int16
	AdvanceWidthMax                                     uint16
	MinLeftSideBearing, MinRightSideBearing, XMaxExtent int16
	CaretSlopeRise, CaretSlopeRun, CaretOffset          int16
	Reserved                                            [4]int16
	MetricDataFormat                                    int16
	NumberOfHMetrics                                    uint16
}

https://docs.microsoft.com/en-gb/typography/opentype/spec/hhea

type Lang

type Lang struct {
	Tag             string
	RequiredFeature *int
	Feature         []int
}

Model for a Language System. The OpenType spec mostly uses the term Language System instead of language because there may not be a one-to-one mapping (for example Japanese has several typographic conventions for certain glyphs according to historical periods of standardisation). Here though, i use the type Lang, on the understanding that this actually corresponds to an OpenType LangSys. Typographically there is no need to care about the distinction, there is simply a four-character code that is either in use or not. The required feature is optional (nil when not present). The Feature slice is a list of the features, each one being represented by its FeatureIndex.

type LangSysRecord

type LangSysRecord struct {
	LangSysTag    [4]byte
	LangSysOffset uint16
}

type LangSysTableRecord

type LangSysTableRecord struct {
	LookupOrder          uint16
	RequiredFeatureIndex uint16
	FeatureIndexCount    uint16
}

https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#language-system-table

type LangTagRecord

type LangTagRecord struct {
	Length, Offset uint16
}

Only used in Format 1 https://docs.microsoft.com/en-gb/typography/opentype/spec/name#naming-table-format-1

type LayerRecord

type LayerRecord struct {
	GlyphID, PaletteIndex uint16
}

type Ligature

type Ligature struct {
	Ligature int // a GlyphID
	// GlyphIDs of the components _including the initial glyph_
	Component []int
}

func LigatureMake

func LigatureMake(bs []byte) Ligature

type LigatureSet

type LigatureSet []Ligature

func LigatureSetMake

func LigatureSetMake(bs []byte) LigatureSet

type LigatureSubst

type LigatureSubst struct {
	Coverage     CoverageTable
	LigatureSets []LigatureSet
}

func LigatureSubstitutionFormat1

func LigatureSubstitutionFormat1(header *LigatureSubstRecord, r io.Reader, bs []byte) LigatureSubst

type LigatureSubstRecord

type LigatureSubstRecord struct {
	Format           uint16
	CoverageOffset   uint16
	LigatureSetCount uint16
}

https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#41-ligature-substitution-format-1 As of 2021-11-26, only one format

type Lookup

type Lookup struct {
	LookupRecord
	SubTable []interface{}
}

Model a Lookup table. https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#lookup-table

func GsubLookupSub

func GsubLookupSub(bs []byte) Lookup

Returns a Lookup. A word of warning: 1 Lookup Table has 1 Lookup Type; all the subtables are of the same Lookup Type; this Lookup Type is store with the Lookup Table, not the subtables. The Lookup Types are a small integer that varies between GPOS and GSUB TrueType tables.

func GsubLookups

func GsubLookups(bs []byte) []Lookup

Return a slice of Lookup, given the bytes for the Lookup List Table (and all bytes following). https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#lookup-list-table

type LookupRecord

type LookupRecord struct {
	LookupType, LookupFlag, SubTableCount uint16
}

type Metric

type Metric struct {
	Advance, Bearing int
}

Metric to be used for either Horizontal or Vertical metric. For Horizontal: - Advance is Advance Width - Bearing is Left Side Bearing For Vertical: - Advance is Advance Height - Bearing is Top Bearing (these follow hmtx and vmtx in OpenType)

type MultipleSubst

type MultipleSubst struct {
	Coverage  CoverageTable
	Sequences []Sequence
}

func MultipleSubstitution

func MultipleSubstitution(bs []byte) MultipleSubst

type MultipleSubstRecord

type MultipleSubstRecord struct {
	Format         uint16
	CoverageOffset uint16
	SequenceCount  uint16
}

type Name

type Name struct {
	NameRecord
	PlatEnc string // Platform and Encoding as single string
	Lang    string
	Value   string
}

Decoded and modelled names. Because of platform and encoding issues, it's possible that not all NameRecord objects can be successfully decoded.

type NameHeaderRecord

type NameHeaderRecord struct {
	Format       uint16
	Count        uint16
	StringOffset uint16
}

type NameRecord

type NameRecord struct {
	PlatformID, EncodingID, LanguageID, NameID uint16
	Length, Offset                             uint16
}

https://docs.microsoft.com/en-gb/typography/opentype/spec/name#name-records

type NameTable

type NameTable struct {
	NameHeaderRecord
	Lrec []LangTagRecord
	Nrec []NameRecord
	B    []byte
}

func NewName

func NewName(table Table) *NameTable

func (*NameTable) DecodeName

func (n *NameTable) DecodeName(record *NameRecord) *Name

func (*NameTable) FullName

func (nt *NameTable) FullName() string

Return the "Full Name" of the font, derived from the OpenType name table. This function uses the name record with Name ID 4; the OpenType spec describes Name ID 4 as "Full font name".

This function searches only the Windows platform records, and returns the first one from the following sequence: - the first English-language record; - the first record; - the empty string "" (there are no Windows platform records)

Notes on Platform/Encoding/Language. Each record has a Platform/Encoding/Language triple; a given ID (such as 4) may have several records. The intention behind Platform is that one code is used for Macintosh and one code is used for Windows.

In practice in 2022, modern fonts supply Windows platform records, regardless of the intended target; all rendering systems can interpret Windows platform records.

Most fonts also supply Macintosh platform records but usage varies: - duplicate set (for example Ubuntu Mono) - none, only Windows platform (for example Zilla Slab, Roboto Mono) - minimal set (historical MS system fonts) There is also a _Unicode_ platform, presumably intended for platforms such as Unix and Plan 9, very few fonts seems to use it (some MS fonts supplied by Monotype such as Arial and Times New Roman). The Unicode platform seems largely irrelevant in 2022.

func (*NameTable) RecordToString

func (n *NameTable) RecordToString(record *NameRecord) string

Show the name record in printable form.

type OS2HeaderVersion0Record

type OS2HeaderVersion0Record struct {
	Version                                  uint16 // 1
	XAvgCharWidth                            int16
	WeightClass, WidthClass                  uint16
	FsType                                   uint16
	YSubscriptXSize, YSubscriptYSize         int16
	YSubscriptXOffset, YSubscriptYOffset     int16
	YSuperscriptXSize, YSuperscriptYSize     int16
	YSuperscriptXOffset, YSuperscriptYOffset int16
	YStrikeoutSize, YStrikeoutPosition       int16
	FamilyClass                              int16
	Panose                                   [10]byte
	UnicodeRange                             [4]uint32
	VendID                                   [4]byte
	FsSelection                              uint16
	FirstCharIndex, LastCharIndex            uint16
	TypoAscender, TypoDescender, TypoLineGap int16
	WinAscent, WinDescent                    uint16
}

https://learn.microsoft.com/en-gb/typography/opentype/spec/os2#version-0

type OS2HeaderVersion1Record

type OS2HeaderVersion1Record struct {
	OS2HeaderVersion0Record
	CodePageRange [2]uint32 // Only in Version ≥ 1
}

https://learn.microsoft.com/en-gb/typography/opentype/spec/os2#version-1

type OS2HeaderVersion2Record

type OS2HeaderVersion2Record struct {
	OS2HeaderVersion1Record
	XHeight, CapHeight int16
	DefaultChar        uint16
	BreakChar          uint16
	MaxContext         uint16
}

According to Microsoft documentation, Versions 2, 3, and 4 have the same structure (but possibly slightly different interpretations). https://learn.microsoft.com/en-gb/typography/opentype/spec/os2#version-4

type OffsetTableRecord

type OffsetTableRecord struct {
	SfntVersion                            uint32
	NumTables                              uint16
	SearchRange, EntrySelector, RangeShift uint16
}

Global header tables

type OutlineGlyph

type OutlineGlyph interface {
	ToOutline() *coff.Outline
}

type PC

type PC struct {

	// name of subroutine
	In string
	// contains filtered or unexported fields
}

A model for the program counter.

type Post

type Post struct {
	PostHeaderRecord
	Names []string
}

func PostOpen

func PostOpen(bs []byte) *Post

type PostHeaderRecord

type PostHeaderRecord struct {
	Format                                uint32
	ItalicAngle                           int32
	UnderlinePosition, UnderlineThickness int16
	IsFixedPitch                          uint32
	MinMemType42, MaxMemType42            uint32
	MinMemType1, MaxMemType1              uint32
}

type SIDRange

type SIDRange struct {
	SID, N int
}

type Script

type Script struct {
	Tag         string
	DefaultLang *Lang
	Lang        []Lang
}

Model for a Script. Each script has a name which is a 4 letter tag, see https://docs.microsoft.com/en-gb/typography/opentype/spec/scripttags. A Script consists of a list of languages (Language System, really), each language identified by a four-character code, and an additional and optional default language system (which need not correspond to any other actual language, but is commonly referred to using the reserved code `dflt`).

func Scripts

func Scripts(bs []byte) []Script

Convert the binary ScriptList table to a modelled Script slice.

type ScriptTableRecord

type ScriptTableRecord struct {
	DefaultLangSysOffset uint16
	LangSysCount         uint16
}

https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#script-table-and-language-system-record Parsed by ScripTable function.

type Segment

type Segment interface {
	String() string
	Codes() []rune
	Items() []CmapItem
}

Shared interface used by format 4 and 12

func Format12Segments

func Format12Segments(b []byte) []Segment

type Sequence

type Sequence []int

Sequence of glyphs

func SequenceMake

func SequenceMake(bs []byte) Sequence

Multiple Substitution Format 1, Sequence table, binary representation to model. :todo: same as AlternateSetMake?

type SequenceLookup

type SequenceLookup struct {
	// Index into input
	SequenceIndex int
	// Lookup to be applied at that point in the input
	LookupIndex int
}

A pair that models the Sequence Lookup Record

type SequenceLookupRecord

type SequenceLookupRecord struct {
	SequenceIndex, LookupListIndex uint16
}

https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#sequence-lookup-record Specifies an action to be applied to a glyph in the input sequence (for a variety of contextual lookups). The SequenceIndex is the target of the action; the LookupListIndex specifies (nested/recursively) a lookup to apply.

type SingleSubst

type SingleSubst struct {
	Format uint16
	U      [2]uint16
}

type SingleSubst1

type SingleSubst1 struct {
	Format   int
	Coverage CoverageTable
	Delta    int
}

func SingleSubstitutionFormat1

func SingleSubstitutionFormat1(bs []byte) SingleSubst1

func (*SingleSubst1) Apply

func (sub *SingleSubst1) Apply(glyph int) int

Apply the SingleSubst1 to a glyph, transforming it.

type SingleSubst1Record

type SingleSubst1Record struct {
	Format         uint16
	CoverageOffset uint16
	Delta          int16
}

type SingleSubst2

type SingleSubst2 struct {
	Format int
	// Combines the CoverageTable and the substitute glyph array
	// into a single map.
	Substitute      map[int]int
	Coverage        CoverageTable
	SubstituteGlyph []int
}

func SingleSubstitutionFormat2

func SingleSubstitutionFormat2(bs []byte) SingleSubst2

type SingleSubst2Record

type SingleSubst2Record struct {
	Format         uint16
	CoverageOffset uint16
	GlyphCount     uint16
}

type T

type T struct {
	OffsetTableRecord
	Table     map[string]Table
	Tags      []string // Just the tags, in the order they appear
	GlyphData [][]byte
	GlyphType string // "glyf" or "CFF 2"
	Source    string // intended to be used as a file name
	// contains filtered or unexported fields
}

func NewT

func NewT() *T

func OpenFont

func OpenFont(r io.ReadSeeker) (*T, error)

func (*T) CFFGlyphNames

func (font *T) CFFGlyphNames(table *Table) ([]string, error)

func (*T) FetchGlyph

func (font *T) FetchGlyph(i int) OutlineGlyph

Return Glyph from its index.

func (*T) Flavor

func (font *T) Flavor() string

Return the flavor of the font as a string. Flavor is a term used by WOFF to refer to the 4-byte signature of the contained sfnt font-file. Apple TrueType uses "scaler type"; Microsoft OpenType uses "sfntVersion". The input is the uint32 made up of the first 4 bytes of the file. If all 4 bytes are ASCII then they are returned as a 4 byte string. Otherwise a hex representation of the 32-bit value is returned.

func (*T) GlyphCount

func (font *T) GlyphCount() (int, error)

Number of Glyphs

func (*T) GlyphDataBlocks

func (font *T) GlyphDataBlocks() ([][]byte, error)

func (*T) GlyphNames

func (font *T) GlyphNames() ([]string, error)

Return the glyph names, in glyph index order so that the slice can be indexed by glyph number to get the correct name. Uses either the CFF or the post table.

func (*T) HMetrics

func (font *T) HMetrics() ([]Metric, error)

func (*T) PostGlyphNames

func (font *T) PostGlyphNames(table *Table) []string

func (*T) VMetrics

func (font *T) VMetrics() ([]Metric, error)

type TTGlyph

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

func (*TTGlyph) ToOutline

func (g *TTGlyph) ToOutline() *coff.Outline

type Table

type Table struct {
	Tag      string
	Checksum uint32
	Offset   uint32
	B        []byte
}

Each table in a, correctly formed, OTF file is modelled with a tag and its content as a slice of bytes.

type TableRecord

type TableRecord struct {
	Tag      [4]byte
	Checksum uint32
	Offset   uint32
	Length   uint32
}

type Terp

type Terp struct {
	Subr      [][]byte // Set once, never changes
	Gsubr     [][]byte // Set once, never changes
	BiasSubr  int
	BiasGsubr int
	PC
	// Total number of callsubr/callgsubr
	// (to limit accidentally or deliberately costly charstrings)
	CallCount int
	Width     *float64 // the glyph width, optional
	HStemHint [][]float64
	VStemHint [][]float64
	// Active hints
	// priority list of counters
	Stack       []float64
	ReturnStack []PC
}

A minimal interpreter that can't draw.

func (*Terp) FetchSubr

func (terp *Terp) FetchSubr(global bool, v float64) PC

Fetch the code (and a name) for the (global?) subr. The value v should be the _biased_ number, as it appears in the charstring byte stream. The returned name incorporates the _unbiased_ number, which will be used in the Subr/Gsubr section of the .ttx file.

func (*Terp) FixBias

func (terp *Terp) FixBias()

The bias for callsubr and callgsubr is computed (once hopefully) and stored in the terp.

func (*Terp) MaskBytes

func (terp *Terp) MaskBytes() int

How many bytes follow a hintmask operator?

func (*Terp) SetWidth

func (terp *Terp) SetWidth()

Set (optioonal) Width, based on whether the stack length is odd or even.

func (*Terp) SetWidth2

func (terp *Terp) SetWidth2()

Set (optioonal) Width, based on whether the stack has length 2. Same as SetWidth, but for hmoveto and vmoveto

type TerpAction

type TerpAction func(terp *Terp, code string)

func MakeActionOutline

func MakeActionOutline() (TerpAction, *coff.Outline)

Return a TerpAction and an Outline. Executing the action (by passing it to InterpretCharstring) has the effect of accumulating contours into the returned outline.

Jump to

Keyboard shortcuts

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