// SPDX-License-Identifier: Unlicense OR BSD-3-Clause

package cff

// code is adapted from golang.org/x/image/font/sfnt

import (
	
	
	

	ps 
	
)

var errUnsupportedCFFVersion = errors.New("unsupported CFF version")

// CFF represents a parsed CFF font, as found in the 'CFF ' Opentype table.
type CFF struct {
	userStrings userStrings
	fdSelect    fdSelect // only valid for CIDFonts
	charset     []uint16 // indexed by glyph ID

	cidFontName string

	// Charstrings contains the actual glyph definition.
	// It has a length of numGlyphs and is indexed by glyph ID.
	// See `LoadGlyph` for a way to intepret the glyph data.
	Charstrings [][]byte

	fontName    []byte // name from the Name INDEX
	globalSubrs [][]byte

	// array of length 1 for non CIDFonts
	// For CIDFonts, it can be safely indexed by `fdSelect` output
	localSubrs [][][]byte
}

// Parse parses a .cff font file.
// Although CFF enables multiple font or CIDFont programs to be bundled together in a
// single file, embedded CFF font file in PDF or in TrueType/OpenType fonts
// shall consist of exactly one font or CIDFont. Thus, this function
// returns an error if the file contains more than one font.
func ( []byte) (*CFF, error) {
	// read 4 bytes to check if its a supported CFF file
	if  := len();  < 4 {
		return nil, fmt.Errorf("EOF: expected length: %d, got %d", 4, )
	}
	if [0] != 1 || [1] != 0 || [2] != 4 {
		return nil, errUnsupportedCFFVersion
	}
	 := cffParser{src: , offset: 4}
	,  := .parse()
	if  != nil {
		return nil, 
	}

	if len() > 1 {
		return nil, errors.New("only one font is allowed CFF table")
	}

	return &[0], nil
}

// GlyphName returns the name of the glyph or an empty string if not found.
func ( *CFF) ( opentype.GID) string {
	if .fdSelect != nil || int() >= len(.charset) {
		return ""
	}
	,  := .userStrings.getString(.charset[])
	return 
}

// since SID = 0 means .notdef, we use a reserved value
// to mean unset
const unsetSID = uint16(0xFFFF)

type userStrings [][]byte

// return either the predefined string or the user defined one
func ( userStrings) ( uint16) (string, error) {
	if  == unsetSID {
		return "", nil
	}
	if  < 391 {
		return stdStrings[], nil
	}
	 -= 391
	if int() >= len() {
		return "", fmt.Errorf("invalid glyph index %d", )
	}
	return string([]), nil
}

// Compact Font Format (CFF) fonts are written in PostScript, a stack-based
// programming language.
//
// A fundamental concept is a DICT, or a key-value map, expressed in reverse
// Polish notation. For example, this sequence of operations:
//   - push the number 379
//   - version operator
//   - push the number 392
//   - Notice operator
//   - etc
//   - push the number 100
//   - push the number 0
//   - push the number 500
//   - push the number 800
//   - FontBBox operator
//   - etc
//
// defines a DICT that maps "version" to the String ID (SID) 379, "Notice" to
// the SID 392, "FontBBox" to the four numbers [100, 0, 500, 800], etc.
//
// The first 391 String IDs (starting at 0) are predefined as per the CFF spec
// Appendix A, in 5176.CFF.pdf referenced below. For example, 379 means
// "001.000". String ID 392 is not predefined, and is mapped by a separate
// structure, the "String INDEX", inside the CFF data. (String ID 391 is also
// not predefined. Specifically for go-opentype-testdata/data/toys/CFFTest.otf, 391 means
// "uni4E2D", as this font contains a glyph for U+4E2D).
//
// The actual glyph vectors are similarly encoded (in PostScript), in a format
// called Type 2 Charstrings. The wire encoding is similar to but not exactly
// the same as CFF's. For example, the byte 0x05 means FontBBox for CFF DICTs,
// but means rlineto (relative line-to) for Type 2 Charstrings. See
// 5176.CFF.pdf Appendix H and 5177.Type2.pdf Appendix A in the PDF files
// referenced below.
//
// The relevant specifications are:
//   - http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf
//   - http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5177.Type2.pdf
type cffParser struct {
	src    []byte // whole input
	offset int    // current position
}

