ws-arch2: wip type1 (charstring interpreter, PFB / PFA parsing) and codecs/font/GlyphNames (AGLFN + StandardEncoding)

This commit is contained in:
4DBug committed 2026-10-31 15:21:08 -05:00
1 parent b6b7999a63
commit e3c2ceaa5e
5 files changed
+836

No files matched your search

+284
View File
@@ -0,0 +1,284 @@
--!strict
-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted
-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side
-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div,
-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement;
-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes,
-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the
-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops).
local Charstring = {}
export type Result = { cmds: { any }, advance: number, sbx: number }
-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result
export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? }
local readu8 = buffer.readu8
function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
local cmds: { any } = {}
local stack: { number } = {}
local sp = 0
local ps: { number } = {} -- the PostScript stack callothersubr / pop use
local x, y = 0, 0
local advance, sbx = 0, 0
local open = false
local flex = false
local flexPts: { number } = {}
local budget = 200000
local finished = false
local function push(v: number)
if sp < 48 then
sp += 1
stack[sp] = v
end
end
local function arg(i: number): number
return stack[i] or 0
end
local function close()
if open then
table.insert(cmds, { op = "close" })
open = false
end
end
local function moveTo(dx: number, dy: number)
x += dx
y += dy
if flex then
table.insert(flexPts, x)
table.insert(flexPts, y)
return
end
close()
local c: any = { op = "moveTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
end
local function ensureOpen()
if not open then
-- a drawing operator without a moveto starts at the current point
local c: any = { op = "moveTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
open = true
end
end
local function lineTo(dx: number, dy: number)
local first = not open
ensureOpen()
local _ = first
x += dx
y += dy
local c: any = { op = "lineTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
end
local function curveTo(a: number, b: number, c: number, d: number, e: number, f: number)
ensureOpen()
local x1, y1 = x + a, y + b
local x2, y2 = x1 + c, y1 + d
x, y = x2 + e, y2 + f
local cmd: any = { op = "cubicTo" }
cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = x1, y1, x2, y2, x, y
table.insert(cmds, cmd)
end
local function exec(b: buffer, depth: number): string?
if depth > 10 then
return "subroutines nested too deep"
end
local n = buffer.len(b)
local p = 0
while p < n do
budget -= 1
if budget <= 0 then
return "operation budget exceeded"
end
local v = readu8(b, p)
p += 1
if v >= 32 then
if v <= 246 then
push(v - 139)
elseif v <= 250 then
if p >= n then
return "truncated number"
end
push((v - 247) * 256 + readu8(b, p) + 108)
p += 1
elseif v <= 254 then
if p >= n then
return "truncated number"
end
push(-(v - 251) * 256 - readu8(b, p) - 108)
p += 1
else
if p + 4 > n then
return "truncated number"
end
local u = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3)
push(if u >= 0x80000000 then u - 0x100000000 else u)
p += 4
end
continue
end
local op = v
if op == 12 then
if p >= n then
return "truncated escape"
end
op = 1200 + readu8(b, p)
p += 1
end
if op == 13 then -- hsbw
sbx, advance = arg(1), arg(2)
x, y = sbx, 0
sp = 0
elseif op == 1207 then -- sbw
sbx, advance = arg(1), arg(3)
x, y = arg(1), arg(2)
sp = 0
elseif op == 21 then
moveTo(arg(1), arg(2))
sp = 0
elseif op == 22 then
moveTo(arg(1), 0)
sp = 0
elseif op == 4 then
moveTo(0, arg(1))
sp = 0
elseif op == 5 then
lineTo(arg(1), arg(2))
sp = 0
elseif op == 6 then
lineTo(arg(1), 0)
sp = 0
elseif op == 7 then
lineTo(0, arg(1))
sp = 0
elseif op == 8 then
curveTo(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6))
sp = 0
elseif op == 30 then -- vhcurveto
curveTo(0, arg(1), arg(2), arg(3), arg(4), 0)
sp = 0
elseif op == 31 then -- hvcurveto
curveTo(arg(1), 0, arg(2), arg(3), 0, arg(4))
sp = 0
elseif op == 9 then
close()
sp = 0
elseif op == 10 then -- callsubr
local idx = arg(sp)
sp = math.max(0, sp - 1)
local sub = ctx.subrs[idx + 1]
if not sub then
return "call of a missing subroutine " .. idx
end
local err = exec(sub, depth + 1)
if err or finished then
return err
end
elseif op == 11 then -- return
return nil
elseif op == 14 then -- endchar
close()
finished = true
return nil
elseif op == 1212 then -- div
if sp >= 2 then
local d = stack[sp]
stack[sp - 1] = if d ~= 0 then stack[sp - 1] / d else 0
sp -= 1
end
elseif op == 1216 then -- callothersubr: args... n othersubr#
local num = arg(sp)
local count = arg(sp - 1)
sp = math.max(0, sp - 2)
count = math.clamp(count, 0, sp)
local args = {}
for i = 1, count do
args[i] = stack[sp - count + i]
end
sp -= count
if num == 1 then
flex = true
table.clear(flexPts)
elseif num == 2 then
-- a flex point: the rmoveto before it already recorded the point
elseif num == 0 and flex then
flex = false
-- flexPts: the reference point, then 6 control / end points
local f = flexPts
if #f >= 14 then
-- restore the current point to before the flex sequence's moves
local function curve(i: number)
ensureOpen()
local cmd: any = { op = "cubicTo" }
cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = f[i], f[i + 1], f[i + 2], f[i + 3], f[i + 4], f[i + 5]
table.insert(cmds, cmd)
end
curve(3)
curve(9)
x, y = f[13], f[14]
end
table.clear(ps)
table.insert(ps, args[3] or y)
table.insert(ps, args[2] or x)
elseif num == 3 then
table.clear(ps)
table.insert(ps, 3)
else
table.clear(ps)
for i = #args, 1, -1 do
table.insert(ps, args[i])
end
end
elseif op == 1217 then -- pop
push(table.remove(ps) or 0)
elseif op == 1233 then -- setcurrentpoint
x, y = arg(1), arg(2)
sp = 0
elseif op == 1206 then -- seac: asb adx ady bchar achar
local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5)
sp = 0
if not ctx.seac then
return "seac without base glyphs"
end
local base = ctx.seac(bchar)
local accent = ctx.seac(achar)
if not base or not accent then
return "seac of a missing glyph"
end
close()
for _, c in base.cmds do
table.insert(cmds, c)
end
local ox, oy = adx - asb, ady
for _, c in accent.cmds do
local t: any = { op = c.op }
for i = 1, #c, 2 do
t[i], t[i + 1] = c[i] + ox, c[i + 1] + oy
end
table.insert(cmds, t)
end
finished = true
return nil
elseif op == 1 or op == 3 or op == 1200 or op == 1201 or op == 1202 then
sp = 0 -- hints
else
sp = 0 -- unknown operators clear the stack
end
end
return nil
end
local err = exec(cs, 0)
if err then
return nil, err
end
close()
return { cmds = cmds, advance = advance, sbx = sbx }, nil
end
return Charstring
+365
View File
@@ -0,0 +1,365 @@
--!strict
-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the
-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox,
-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV,
-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring
-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph
-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through
-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple
-- Master and CID-keyed (Type 9 / 11) fonts, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Raster = require("@formats/codecs/image/Raster")
local GlyphNames = require("@formats/codecs/font/GlyphNames")
local Charstring = require("@formats/font/type1/Charstring")
-- ------------------------------------------------------------------------------------------------ contract
local Type1 = {
name = "type1",
category = "font",
extensions = { "pfb", "pfa", "t1" },
mime = { "application/x-font-type1" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" },
caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } },
}
export type DecodeOptions = { maxGlyphs: number? } -- default 65536
-- ------------------------------------------------------------------------------------------------ sniff
function Type1.sniff(r: Bytes.Reader): number
local h = r:peek(64)
if string.sub(h, 1, 2) == "\128\1" then
h = string.sub(h, 7)
end
if string.sub(h, 1, 14) == "%!PS-AdobeFont" or string.sub(h, 1, 10) == "%!FontType" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA
local function sections(r: Bytes.Reader): (string?, buffer?, string?)
local b = r.buf
local n = r:size()
if r:peek(2) == "\128\1" then
local clear, bin = {}, Bytes.writer()
local p = 0
while p + 2 <= n do
local h = r:sub(p, 6)
local m, ty, len = h:u8(), h:u8(), h:u32le()
if m ~= 128 then
return nil, nil, "bad PFB segment marker"
end
if ty == 3 then
break
end
if h.err or p + 6 + len > n then
return nil, nil, "truncated PFB segment"
end
if ty == 1 then
if #clear == 0 or bin:tell() == 0 then
table.insert(clear, buffer.readstring(b, r.base + p + 6, len))
end
elseif ty == 2 then
bin:bytes(r:sub(p + 6, len):bytes(len))
else
return nil, nil, "bad PFB segment type " .. ty
end
p += 6 + len
end
return table.concat(clear), bin:finish(), nil
end
local text = buffer.readstring(b, r.base, n)
local e = string.find(text, "eexec", 1, true)
if not e then
return nil, nil, "no eexec section"
end
local clear = string.sub(text, 1, e + 4)
-- PFA: hex digits after eexec, up to the zeros trailer (or binary if not hex)
local rest = string.sub(text, e + 5)
local hexPart = string.match(rest, "^%s*([%x%s]+)")
if hexPart and #hexPart > 8 then
local digits = string.gsub(hexPart, "%s", "")
local out = buffer.create(#digits // 2)
for i = 0, #digits // 2 - 1 do
buffer.writeu8(out, i, tonumber(string.sub(digits, i * 2 + 1, i * 2 + 2), 16) or 0)
end
return clear, out, nil
end
local s = string.match(rest, "^[\r\n]*(.*)$") or rest
return clear, buffer.fromstring(s), nil
end
local function decrypt(src: buffer, off: number, n: number, key: number, skip: number): buffer
local r = key
local out = buffer.create(math.max(0, n - skip))
for i = 0, n - 1 do
local c = buffer.readu8(src, off + i)
local p = bit32.bxor(c, bit32.rshift(r, 8))
r = ((c + r) * 52845 + 22719) % 65536
if i >= skip then
buffer.writeu8(out, i - skip, p)
end
end
return out
end
-- binary strings of the private dictionary: "<len> RD <bytes>" / "<len> -| <bytes>"
local function binaryAt(priv: buffer, p: number, len: number): buffer?
if p < 0 or len < 0 or p + len > buffer.len(priv) then
return nil
end
local out = buffer.create(len)
buffer.copy(out, 0, priv, p, len)
return out
end
local function psString(clear: string, key: string): string?
return string.match(clear, "/" .. key .. "%s*%((.-)%)%s*[rd]") or string.match(clear, "/" .. key .. "%s*%((.-)%)")
end
local Face = {}
Face.__index = Face
function Face.glyphIndex(self: any, cp: number): number
return self._cmap[cp] or 0
end
function Face.advance(self: any, g: number): number
local res = self:_run(g)
return if res then res.advance else 0
end
function Face.kern(_self: any, _a: number, _b: number): number
return 0
end
function Face._run(self: any, g: number): Charstring.Result?
local cached = self._cache[g]
if cached ~= nil then
return if cached == false then nil else cached
end
local cs = self._charstrings[g + 1]
if not cs then
return nil
end
local res = Charstring.run(cs, self._ctx)
self._cache[g] = res or false
return res
end
function Face.outline(self: any, g: number): { any }?
local res = self:_run(g)
if not res then
return nil
end
local out = table.create(#res.cmds)
for i, c in res.cmds do
out[i] = table.clone(c)
end
return out
end
function Face.rasterize(self: any, g: number, px: number): Types.Image?
if type(px) ~= "number" or not (px > 0) or px > 4096 then
return nil
end
local res = self:_run(g)
if not res then
return nil
end
local s = px / self.unitsPerEm
local m = Raster.mask(res.cmds, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 })
local img
if m then
img = Types.Image.new(m.width, m.height, "alpha8")
buffer.copy(img.pixels, 0, m.coverage)
img.meta.left, img.meta.top = m.x, -m.y
else
img = Types.Image.new(0, 0, "alpha8")
img.meta.left, img.meta.top = 0, 0
end
img.meta.advance = res.advance * s
img.meta.glyph = g
return img
end
function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 65536
local clear, enc, serr = sections(r)
if not clear or not enc then
return nil, Err.from(serr)
end
if not string.find(clear, "eexec", 1, true) and buffer.len(enc) == 0 then
return nil, Err.new(Err.CORRUPT, "no eexec section")
end
if buffer.len(enc) < 4 then
return nil, Err.new(Err.TRUNCATED, "eexec section too short")
end
local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4)
local ptext = buffer.tostring(priv)
local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4
-- Subrs
local subrs: { buffer } = {}
local function charstring(p: number, len: number): buffer?
local raw = binaryAt(priv, p, len)
if not raw then
return nil
end
if lenIV < 0 then
return raw
end
return decrypt(raw, 0, len, 4330, lenIV)
end
local sAt = string.find(ptext, "/Subrs", 1, true)
local csAt = string.find(ptext, "/CharStrings", 1, true)
if not csAt then
return nil, Err.new(Err.CORRUPT, "no CharStrings")
end
if sAt and sAt < csAt then
local p = sAt
while true do
local s, e, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p)
if not s or s > csAt then
break
end
local i, n = tonumber(idx) :: number, tonumber(len) :: number
if i > 65535 then
return nil, Err.new(Err.LIMIT, "too many subroutines")
end
local cs = charstring(e, n)
if not cs then
return nil, Err.new(Err.TRUNCATED, "subroutine " .. i .. " past the end")
end
subrs[i + 1] = cs
p = e + n
end
end
-- CharStrings
local names: { string } = {}
local charstrings: { buffer } = {}
local byName: { [string]: number } = {}
local p = csAt + 12
while true do
local s, e, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p)
if not s then
break
end
-- stop at the end of the dictionary
if string.find(string.sub(ptext, p, s), "%send%s") then
break
end
local n = tonumber(len) :: number
local cs = charstring(e, n)
if not cs then
return nil, Err.new(Err.TRUNCATED, "charstring " .. tostring(name) .. " past the end")
end
if #names >= maxGlyphs then
return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
end
table.insert(names, name :: string)
table.insert(charstrings, cs)
if byName[name :: string] == nil then
byName[name :: string] = #names - 1
end
p = e + n
end
if #names == 0 then
return nil, Err.new(Err.CORRUPT, "no glyphs")
end
-- .notdef first: glyph 0
local nd = byName[".notdef"]
if nd and nd ~= 0 then
names[1], names[nd + 1] = names[nd + 1], names[1]
charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1]
byName[names[1]], byName[names[nd + 1]] = 0, nd
end
-- the encoding
local encoding: { [number]: string } = {}
if string.find(clear, "/Encoding%s+StandardEncoding") then
for code, gname in GlyphNames.STANDARD do
encoding[code] = gname
end
else
for code, gname in string.gmatch(clear, "dup%s+(%d+)%s*/([^%s/]+)%s+put") do
encoding[tonumber(code) :: number] = gname
end
end
local cmap: { [number]: number } = {}
for _, gname in encoding do
local g = byName[gname]
local cp = GlyphNames.unicode(gname)
if g and cp and cmap[cp] == nil then
cmap[cp] = g
end
end
for k, gname in names do
local cp = GlyphNames.unicode(gname)
if cp and cmap[cp] == nil then
cmap[cp] = k - 1
end
end
-- font matrix / bbox
local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]")
local scale = 0.001
if fm then
local a = tonumber(string.match(fm, "^%s*(%S+)"))
if a and a > 0 then
scale = a
end
end
local bb = string.match(clear, "/FontBBox%s*[{%[]([^}%]]*)[}%]]")
local bbox = { 0, 0, 0, 0 }
if bb then
local k = 1
for v in string.gmatch(bb, "%S+") do
bbox[k] = tonumber(v) or 0
k += 1
end
end
local upm = math.floor(1 / scale + 0.5)
local font = setmetatable({
kind = "font",
info = {
family = psString(clear, "FamilyName") or string.match(clear, "/FontName%s*/(%S+)"),
style = psString(clear, "Weight") or "Regular",
fullName = psString(clear, "FullName"),
postscriptName = string.match(clear, "/FontName%s*/(%S+)"),
},
unitsPerEm = upm,
ascent = bbox[4],
descent = bbox[2],
lineGap = 0,
numGlyphs = #names,
meta = {
glyphNames = names,
encoding = encoding,
bbox = bbox,
italicAngle = tonumber(string.match(clear, "/ItalicAngle%s+(%-?[%d%.]+)") or "0"),
lenIV = lenIV,
source = { format = "type1", variant = if r:peek(2) == "\128\1" then "pfb" else "pfa" },
},
_cmap = cmap,
_charstrings = charstrings,
_cache = {},
}, Face)
font._ctx = {
subrs = subrs,
seac = function(code: number): Charstring.Result?
local gname = GlyphNames.STANDARD[code]
local g = if gname then byName[gname] else nil
if not g then
return nil
end
return Charstring.run(charstrings[g + 1], { subrs = subrs })
end,
}
return font, nil
end
return Type1