func ( *cffParser) () ([]CFF, error) {
	// header was checked prior to this call

	// Parse the Name INDEX.
	,  := .parseNames()
	if  != nil {
		return nil, 
	}

	,  := .parseTopDicts()
	if  != nil {
		return nil, 
	}
	// 5176.CFF.pdf section 8 "Top DICT INDEX" says that the count here
	// should match the count of the Name INDEX
	if len() != len() {
		return nil, fmt.Errorf("top DICT length doest not match Names (%d, %d)", len(),
			len())
	}

	// parse the String INDEX.
	,  := .parseUserStrings()
	if  != nil {
		return nil, 
	}

	 := make([]CFF, len())

	// use the strings to fetch the PSInfo
	for ,  := range  {
		[].fontName = []
		[].userStrings = 

		// skip PSInfo, and cidFontName

		[].cidFontName,  = .getString(.cidFontName)
		if  != nil {
			return nil, 
		}
	}

	// Parse the Global Subrs [Subroutines] INDEX,
	// shared among all fonts.
	,  := .parseIndex()
	if  != nil {
		return nil, 
	}

	for ,  := range  {
		[].globalSubrs = 

		// Parse the CharStrings INDEX, whose location was found in the Top DICT.
		if  = .seek(.charStringsOffset);  != nil {
			return nil, 
		}
		[].Charstrings,  = .parseIndex()
		if  != nil {
			return nil, 
		}
		 := uint16(len([].Charstrings))

		[].charset,  = .parseCharset(.charsetOffset, )
		if  != nil {
			return nil, 
		}

		// skip encoding

		if !.isCIDFont {
			// Parse the Private DICT, whose location was found in the Top DICT.
			var  [][]byte
			,  = .parsePrivateDICT(.privateDictOffset, .privateDictLength)
			if  != nil {
				return nil, 
			}
			[].localSubrs = [][][]byte{}
		} else {
			// Parse the Font Dict Select data, whose location was found in the Top
			// DICT.
			[].fdSelect,  = .parseFDSelect(.fdSelect, )
			if  != nil {
				return nil, 
			}
			 := [].fdSelect.extent()

			// Parse the Font Dicts. Each one contains its own Private DICT.
			if  = .seek(.fdArray);  != nil {
				return nil, 
			}
			,  := .parseTopDicts()
			if  != nil {
				return nil, 
			}
			if len() <  {
				return nil, fmt.Errorf("invalid number of font dicts: %d (for %d)",
					len(), )
			}
			 := make([][][]byte, len())
			for ,  := range  {
				[],  = .parsePrivateDICT(.privateDictOffset, .privateDictLength)
				if  != nil {
					return nil, 
				}
			}
			[].localSubrs = 
		}
	}

	return , nil
}

func ( *cffParser) () ([]topDict, error) {
	// Parse the Top DICT INDEX.
	,  := .parseIndex()
	if  != nil {
		return nil, 
	}

	 := make([]topDict, len()) // guarded by uint16 max size
	var  ps.Machine
	for ,  := range  {
		 := &[]

		// set default value before parsing
		.underlinePosition = -100
		.underlineThickness = 50
		.version = unsetSID
		.notice = unsetSID
		.fullName = unsetSID
		.familyName = unsetSID
		.weight = unsetSID
		.cidFontName = unsetSID

		if  = .Run(, nil, nil, );  != nil {
			return nil, 
		}
	}
	return , nil
}

// src does NOT includes header, but starts at the array offset
// also returns the length read from 'src'
func parseIndexContent( []byte,  indexStart) ([][]byte, int, error) {
	if .count == 0 {
		return nil, 0, nil
	}
	 := int(.offSize)
	 := int(.count+1) * 
	if  := len();  <  {
		return nil, 0, fmt.Errorf("reading INDEX offsets: EOF: expected length: %d, got %d", , )
	}
	 := make([][]byte, .count)
	 := [:]

	 := 0
	for  := range  {
		// In the same paragraph, "Therefore the first element of the offset
		// array is always 1" before correcting for the off-by-1.
		 := int(bigEndian([(+1)* : (+2)*]))

		// Locations are off by 1 byte. 5176.CFF.pdf section 5 "INDEX Data"
		// says that "Offsets in the offset array are relative to the byte that
		// precedes the object data... This ensures that every object has a
		// corresponding offset which is always nonzero".
		if  == 0 {
			return nil, 0, errors.New("invalid INDEX locations (0)")
		}
		--

		if  <  { // Check that locations are increasing
			return nil, 0, errors.New("invalid INDEX locations (not increasing)")
		}

		// Check that locations are in bounds, that is offsetsLength + loc <= len(src)
		if int() > len() {
			return nil, 0, errors.New("invalid INDEX locations (out of bounds)")
		}

		[] = [:]
		 = 
	}
	return ,  + , nil
}

// parse the general form of an index
func ( *cffParser) () ([][]byte, error) {
	, ,  := .parseIndexHeader()
	if  != nil {
		return nil, 
	}

	, ,  := parseIndexContent(.src[.offset:], indexStart{count: uint32(), offSize: })
	.offset += 

	return , 
}

// parse the Name INDEX
func ( *cffParser) () ([][]byte, error) {
	return .parseIndex()
}

// parse the String INDEX
func ( *cffParser) () (userStrings, error) {
	,  := .parseIndex()
	return userStrings(), 
}

// Parse the charset data, whose location was found in the Top DICT.
func ( *cffParser) ( int32,  uint16) ([]uint16, error) {
	// Predefined charset may have offset of 0 to 2 // Table 22
	var  []uint16
	switch  {
	case 0: // ISOAdobe
		 = charsetISOAdobe[:]
	case 1: // Expert
		 = charsetExpert[:]
	case 2: // ExpertSubset
		 = charsetExpertSubset[:]
	default: // custom
		if  := .seek();  != nil {
			return nil, 
		}
		,  := .read(1)
		if  != nil {
			return nil, 
		}
		 = make([]uint16, )
		switch [0] { // format
		case 0:
			,  = .read(2 * (int() - 1)) // ".notdef" is omited, and has an implicit SID of 0
			if  != nil {
				return nil, 
			}
			for  := uint16(1);  < ; ++ {
				[] = binary.BigEndian.Uint16([2*-2:])
			}
		case 1:
			for  := uint16(1);  < ; {
				,  = .read(3)
				if  != nil {
					return nil, 
				}
				,  := binary.BigEndian.Uint16(), uint16([2])
				for  := uint16(0);  <=  &&  < ; ++ {
					[] =  + 
					++
				}
			}
		case 2:
			for  := uint16(1);  < ; {
				,  = .read(4)
				if  != nil {
					return nil, 
				}
				,  := binary.BigEndian.Uint16(), binary.BigEndian.Uint16([2:])
				for  := uint16(0);  <=  &&  < ; ++ {
					[] =  + 
					++
				}
			}
		default:
			return nil, fmt.Errorf("invalid custom charset format %d", [0])
		}
	}
	return , nil
}

// parseFDSelect parses the Font Dict Select data as per 5176.CFF.pdf section
// 19 "FDSelect".
func ( *cffParser) ( int32,  uint16) (fdSelect, error) {
	if  := .seek();  != nil {
		return nil, 
	}
	, ,  := parseFdSelect(.src[:], int())
	if  != nil {
		return nil, 
	}
	return , 
}

// Parse Private DICT and the Local Subrs [Subroutines] INDEX
func ( *cffParser) (,  int32) ([][]byte, error) {
	if  == 0 {
		return nil, nil
	}
	if  := .seek();  != nil {
		return nil, 
	}
	,  := .read(int())
	if  != nil {
		return nil, 
	}
	var (
		  ps.Machine
		 privateDict
	)
	if  = .Run(, nil, nil, &);  != nil {
		return nil, 
	}

	if .subrsOffset == 0 {
		return nil, nil
	}

	// "The local subrs offset is relative to the beginning of the Private DICT data"
	if  = .seek( + .subrsOffset);  != nil {
		return nil, errors.New("invalid local subroutines offset")
	}
	,  := .parseIndex()
	if  != nil {
		return nil, 
	}
	return , nil
}

// read returns the n bytes from p.offset and advances p.offset by n.
func ( *cffParser) ( int) ([]byte, error) {
	if  < 0 || len(.src) < .offset+ {
		return nil, errors.New("invalid CFF font file (EOF)")
	}
	 := .src[.offset : .offset+]
	.offset += 
	return , nil
}

func ( *cffParser) ( int32) error {
	if  < 0 || len(.src) < int() {
		return errors.New("invalid CFF font file (EOF)")
	}
	.offset = int()
	return nil
}

func bigEndian( []byte) uint32 {
	switch len() {
	case 1:
		return uint32([0])
	case 2:
		return uint32([0])<<8 | uint32([1])
	case 3:
		return uint32([0])<<16 | uint32([1])<<8 | uint32([2])
	case 4:
		return uint32([0])<<24 | uint32([1])<<16 | uint32([2])<<8 | uint32([3])
	}
	panic("unreachable")
}

func ( *cffParser) () ( uint16,  uint8,  error) {
	,  := .read(2)
	if  != nil {
		return 0, 0, 
	}
	 = binary.BigEndian.Uint16()
	// 5176.CFF.pdf section 5 "INDEX Data" says that "An empty INDEX is
	// represented by a count field with a 0 value and no additional fields.
	// Thus, the total size of an empty INDEX is 2 bytes".
	if  == 0 {
		return , 0, nil
	}
	,  = .read(1)
	if  != nil {
		return 0, 0, 
	}
	 = [0]
	if  < 1 || 4 <  {
		return 0, 0, fmt.Errorf("invalid offset size %d", )
	}
	return , , nil
}

// topDict contains fields specific to the Top DICT context.
type topDict struct {
	// SIDs, to be decoded using the string index
	version, notice, fullName, familyName, weight      uint16
	isFixedPitch                                       bool
	italicAngle, underlinePosition, underlineThickness float32
	charsetOffset                                      int32
	encodingOffset                                     int32
	charStringsOffset                                  int32
	fdArray                                            int32
	fdSelect                                           int32
	isCIDFont                                          bool
	cidFontName                                        uint16
	privateDictOffset                                  int32
	privateDictLength                                  int32
}

func ( *topDict) () ps.Context { return ps.TopDict }

func ( *topDict) ( *ps.Machine,  ps.Operator) error {
	 := topDictOperators[0]
	if .IsEscaped {
		 = topDictOperators[1]
	}
	if int(.Operator) >= len() {
		return fmt.Errorf("invalid operator %s in Top Dict", )
	}
	 := [.Operator]
	if .run == nil {
		return fmt.Errorf("invalid operator %s in Top Dict", )
	}
	if .ArgStack.Top < .numPop {
		return fmt.Errorf("invalid number of arguments for operator %s in Top Dict", )
	}
	 := .run(, )
	if  != nil {
		return 
	}
	 = .ArgStack.PopN(.numPop)
	return 
}

// The Top DICT operators are defined by 5176.CFF.pdf Table 9 "Top DICT
// Operator Entries" and Table 10 "CIDFont Operator Extensions".
type topDictOperator struct {
	// run is the function that implements the operator. Nil means that we
	// ignore the operator, other than popping its arguments off the stack.
	run func(*topDict, *ps.Machine) error

	// numPop is the number of stack values to pop. -1 means "array" and -2
	// means "delta" as per 5176.CFF.pdf Table 6 "Operand Types".
	numPop int32
}

func topDictNoOp(*topDict, *ps.Machine) error { return nil }

var topDictOperators = [2][]topDictOperator{
	// 1-byte operators.
	{
		0: {func( *topDict,  *ps.Machine) error {
			.version = .ArgStack.Uint16()
			return nil
		}, +1 /*version*/},
		1: {func( *topDict,  *ps.Machine) error {
			.notice = .ArgStack.Uint16()
			return nil
		}, +1 /*Notice*/},
		2: {func( *topDict,  *ps.Machine) error {
			.fullName = .ArgStack.Uint16()
			return nil
		}, +1 /*FullName*/},
		3: {func( *topDict,  *ps.Machine) error {
			.familyName = .ArgStack.Uint16()
			return nil
		}, +1 /*FamilyName*/},
		4: {func( *topDict,  *ps.Machine) error {
			.weight = .ArgStack.Uint16()
			return nil
		}, +1 /*Weight*/},
		5:  {topDictNoOp, -1 /*FontBBox*/},
		13: {topDictNoOp, +1 /*UniqueID*/},
		14: {topDictNoOp, -1 /*XUID*/},
		15: {func( *topDict,  *ps.Machine) error {
			.charsetOffset = int32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*charset*/},
		16: {func( *topDict,  *ps.Machine) error {
			.encodingOffset = int32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*Encoding*/},
		17: {func( *topDict,  *ps.Machine) error {
			.charStringsOffset = int32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*CharStrings*/},
		18: {func( *topDict,  *ps.Machine) error {
			.privateDictLength = int32(.ArgStack.Vals[.ArgStack.Top-2])
			.privateDictOffset = int32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +2 /*Private*/},
	},
	// 2-byte operators. The first byte is the escape byte.
	{
		0: {topDictNoOp, +1 /*Copyright*/},
		1: {func( *topDict,  *ps.Machine) error {
			.isFixedPitch = .ArgStack.Vals[.ArgStack.Top-1] == 1
			return nil
		}, +1 /*isFixedPitch*/},
		2: {func( *topDict,  *ps.Machine) error {
			.italicAngle = float32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*ItalicAngle*/},
		3: {func( *topDict,  *ps.Machine) error {
			.underlinePosition = float32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*UnderlinePosition*/},
		4: {func( *topDict,  *ps.Machine) error {
			.underlineThickness = float32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*UnderlineThickness*/},
		5: {topDictNoOp, +1 /*PaintType*/},
		6: {func( *topDict,  *ps.Machine) error {
			if  := int(.ArgStack.Vals[.ArgStack.Top-1]);  != 2 {
				return fmt.Errorf("charstring type %d not supported", )
			}
			return nil
		}, +1 /*CharstringType*/},
		7:  {topDictNoOp, -1 /*FontMatrix*/},
		8:  {topDictNoOp, +1 /*StrokeWidth*/},
		20: {topDictNoOp, +1 /*SyntheticBase*/},
		21: {topDictNoOp, +1 /*PostScript*/},
		22: {topDictNoOp, +1 /*BaseFontName*/},
		23: {topDictNoOp, -2 /*BaseFontBlend*/},
		30: {func( *topDict,  *ps.Machine) error {
			.isCIDFont = true
			return nil
		}, +3 /*ROS*/},
		31: {topDictNoOp, +1 /*CIDFontVersion*/},
		32: {topDictNoOp, +1 /*CIDFontRevision*/},
		33: {topDictNoOp, +1 /*CIDFontType*/},
		34: {topDictNoOp, +1 /*CIDCount*/},
		35: {topDictNoOp, +1 /*UIDBase*/},
		36: {func( *topDict,  *ps.Machine) error {
			.fdArray = int32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*FDArray*/},
		37: {func( *topDict,  *ps.Machine) error {
			.fdSelect = int32(.ArgStack.Vals[.ArgStack.Top-1])
			return nil
		}, +1 /*FDSelect*/},
		38: {func( *topDict,  *ps.Machine) error {
			.cidFontName = .ArgStack.Uint16()
			return nil
		}, +1 /*FontName*/},
	},
}

// privateDict contains fields specific to the Private DICT context.
type privateDict struct {
	subrsOffset                  int32
	defaultWidthX, nominalWidthX float64
}

func (privateDict) () ps.Context { return ps.PrivateDict }

// The Private DICT operators are defined by 5176.CFF.pdf Table 23 "Private
// DICT Operators".
func ( *privateDict) ( *ps.Machine,  ps.Operator) error {
	if !.IsEscaped { // 1-byte operators.
		switch .Operator {
		case 6, 7, 8, 9: // "BlueValues" "OtherBlues" "FamilyBlues" "FamilyOtherBlues"
			return .ArgStack.PopN(-2)
		case 10, 11: // "StdHW" "StdVW"
			return .ArgStack.PopN(1)
		case 20: // "defaultWidthX"
			if .ArgStack.Top < 1 {
				return errors.New("invalid stack size for 'defaultWidthX' in private Dict charstring")
			}
			.defaultWidthX = .ArgStack.Vals[.ArgStack.Top-1]
			return .ArgStack.PopN(1)
		case 21: // "nominalWidthX"
			if .ArgStack.Top < 1 {
				return errors.New("invalid stack size for 'nominalWidthX' in private Dict charstring")
			}
			.nominalWidthX = .ArgStack.Vals[.ArgStack.Top-1]
			return .ArgStack.PopN(1)
		case 19: // "Subrs" pop 1
			if .ArgStack.Top < 1 {
				return errors.New("invalid stack size for 'subrs' in private Dict charstring")
			}
			.subrsOffset = int32(.ArgStack.Vals[.ArgStack.Top-1])
			return .ArgStack.PopN(1)
		}
	} else { // 2-byte operators. The first byte is the escape byte.
		switch .Operator {
		case 9, 10, 11, 14, 17, 18, 19: // "BlueScale" "BlueShift" "BlueFuzz" "ForceBold" "LanguageGroup" "ExpansionFactor" "initialRandomSeed"
			return .ArgStack.PopN(1)
		case 12, 13: //  "StemSnapH"  "StemSnapV"
			return .ArgStack.PopN(-2)
		}
	}
	return errors.New("invalid operand in private Dict charstring")
}