ws-arch: wip codecs/TrueType + codecs/Cff (glyf, cmap, kern, GPOS, names, OS/2; Type 2 charstrings)

This commit is contained in:
4DBug committed 2026-10-31 08:37:27 -05:00
1 parent a6a50ba1eb
commit 42d3559a48
5 files changed
+2110

No files matched your search

+657
View File
@@ -0,0 +1,657 @@
--!strict
-- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
-- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed
-- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands
-- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26
-- (public domain / MIT; Dougall Johnson's Type 2 support) through imgui-luau's imstb_truetype.lua, bounds-checked,
-- with fixes: flex1's last delta, an operation budget against subroutine bombs, and the arithmetic / storage
-- operators (TN #5177 4.4: and or not abs add sub div neg eq drop put get ifelse random mul sqrt dup exch index roll).
-- Not supported: CFF2 (variable fonts), seac accented glyphs in endchar (deprecated in OpenType), hinting.
--
-- local cff, err = Cff.parse(buf, offset, length)
-- local cmds, err = Cff.outline(cff, glyphIndex)
--
-- Never throws: malformed data returns nil, message.
local Cff = {}
local readu8 = buffer.readu8
local blen = buffer.len
local function u8(b: buffer, o: number): number
if o < 0 or o + 1 > blen(b) then
return 0
end
return readu8(b, o)
end
local function uN(b: buffer, o: number, n: number): number
local v = 0
for i = 0, n - 1 do
v = v * 256 + u8(b, o + i)
end
return v
end
export type Index = { count: number, offSize: number, offsets: number, data: number, next: number }
export type Font = {
buf: buffer,
base: number,
limit: number,
charStrings: Index,
gsubrs: Index,
subrs: Index?, -- name-keyed fonts
fdSubrs: { Index? }?, -- CID-keyed fonts: per font dict
fdSelect: number?, -- absolute offset of FDSelect
numGlyphs: number,
cid: boolean,
fontMatrix: { number }?,
}
-- INDEX at absolute offset p (within [base, limit)) -> Index | nil
local function index(b: buffer, p: number, limit: number): Index?
if p + 2 > limit then
return nil
end
local count = uN(b, p, 2)
if count == 0 then
return { count = 0, offSize = 1, offsets = p + 2, data = p + 2, next = p + 2 }
end
local offSize = u8(b, p + 2)
if offSize < 1 or offSize > 4 then
return nil
end
local offsets = p + 3
local data = offsets + (count + 1) * offSize - 1 -- offsets are 1-based
if data + 1 > limit then
return nil
end
local last = uN(b, offsets + count * offSize, offSize)
if data + last > limit then
return nil
end
return { count = count, offSize = offSize, offsets = offsets, data = data, next = data + last }
end
-- item(idx, i) -> absolute start, length (nil when out of range / corrupt)
local function item(b: buffer, idx: Index, i: number): (number?, number)
if i < 0 or i >= idx.count then
return nil, 0
end
local s = uN(b, idx.offsets + i * idx.offSize, idx.offSize)
local e = uN(b, idx.offsets + (i + 1) * idx.offSize, idx.offSize)
if s < 1 or e < s or idx.data + e > idx.next then
return nil, 0
end
return idx.data + s, e - s
end
Cff.item = item
-- DICT at [p, p + n) -> { [op] = { operands } } (two-byte ops are 1200 + second byte)
local function dict(b: buffer, p: number, n: number): { [number]: { number } }
local out: { [number]: { number } } = {}
local ops: { number } = {}
local e = p + n
while p < e do
local b0 = u8(b, p)
if b0 <= 21 then
local op = b0
p += 1
if b0 == 12 then
op = 1200 + u8(b, p)
p += 1
end
out[op] = ops
ops = {}
elseif b0 == 28 then
local v = uN(b, p + 1, 2)
table.insert(ops, if v >= 32768 then v - 65536 else v)
p += 3
elseif b0 == 29 then
local v = uN(b, p + 1, 4)
table.insert(ops, if v >= 2147483648 then v - 4294967296 else v)
p += 5
elseif b0 == 30 then -- real number: BCD nibbles
local s = {}
p += 1
local done = false
while p < e and not done do
local byte = u8(b, p)
p += 1
for _, nib in { byte // 16, byte % 16 } do
if nib <= 9 then
table.insert(s, tostring(nib))
elseif nib == 10 then
table.insert(s, ".")
elseif nib == 11 then
table.insert(s, "E")
elseif nib == 12 then
table.insert(s, "E-")
elseif nib == 14 then
table.insert(s, "-")
elseif nib == 15 then
done = true
break
end
end
end
table.insert(ops, tonumber(table.concat(s)) or 0)
elseif b0 >= 32 and b0 <= 246 then
table.insert(ops, b0 - 139)
p += 1
elseif b0 >= 247 and b0 <= 250 then
table.insert(ops, (b0 - 247) * 256 + u8(b, p + 1) + 108)
p += 2
elseif b0 >= 251 and b0 <= 254 then
table.insert(ops, -(b0 - 251) * 256 - u8(b, p + 1) - 108)
p += 2
else
p += 1 -- reserved
end
if #ops > 48 then
return out
end
end
return out
end
local function privateSubrs(b: buffer, base: number, limit: number, d: { [number]: { number } }): Index?
local pr = d[18]
if not pr or #pr < 2 then
return nil
end
local size, off = pr[1], pr[2]
local ps = base + off
if size < 0 or off < 0 or ps + size > limit then
return nil
end
local pd = dict(b, ps, size)
local s = pd[19]
if not s or #s < 1 then
return nil
end
return index(b, ps + s[1], limit)
end
-- parse(buf, offset, length) -> Font | nil, message
function Cff.parse(b: buffer, offset: number, length: number): (Font?, string?)
local base, limit = offset, math.min(offset + length, blen(b))
if limit - base < 4 then
return nil, "truncated CFF header"
end
local major, hdrSize = u8(b, base), u8(b, base + 2)
if major == 2 then
return nil, "unsupported: CFF2 (variable font outlines)"
end
if major ~= 1 then
return nil, "bad CFF version " .. major
end
local names = index(b, base + hdrSize, limit)
if not names then
return nil, "bad name INDEX"
end
local tops = index(b, names.next, limit)
if not tops or tops.count < 1 then
return nil, "bad Top DICT INDEX"
end
local strings = index(b, tops.next, limit)
if not strings then
return nil, "bad String INDEX"
end
local gsubrs = index(b, strings.next, limit)
if not gsubrs then
return nil, "bad global subrs INDEX"
end
local ts, tl = item(b, tops, 0)
if not ts then
return nil, "bad Top DICT"
end
local top = dict(b, ts, tl)
local cso = top[17]
if not cso or #cso < 1 then
return nil, "no CharStrings"
end
local cst = top[1206]
if cst and cst[1] ~= 2 then
return nil, "unsupported: charstring type " .. tostring(cst[1])
end
local charStrings = index(b, base + cso[1], limit)
if not charStrings then
return nil, "bad CharStrings INDEX"
end
local f: Font = {
buf = b,
base = base,
limit = limit,
charStrings = charStrings,
gsubrs = gsubrs,
subrs = nil,
fdSubrs = nil,
fdSelect = nil,
numGlyphs = charStrings.count,
cid = top[1230] ~= nil,
fontMatrix = top[1207],
}
if f.cid then
local fda, fds = top[1236], top[1237]
if not fda or not fds then
return nil, "CID font without FDArray / FDSelect"
end
local fdArray = index(b, base + fda[1], limit)
if not fdArray then
return nil, "bad FDArray"
end
local list: { Index? } = {}
for i = 0, math.min(fdArray.count, 256) - 1 do
local s, l = item(b, fdArray, i)
list[i + 1] = if s then privateSubrs(b, base, limit, dict(b, s, l)) else nil
end
f.fdSubrs = list
f.fdSelect = base + fds[1]
else
f.subrs = privateSubrs(b, base, limit, top)
end
return f, nil
end
local function bias(count: number): number
return if count < 1240 then 107 elseif count < 33900 then 1131 else 32768
end
-- the local subrs of glyph g (CID fonts: through FDSelect)
local function localSubrs(f: Font, g: number): Index?
if not f.cid then
return f.subrs
end
local b, p = f.buf, f.fdSelect :: number
local fmt = u8(b, p)
local fd = -1
if fmt == 0 then
fd = u8(b, p + 1 + g)
elseif fmt == 3 then
local n = uN(b, p + 1, 2)
local first = uN(b, p + 3, 2)
for i = 0, n - 1 do
local q = p + 5 + i * 3
local v = u8(b, q)
local nxt = uN(b, q + 1, 2)
if g >= first and g < nxt then
fd = v
break
end
first = nxt
end
end
local list = f.fdSubrs :: { Index? }
return list[fd + 1]
end
local BUDGET = 200000 -- operators per glyph (subroutine bombs)
-- outline(f, g) -> path commands | nil, message
function Cff.outline(f: Font, g: number): ({ any }?, string?)
local b = f.buf
local p, len = item(b, f.charStrings, g)
if not p then
return nil, "bad glyph index " .. tostring(g)
end
local e = p + len
local cmds: { any } = {}
local s: { number } = table.create(48, 0) -- operand stack, 1-based; sp = count
local sp = 0
local trans: { number } = table.create(32, 0)
local x, y = 0, 0
local open = false
local maskbits = 0
local inHeader = true
local stack: { { number } } = {} -- return addresses { p, e }
local subrs: Index? = nil
local haveSubrs = false
local ops = 0
local seed = 12345
local function moveTo(dx: number, dy: number)
if open then
table.insert(cmds, { op = "close" })
end
x += dx
y += dy
table.insert(cmds, { op = "moveTo", x, y })
open = true
end
local function lineTo(dx: number, dy: number)
if not open then
moveTo(0, 0)
end
x += dx
y += dy
table.insert(cmds, { op = "lineTo", x, y })
end
local function curveTo(dx1: number, dy1: number, dx2: number, dy2: number, dx3: number, dy3: number)
if not open then
moveTo(0, 0)
end
local x1, y1 = x + dx1, y + dy1
local x2, y2 = x1 + dx2, y1 + dy2
x, y = x2 + dx3, y2 + dy3
table.insert(cmds, { op = "cubicTo", x1, y1, x2, y2, x, y })
end
local function S(i: number): number -- operand i (0-based), 0 past the stack
return s[i + 1] or 0
end
while true do
if p >= e then
-- the end of a subroutine without return, or of the charstring without endchar
if #stack > 0 then
local r = table.remove(stack) :: { number }
p, e = r[1], r[2]
continue
end
break
end
ops += 1
if ops > BUDGET then
return nil, "charstring too long (subroutine loop?)"
end
local b0 = u8(b, p)
p += 1
local clear = true
local i = 0
if b0 == 19 or b0 == 20 then -- hintmask, cntrmask
if inHeader then
maskbits += sp // 2
end
inHeader = false
p += (maskbits + 7) // 8
elseif b0 == 1 or b0 == 3 or b0 == 18 or b0 == 23 then -- hstem vstem hstemhm vstemhm
maskbits += sp // 2
elseif b0 == 21 then -- rmoveto
inHeader = false
if sp < 2 then
return nil, "rmoveto stack"
end
moveTo(S(sp - 2), S(sp - 1))
elseif b0 == 4 then -- vmoveto
inHeader = false
if sp < 1 then
return nil, "vmoveto stack"
end
moveTo(0, S(sp - 1))
elseif b0 == 22 then -- hmoveto
inHeader = false
if sp < 1 then
return nil, "hmoveto stack"
end
moveTo(S(sp - 1), 0)
elseif b0 == 5 then -- rlineto
if sp < 2 then
return nil, "rlineto stack"
end
while i + 1 < sp do
lineTo(S(i), S(i + 1))
i += 2
end
elseif b0 == 6 or b0 == 7 then -- hlineto / vlineto: alternate
if sp < 1 then
return nil, "hlineto stack"
end
local horiz = b0 == 6
while i < sp do
if horiz then
lineTo(S(i), 0)
else
lineTo(0, S(i))
end
horiz = not horiz
i += 1
end
elseif b0 == 31 or b0 == 30 then -- hvcurveto / vhcurveto: alternate
if sp < 4 then
return nil, "hvcurveto stack"
end
local horiz = b0 == 31
while i + 3 < sp do
local last = if sp - i == 5 then S(i + 4) else 0
if horiz then
curveTo(S(i), 0, S(i + 1), S(i + 2), last, S(i + 3))
else
curveTo(0, S(i), S(i + 1), S(i + 2), S(i + 3), last)
end
horiz = not horiz
i += 4
end
elseif b0 == 8 then -- rrcurveto
if sp < 6 then
return nil, "rrcurveto stack"
end
while i + 5 < sp do
curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5))
i += 6
end
elseif b0 == 24 then -- rcurveline
if sp < 8 then
return nil, "rcurveline stack"
end
while i + 5 < sp - 2 do
curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5))
i += 6
end
lineTo(S(i), S(i + 1))
elseif b0 == 25 then -- rlinecurve
if sp < 8 then
return nil, "rlinecurve stack"
end
while i + 1 < sp - 6 do
lineTo(S(i), S(i + 1))
i += 2
end
curveTo(S(i), S(i + 1), S(i + 2), S(i + 3), S(i + 4), S(i + 5))
elseif b0 == 26 or b0 == 27 then -- vvcurveto / hhcurveto
if sp < 4 then
return nil, "vv/hhcurveto stack"
end
local f0 = 0
if sp % 2 == 1 then
f0 = S(0)
i = 1
end
while i + 3 < sp do
if b0 == 27 then
curveTo(S(i), f0, S(i + 1), S(i + 2), S(i + 3), 0)
else
curveTo(f0, S(i), S(i + 1), S(i + 2), 0, S(i + 3))
end
f0 = 0
i += 4
end
elseif b0 == 10 or b0 == 29 then -- callsubr / callgsubr
if b0 == 10 and not haveSubrs then
subrs = localSubrs(f, g)
haveSubrs = true
end
if sp < 1 then
return nil, "callsubr stack"
end
local idx = if b0 == 10 then subrs else f.gsubrs
if not idx then
return nil, "no subroutines"
end
local n = math.floor(S(sp - 1)) + bias(idx.count)
sp -= 1
if #stack >= 10 then
return nil, "subroutine recursion limit"
end
local sp0, sl = item(b, idx, n)
if not sp0 then
return nil, "subroutine " .. n .. " not found"
end
table.insert(stack, { p, e })
p, e = sp0, sp0 + sl
clear = false
elseif b0 == 11 then -- return
if #stack == 0 then
return nil, "return outside a subroutine"
end
local r = table.remove(stack) :: { number }
p, e = r[1], r[2]
clear = false
elseif b0 == 14 then -- endchar
if open then
table.insert(cmds, { op = "close" })
end
return cmds, nil
elseif b0 == 12 then -- escape
local b1 = u8(b, p)
p += 1
if b1 == 34 then -- hflex
if sp < 7 then
return nil, "hflex stack"
end
curveTo(S(0), 0, S(1), S(2), S(3), 0)
curveTo(S(4), 0, S(5), -S(2), S(6), 0)
elseif b1 == 35 then -- flex
if sp < 13 then
return nil, "flex stack"
end
curveTo(S(0), S(1), S(2), S(3), S(4), S(5))
curveTo(S(6), S(7), S(8), S(9), S(10), S(11))
elseif b1 == 36 then -- hflex1
if sp < 9 then
return nil, "hflex1 stack"
end
curveTo(S(0), S(1), S(2), S(3), S(4), 0)
curveTo(S(5), 0, S(6), S(7), S(8), -(S(1) + S(3) + S(7)))
elseif b1 == 37 then -- flex1
if sp < 11 then
return nil, "flex1 stack"
end
local dx = S(0) + S(2) + S(4) + S(6) + S(8)
local dy = S(1) + S(3) + S(5) + S(7) + S(9)
local dx6, dy6 = S(10), S(10)
if math.abs(dx) > math.abs(dy) then
dy6 = -dy
else
dx6 = -dx
end
curveTo(S(0), S(1), S(2), S(3), S(4), S(5))
curveTo(S(6), S(7), S(8), S(9), dx6, dy6)
else
-- arithmetic and storage operators: they leave results on the stack
clear = false
local top = sp
local a, c = S(top - 2), S(top - 1)
local function set(n: number, v: number)
-- pop n operands, push v
sp = math.max(0, sp - n)
sp += 1
s[sp] = v
end
if b1 == 3 then
set(2, if a ~= 0 and c ~= 0 then 1 else 0) -- and
elseif b1 == 4 then
set(2, if a ~= 0 or c ~= 0 then 1 else 0) -- or
elseif b1 == 5 then
set(1, if c == 0 then 1 else 0) -- not
elseif b1 == 9 then
set(1, math.abs(c))
elseif b1 == 10 then
set(2, a + c)
elseif b1 == 11 then
set(2, a - c)
elseif b1 == 12 then
set(2, if c ~= 0 then a / c else 0)
elseif b1 == 14 then
set(1, -c)
elseif b1 == 15 then
set(2, if a == c then 1 else 0)
elseif b1 == 18 then
sp = math.max(0, sp - 1) -- drop
elseif b1 == 20 then -- put: val i
local k = math.floor(c)
if k >= 0 and k < 32 then
trans[k + 1] = a
end
sp = math.max(0, sp - 2)
elseif b1 == 21 then -- get
local k = math.floor(c)
set(1, if k >= 0 and k < 32 then trans[k + 1] else 0)
elseif b1 == 22 then -- ifelse: s1 s2 v1 v2 -> v1 <= v2 ? s1 : s2
local s1, s2, v1, v2 = S(top - 4), S(top - 3), S(top - 2), S(top - 1)
set(4, if v1 <= v2 then s1 else s2)
elseif b1 == 23 then -- random (deterministic)
seed = (seed * 1103515245 + 12345) % 2147483648
set(0, (seed % 65535 + 1) / 65536)
elseif b1 == 24 then
set(2, a * c)
elseif b1 == 26 then
set(1, math.sqrt(math.max(0, c)))
elseif b1 == 27 then
set(0, c) -- dup
elseif b1 == 28 then -- exch
if sp >= 2 then
s[sp - 1], s[sp] = s[sp], s[sp - 1]
end
elseif b1 == 29 then -- index
local k = math.floor(c)
local v = if k < 0 then S(top - 2) else S(top - 2 - k)
set(1, v)
elseif b1 == 30 then -- roll: n j
local n, j = math.floor(a), math.floor(c)
sp = math.max(0, sp - 2)
if n > 0 and n <= sp then
local base = sp - n
local tmp = table.create(n, 0)
for k = 0, n - 1 do
tmp[((k + j) % n) + 1] = s[base + k + 1]
end
for k = 0, n - 1 do
s[base + k + 1] = tmp[k + 1]
end
end
else
return nil, "unknown operator 12 " .. b1
end
if sp > 48 then
return nil, "stack overflow"
end
end
elseif b0 >= 32 or b0 == 28 then -- operands
local v
if b0 == 28 then
v = uN(b, p, 2)
if v >= 32768 then
v -= 65536
end
p += 2
elseif b0 <= 246 then
v = b0 - 139
elseif b0 <= 250 then
v = (b0 - 247) * 256 + u8(b, p) + 108
p += 1
elseif b0 <= 254 then
v = -(b0 - 251) * 256 - u8(b, p) - 108
p += 1
else -- 255: 16.16 fixed
v = uN(b, p, 4)
if v >= 2147483648 then
v -= 4294967296
end
v /= 65536
p += 4
end
if sp >= 48 then
return nil, "operand stack overflow"
end
sp += 1
s[sp] = v
clear = false
else
return nil, "reserved operator " .. b0
end
if clear then
sp = 0
end
end
return nil, "no endchar"
end
return Cff
+403
View File
@@ -0,0 +1,403 @@
--!strict
-- codecs/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and
-- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale /
-- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26
-- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point
-- matching and the FreeType component transform (stb scales the offsets of transformed components; FreeType and the
-- spec do not). No hinting.
--
-- Never throws: every read is range-checked (out of range reads as 0) and malformed glyphs return nil, message.
local Glyf = {}
local readu8, readi8 = buffer.readu8, buffer.readi8
local blen = buffer.len
local band = bit32.band
local function u8(b: buffer, o: number): number
if o < 0 or o + 1 > blen(b) then
return 0
end
return readu8(b, o)
end
local function u16(b: buffer, o: number): number
if o < 0 or o + 2 > blen(b) then
return 0
end
return readu8(b, o) * 256 + readu8(b, o + 1)
end
local function i16(b: buffer, o: number): number
local v = u16(b, o)
return if v >= 32768 then v - 65536 else v
end
local function u32(b: buffer, o: number): number
return u16(b, o) * 65536 + u16(b, o + 2)
end
export type Face = {
buf: buffer,
glyf: number, -- absolute offset of the glyf table
glyfLen: number,
loca: number,
locaLen: number,
longLoca: boolean,
numGlyphs: number,
[string]: any,
}
-- (start, length) of glyph g in the glyf table, or nil for an empty glyph / bad index
function Glyf.range(f: Face, g: number): (number?, number)
if g < 0 or g >= f.numGlyphs or g % 1 ~= 0 then
return nil, 0
end
local a, z
if f.longLoca then
if (g + 2) * 4 > f.locaLen then
return nil, 0
end
a, z = u32(f.buf, f.loca + g * 4), u32(f.buf, f.loca + g * 4 + 4)
else
if (g + 2) * 2 > f.locaLen then
return nil, 0
end
a, z = u16(f.buf, f.loca + g * 2) * 2, u16(f.buf, f.loca + g * 2 + 2) * 2
end
if z <= a or z > f.glyfLen then
return nil, 0
end
return f.glyf + a, z - a
end
-- bounds(f, g) -> xMin, yMin, xMax, yMax from the glyph header (nil for empty glyphs)
function Glyf.bounds(f: Face, g: number): (number?, number, number, number)
local o, n = Glyf.range(f, g)
if not o or n < 10 then
return nil, 0, 0, 0
end
local b = f.buf
return i16(b, o + 2), i16(b, o + 4), i16(b, o + 6), i16(b, o + 8)
end
-- contours: { { xs, ys, on } } point lists in font units
type Contour = { x: { number }, y: { number }, on: { boolean } }
local MAX_POINTS = 65536
local function simple(b: buffer, o: number, len: number, nc: number): ({ Contour }?, string?)
local e = o + len
local ends = table.create(nc)
local p = o + 10
if p + nc * 2 + 2 > e then
return nil, "glyph header past the end"
end
local last = -1
for i = 1, nc do
local v = u16(b, p)
if v < last then
return nil, "contour end points out of order"
end
ends[i] = v
last = v
p += 2
end
local n = last + 1
if n > MAX_POINTS then
return nil, "too many points"
end
local ins = u16(b, p)
p += 2 + ins
if p > e then
return nil, "instructions past the end"
end
-- flags
local flags = table.create(n, 0)
local i = 1
while i <= n do
if p >= e then
return nil, "flags past the end"
end
local fl = readu8(b, p)
p += 1
flags[i] = fl
i += 1
if band(fl, 8) ~= 0 then
if p >= e then
return nil, "flags past the end"
end
local rep = readu8(b, p)
p += 1
for _ = 1, rep do
if i > n then
break
end
flags[i] = fl
i += 1
end
end
end
-- coordinates
local xs = table.create(n, 0)
local x = 0
for k = 1, n do
local fl = flags[k]
if band(fl, 2) ~= 0 then
if p >= e then
return nil, "x coordinates past the end"
end
local d = readu8(b, p)
p += 1
x += if band(fl, 16) ~= 0 then d else -d
elseif band(fl, 16) == 0 then
if p + 2 > e then
return nil, "x coordinates past the end"
end
x += i16(b, p)
p += 2
end
xs[k] = x
end
local ys = table.create(n, 0)
local y = 0
for k = 1, n do
local fl = flags[k]
if band(fl, 4) ~= 0 then
if p >= e then
return nil, "y coordinates past the end"
end
local d = readu8(b, p)
p += 1
y += if band(fl, 32) ~= 0 then d else -d
elseif band(fl, 32) == 0 then
if p + 2 > e then
return nil, "y coordinates past the end"
end
y += i16(b, p)
p += 2
end
ys[k] = y
end
local out: { Contour } = table.create(nc)
local s = 1
for c = 1, nc do
local z = ends[c] + 1
local cx, cy, con = {}, {}, {}
for k = s, z do
table.insert(cx, xs[k])
table.insert(cy, ys[k])
table.insert(con, band(flags[k], 1) ~= 0)
end
out[c] = { x = cx, y = cy, on = con }
s = z + 1
end
return out, nil
end
local contours: (f: Face, g: number, depth: number) -> ({ Contour }?, string?)
local function composite(f: Face, o: number, len: number, depth: number): ({ Contour }?, string?)
local b = f.buf
local e = o + len
local p = o + 10
local out: { Contour } = {}
local total = 0
while true do
if p + 4 > e then
return nil, "component past the end"
end
local flags = u16(b, p)
local gi = u16(b, p + 2)
p += 4
local a1, a2
if band(flags, 1) ~= 0 then -- ARG_1_AND_2_ARE_WORDS
if p + 4 > e then
return nil, "component past the end"
end
if band(flags, 2) ~= 0 then
a1, a2 = i16(b, p), i16(b, p + 2)
else
a1, a2 = u16(b, p), u16(b, p + 2)
end
p += 4
else
if p + 2 > e then
return nil, "component past the end"
end
if band(flags, 2) ~= 0 then
a1, a2 = readi8(b, p), readi8(b, p + 1)
else
a1, a2 = readu8(b, p), readu8(b, p + 1)
end
p += 2
end
local m1, m2, m3, m4 = 1, 0, 0, 1
if band(flags, 8) ~= 0 then -- WE_HAVE_A_SCALE
m1 = i16(b, p) / 16384
m4 = m1
p += 2
elseif band(flags, 0x40) ~= 0 then -- WE_HAVE_AN_X_AND_Y_SCALE
m1, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384
p += 4
elseif band(flags, 0x80) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO
m1, m2, m3, m4 = i16(b, p) / 16384, i16(b, p + 2) / 16384, i16(b, p + 4) / 16384, i16(b, p + 6) / 16384
p += 8
end
if p > e then
return nil, "component past the end"
end
local child, err = contours(f, gi, depth + 1)
if not child then
return nil, err
end
-- transform the child's points
local tc: { Contour } = table.create(#child)
for i, c in child do
local nx, ny = table.create(#c.x), table.create(#c.x)
for k = 1, #c.x do
local x, y = c.x[k], c.y[k]
nx[k] = m1 * x + m3 * y
ny[k] = m2 * x + m4 * y
end
tc[i] = { x = nx, y = ny, on = c.on }
end
local dx, dy
if band(flags, 2) ~= 0 then -- ARGS_ARE_XY_VALUES
dx, dy = a1, a2
if band(flags, 0x800) ~= 0 and band(flags, 0x1000) == 0 then -- SCALED_COMPONENT_OFFSET
dx, dy = m1 * a1 + m3 * a2, m2 * a1 + m4 * a2
end
else
-- point matching: parent point a1 (in what is composed so far) meets child point a2
local function pt(list: { Contour }, idx: number): (number?, number)
local k = idx
for _, c in list do
local n = #c.x
if k < n then
return c.x[k + 1], c.y[k + 1]
end
k -= n
end
return nil, 0
end
local px, py = pt(out, a1)
local cx, cy = pt(tc, a2)
if not px or not cx then
return nil, "component point index out of range"
end
dx, dy = px - cx, py - (cy :: number)
end
for _, c in tc do
for k = 1, #c.x do
c.x[k] += dx
c.y[k] += dy
end
total += #c.x
table.insert(out, c)
end
if total > MAX_POINTS then
return nil, "too many points"
end
if band(flags, 0x20) == 0 then -- MORE_COMPONENTS
break
end
end
return out, nil
end
contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?)
if depth > 8 then
return nil, "composite glyphs nested too deep"
end
local o, len = Glyf.range(f, g)
if not o then
return {}, nil -- empty glyph (space)
end
if len < 10 then
return nil, "glyph header past the end"
end
local nc = i16(f.buf, o)
if nc >= 0 then
return simple(f.buf, o, len, nc)
end
return composite(f, o, len, depth)
end
-- outline(f, g) -> path commands (codecs/Raster format, font units, y up) | nil, message
function Glyf.outline(f: Face, g: number): ({ any }?, string?)
local cs, err = contours(f, g, 0)
if not cs then
return nil, err
end
local cmds = {}
for _, c in cs do
local n = #c.x
if n < 2 then
continue
end
local xs, ys, on = c.x, c.y, c.on
-- the start: the first on-curve point, or the midpoint of the first two off-curve points
local s = 0
for k = 1, n do
if on[k] then
s = k
break
end
end
local sx, sy
if s == 0 then
sx, sy = (xs[1] + xs[n]) / 2, (ys[1] + ys[n]) / 2
s = 1
-- all off-curve: start at the implied midpoint between the last and the first, then walk from 1
table.insert(cmds, { op = "moveTo", sx, sy })
local cx, cy = xs[1], ys[1]
for k = 2, n do
local x, y = xs[k], ys[k]
table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 })
cx, cy = x, y
end
table.insert(cmds, { op = "quadTo", cx, cy, sx, sy })
table.insert(cmds, { op = "close" })
continue
end
sx, sy = xs[s], ys[s]
table.insert(cmds, { op = "moveTo", sx, sy })
local off = false
local cx, cy = 0, 0
for i = 1, n do
local k = (s + i - 1) % n + 1
local x, y, isOn = xs[k], ys[k], on[k]
if i == n then
x, y, isOn = sx, sy, true -- back to the start
end
if isOn then
if off then
table.insert(cmds, { op = "quadTo", cx, cy, x, y })
elseif i < n then
table.insert(cmds, { op = "lineTo", x, y })
end
off = false
else
if off then
table.insert(cmds, { op = "quadTo", cx, cy, (cx + x) / 2, (cy + y) / 2 })
end
cx, cy = x, y
off = true
end
end
table.insert(cmds, { op = "close" })
end
return cmds, nil
end
-- points(f, g) -> the number of points and contours (for tests)
function Glyf.counts(f: Face, g: number): (number, number)
local cs = contours(f, g, 0)
if not cs then
return 0, 0
end
local n = 0
for _, c in cs do
n += #c.x
end
return n, #cs
end
return Glyf
+535
View File
@@ -0,0 +1,535 @@
--!strict
-- codecs/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode
-- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair
-- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9),
-- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public
-- domain / MIT) as a reference for cmap 4 and the GPOS walk.
--
-- Never throws: every read is range-checked (out of range reads as 0).
local Tables = {}
local readu8 = buffer.readu8
local blen = buffer.len
local band = bit32.band
local function u8(b: buffer, o: number): number
if o < 0 or o + 1 > blen(b) then
return 0
end
return readu8(b, o)
end
local function u16(b: buffer, o: number): number
if o < 0 or o + 2 > blen(b) then
return 0
end
return readu8(b, o) * 256 + readu8(b, o + 1)
end
local function i16(b: buffer, o: number): number
local v = u16(b, o)
return if v >= 32768 then v - 65536 else v
end
local function u32(b: buffer, o: number): number
return u16(b, o) * 65536 + u16(b, o + 2)
end
Tables.u8, Tables.u16, Tables.i16, Tables.u32 = u8, u16, i16, u32
-- ------------------------------------------------------------------------------------------------ cmap
export type Cmap = { buf: buffer, at: number, format: number, symbol: boolean }
-- pick the best subtable of the cmap table at [o, o + n): Unicode full repertoire, then BMP, then symbol, then Mac
function Tables.cmap(b: buffer, o: number, n: number): Cmap?
local count = u16(b, o + 2)
local best, bestRank, symbol = -1, 0, false
for i = 0, count - 1 do
local r = o + 4 + i * 8
if r + 8 > o + n then
break
end
local pid, eid, off = u16(b, r), u16(b, r + 2), u32(b, r + 4)
local at = o + off
if off >= n then
continue
end
local fmt = u16(b, at)
local rank = 0
if pid == 3 and eid == 10 then
rank = 6
elseif pid == 0 and (eid == 4 or eid == 6) then
rank = 5
elseif pid == 3 and eid == 1 then
rank = 4
elseif pid == 0 and fmt ~= 14 then
rank = 3
elseif pid == 3 and eid == 0 then
rank = 2
elseif pid == 1 and eid == 0 then
rank = 1
end
if fmt ~= 0 and fmt ~= 4 and fmt ~= 6 and fmt ~= 10 and fmt ~= 12 and fmt ~= 13 then
rank = 0
end
if rank > bestRank then
best, bestRank, symbol = at, rank, pid == 3 and eid == 0
end
end
if best < 0 then
return nil
end
return { buf = b, at = best, format = u16(b, best), symbol = symbol }
end
local function lookup(c: Cmap, cp: number): number
local b, t, fmt = c.buf, c.at, c.format
if fmt == 0 then
return if cp < 256 then u8(b, t + 6 + cp) else 0
elseif fmt == 6 then
local first, count = u16(b, t + 6), u16(b, t + 8)
if cp >= first and cp < first + count then
return u16(b, t + 10 + (cp - first) * 2)
end
return 0
elseif fmt == 10 then
local first, count = u32(b, t + 12), u32(b, t + 16)
if cp >= first and cp < first + count then
return u16(b, t + 20 + (cp - first) * 2)
end
return 0
elseif fmt == 4 then
if cp > 0xFFFF then
return 0
end
local segX2 = u16(b, t + 6)
local segs = segX2 // 2
local ends = t + 14
-- binary search for the first segment whose end >= cp
local lo, hi = 0, segs - 1
while lo < hi do
local mid = (lo + hi) // 2
if u16(b, ends + mid * 2) < cp then
lo = mid + 1
else
hi = mid
end
end
if segs == 0 or u16(b, ends + lo * 2) < cp then
return 0
end
local starts = ends + segX2 + 2
local start = u16(b, starts + lo * 2)
if cp < start then
return 0
end
local deltaAt = starts + segX2 + lo * 2
local delta = u16(b, deltaAt)
local rangeAt = deltaAt + segX2
local ro = u16(b, rangeAt)
if ro == 0 then
return (cp + delta) % 65536
end
local g = u16(b, rangeAt + ro + (cp - start) * 2)
if g == 0 then
return 0
end
return (g + delta) % 65536
elseif fmt == 12 or fmt == 13 then
local n = u32(b, t + 12)
local lo, hi = 0, n - 1
while lo <= hi do
local mid = (lo + hi) // 2
local g = t + 16 + mid * 12
local s, e = u32(b, g), u32(b, g + 4)
if cp < s then
hi = mid - 1
elseif cp > e then
lo = mid + 1
else
local gid = u32(b, g + 8)
return if fmt == 12 then gid + cp - s else gid
end
end
return 0
end
return 0
end
-- glyph(cmap, codepoint) -> glyph index (0 = .notdef)
function Tables.glyph(c: Cmap?, cp: number): number
if not c or type(cp) ~= "number" or cp < 0 or cp > 0x10FFFF or cp % 1 ~= 0 then
return 0
end
local g = lookup(c, cp)
if g == 0 and c.symbol and cp < 256 then
g = lookup(c, 0xF000 + cp) -- symbol fonts map U+F020.. to the 8-bit codes
end
return g
end
-- ------------------------------------------------------------------------------------------------ kern
-- the 'kern' table's horizontal format 0 pairs -> { [left * 65536 + right] = value }
function Tables.kern(b: buffer, o: number, n: number): { [number]: number }
local pairs: { [number]: number } = {}
local e = o + n
local apple = u32(b, o) == 0x00010000
local count = if apple then u32(b, o + 4) else u16(b, o + 2)
local p = if apple then o + 8 else o + 4
for _ = 1, math.min(count, 64) do
if p + 6 > e then
break
end
local len, fmt, horizontal, cross, minimum, hdr
if apple then
len = u32(b, p)
local cov = u16(b, p + 4)
fmt = band(cov, 0xFF)
horizontal = band(cov, 0x8000) == 0
cross = band(cov, 0x4000) ~= 0
minimum = band(cov, 0x2000) ~= 0 -- (variation) treated as not applicable
hdr = 8
else
len = u16(b, p + 2)
local cov = u16(b, p + 4)
fmt = cov // 256
horizontal = band(cov, 1) ~= 0
minimum = band(cov, 2) ~= 0
cross = band(cov, 4) ~= 0
hdr = 6
end
if fmt == 0 and horizontal and not cross and not minimum then
local np = u16(b, p + hdr)
local q = p + hdr + 8
for k = 0, np - 1 do
local r = q + k * 6
if r + 6 > e then
break
end
local key = u16(b, r) * 65536 + u16(b, r + 2)
pairs[key] = (pairs[key] or 0) + i16(b, r + 4)
end
end
if len < hdr then
break
end
-- Microsoft subtables often have a wrong 16-bit length for big tables: only the first is reliable then
if not apple and len < hdr + 8 then
break
end
p += len
end
return pairs
end
-- ------------------------------------------------------------------------------------------------ GPOS
local function popcount(v: number): number
local c = 0
while v ~= 0 do
c += band(v, 1)
v = bit32.rshift(v, 1)
end
return c
end
-- coverage index of glyph g in the Coverage table at t, or -1
local function coverage(b: buffer, t: number, g: number): number
local fmt = u16(b, t)
if fmt == 1 then
local n = u16(b, t + 2)
local lo, hi = 0, n - 1
while lo <= hi do
local mid = (lo + hi) // 2
local v = u16(b, t + 4 + mid * 2)
if g < v then
hi = mid - 1
elseif g > v then
lo = mid + 1
else
return mid
end
end
elseif fmt == 2 then
local n = u16(b, t + 2)
local lo, hi = 0, n - 1
while lo <= hi do
local mid = (lo + hi) // 2
local r = t + 4 + mid * 6
local s, e = u16(b, r), u16(b, r + 2)
if g < s then
hi = mid - 1
elseif g > e then
lo = mid + 1
else
return u16(b, r + 4) + g - s
end
end
end
return -1
end
local function classOf(b: buffer, t: number, g: number): number
local fmt = u16(b, t)
if fmt == 1 then
local s, n = u16(b, t + 2), u16(b, t + 4)
if g >= s and g < s + n then
return u16(b, t + 6 + (g - s) * 2)
end
elseif fmt == 2 then
local n = u16(b, t + 2)
local lo, hi = 0, n - 1
while lo <= hi do
local mid = (lo + hi) // 2
local r = t + 4 + mid * 6
local s, e = u16(b, r), u16(b, r + 2)
if g < s then
hi = mid - 1
elseif g > e then
lo = mid + 1
else
return u16(b, r + 4)
end
end
end
return 0
end
-- the x advance adjustment in a value record with format vf at r
local function xAdvance(b: buffer, r: number, vf: number): number
if band(vf, 4) == 0 then
return 0
end
return i16(b, r + 2 * popcount(band(vf, 3)))
end
-- one PairPos subtable: (applies, value)
local function pairPos(b: buffer, t: number, l: number, r: number): (boolean, number)
local fmt = u16(b, t)
local ci = coverage(b, t + u16(b, t + 2), l)
if ci < 0 then
return false, 0
end
local vf1, vf2 = u16(b, t + 4), u16(b, t + 6)
local s1, s2 = 2 * popcount(band(vf1, 0xFF)), 2 * popcount(band(vf2, 0xFF))
if fmt == 1 then
local count = u16(b, t + 8)
if ci >= count then
return false, 0
end
local ps = t + u16(b, t + 10 + ci * 2)
local n = u16(b, ps)
local rec = 2 + s1 + s2
local lo, hi = 0, n - 1
while lo <= hi do
local mid = (lo + hi) // 2
local q = ps + 2 + mid * rec
local g = u16(b, q)
if r < g then
hi = mid - 1
elseif r > g then
lo = mid + 1
else
return true, xAdvance(b, q + 2, vf1)
end
end
return false, 0
elseif fmt == 2 then
local cd1, cd2 = t + u16(b, t + 8), t + u16(b, t + 10)
local n1, n2 = u16(b, t + 12), u16(b, t + 14)
local c1, c2 = classOf(b, cd1, l), classOf(b, cd2, r)
if c1 >= n1 or c2 >= n2 then
return false, 0
end
local q = t + 16 + (c1 * n2 + c2) * (s1 + s2)
return true, xAdvance(b, q, vf1)
end
return false, 0
end
export type Gpos = { buf: buffer, subtables: { { number } } } -- per lookup: PairPos subtable offsets
-- the pair-adjustment lookups of the 'kern' feature (any script / language) of the GPOS table at [o, o + n)
function Tables.gpos(b: buffer, o: number, n: number): Gpos?
if n < 10 or u16(b, o) ~= 1 then
return nil
end
local fl, ll = o + u16(b, o + 6), o + u16(b, o + 8)
local want: { [number]: boolean } = {}
local any = false
local nf = u16(b, fl)
for i = 0, nf - 1 do
local r = fl + 2 + i * 6
if u32(b, r) == 0x6B65726E then -- "kern"
local f = fl + u16(b, r + 4)
for k = 0, u16(b, f + 2) - 1 do
want[u16(b, f + 4 + k * 2)] = true
any = true
end
end
end
if not any then
return nil
end
local lookups: { { number } } = {}
local nl = u16(b, ll)
for i = 0, nl - 1 do
if want[i] then
local lt = ll + u16(b, ll + 2 + i * 2)
local ty = u16(b, lt)
local subs: { number } = {}
for k = 0, math.min(u16(b, lt + 4), 4096) - 1 do
local st = lt + u16(b, lt + 6 + k * 2)
local sty = ty
if ty == 9 and u16(b, st) == 1 then -- extension
sty = u16(b, st + 2)
st += u32(b, st + 4)
end
if sty == 2 then
table.insert(subs, st)
end
end
if #subs > 0 then
table.insert(lookups, subs)
end
end
end
if #lookups == 0 then
return nil
end
return { buf = b, subtables = lookups }
end
-- gposKern(gpos, left, right) -> the summed x advance adjustment of the first glyph (font units)
function Tables.gposKern(g: Gpos, l: number, r: number): number
local total = 0
for _, subs in g.subtables do
for _, st in subs do
local applies, v = pairPos(g.buf, st, l, r)
if applies then
total += v
break
end
end
end
return total
end
-- ------------------------------------------------------------------------------------------------ name, OS/2
local MAC_ROMAN_HIGH = {
0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1, 0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8,
0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3, 0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC,
0x2020, 0xB0, 0xA2, 0xA3, 0xA7, 0x2022, 0xB6, 0xDF, 0xAE, 0xA9, 0x2122, 0xB4, 0xA8, 0x2260, 0xC6, 0xD8,
0x221E, 0xB1, 0x2264, 0x2265, 0xA5, 0xB5, 0x2202, 0x2211, 0x220F, 0x3C0, 0x222B, 0xAA, 0xBA, 0x3A9, 0xE6, 0xF8,
0xBF, 0xA1, 0xAC, 0x221A, 0x192, 0x2248, 0x2206, 0xAB, 0xBB, 0x2026, 0xA0, 0xC0, 0xC3, 0xD5, 0x152, 0x153,
0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0xF7, 0x25CA, 0xFF, 0x178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02,
0x2021, 0xB7, 0x201A, 0x201E, 0x2030, 0xC2, 0xCA, 0xC1, 0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4,
0xF8FF, 0xD2, 0xDA, 0xDB, 0xD9, 0x131, 0x2C6, 0x2DC, 0xAF, 0x2D8, 0x2D9, 0x2DA, 0xB8, 0x2DD, 0x2DB, 0x2C7,
}
local function utf16be(b: buffer, o: number, n: number): string
local out = {}
local k = 0
while k + 1 < n do
local c = u16(b, o + k)
k += 2
if c >= 0xD800 and c < 0xDC00 and k + 1 < n then
local lo = u16(b, o + k)
if lo >= 0xDC00 and lo < 0xE000 then
c = 0x10000 + (c - 0xD800) * 1024 + (lo - 0xDC00)
k += 2
end
end
if c >= 0xD800 and c < 0xE000 then
c = 0xFFFD
end
table.insert(out, utf8.char(c))
end
return table.concat(out)
end
local function macRoman(b: buffer, o: number, n: number): string
local out = {}
for k = 0, n - 1 do
local c = u8(b, o + k)
table.insert(out, utf8.char(if c < 128 then c else MAC_ROMAN_HIGH[c - 127]))
end
return table.concat(out)
end
local NAME_IDS = {
[0] = "copyright",
[1] = "family",
[2] = "style",
[3] = "uniqueId",
[4] = "fullName",
[5] = "version",
[6] = "postScriptName",
[7] = "trademark",
[8] = "manufacturer",
[9] = "designer",
[10] = "description",
[11] = "vendorUrl",
[12] = "designerUrl",
[13] = "license",
[14] = "licenseUrl",
[16] = "typographicFamily",
[17] = "typographicStyle",
}
-- names(name table) -> { family, style, fullName, ... } (English Windows names first, then Unicode, then Mac Roman)
function Tables.names(b: buffer, o: number, n: number): { [string]: string }
local out: { [string]: string } = {}
local rank: { [string]: number } = {}
local count, strings = u16(b, o + 2), o + u16(b, o + 4)
for i = 0, math.min(count, 4096) - 1 do
local r = o + 6 + i * 12
if r + 12 > o + n then
break
end
local pid, eid, lang, nid = u16(b, r), u16(b, r + 2), u16(b, r + 4), u16(b, r + 6)
local len, off = u16(b, r + 8), u16(b, r + 10)
local key = NAME_IDS[nid]
if key and strings + off + len <= o + n then
local rk, s = 0, nil
if pid == 3 and (eid == 1 or eid == 10 or eid == 0) then
rk = if lang == 0x409 then 4 else 2
s = utf16be(b, strings + off, len)
elseif pid == 0 then
rk = 3
s = utf16be(b, strings + off, len)
elseif pid == 1 and eid == 0 then
rk = if lang == 0 then 1 else 0.5
s = macRoman(b, strings + off, len)
end
if s and rk > (rank[key] or 0) then
out[key] = s
rank[key] = rk
end
end
end
return out
end
-- os2(OS/2 table) -> the commonly used fields
function Tables.os2(b: buffer, o: number, n: number): { [string]: number }
local t: { [string]: number } = {
version = u16(b, o),
xAvgCharWidth = i16(b, o + 2),
weightClass = u16(b, o + 4),
widthClass = u16(b, o + 6),
fsType = u16(b, o + 8),
}
if n >= 78 then
t.fsSelection = u16(b, o + 62)
t.firstChar = u16(b, o + 64)
t.lastChar = u16(b, o + 66)
t.typoAscender = i16(b, o + 68)
t.typoDescender = i16(b, o + 70)
t.typoLineGap = i16(b, o + 72)
t.winAscent = u16(b, o + 74)
t.winDescent = u16(b, o + 76)
end
if n >= 96 and t.version >= 2 then
t.xHeight = i16(b, o + 86)
t.capHeight = i16(b, o + 88)
end
return t
end
return Tables
+338
View File
@@ -0,0 +1,338 @@
--!strict
-- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
-- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines
-- (codecs/TrueType/Glyf for glyf, codecs/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments),
-- names, and rasterize(glyph, px) through codecs/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all
-- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean
-- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/Raster instead of stb's.
-- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix),
-- colour layers (COLR), GSUB substitutions.
--
-- local font, err = TrueType.font(buf, offset?, length?, { index = 0 }) -- Types.Font | nil, Err
-- local g = font:glyphIndex(0x41) local adv = font:advance(g) -- font units
-- local k = font:kern(g1, g2) local cmds = font:outline(g) -- moveTo / lineTo / quadTo / cubicTo
-- local img = font:rasterize(g, 32) -- alpha8 Image, 32 px per em; img.meta.left / top / advance (px)
-- local n = TrueType.count(buf) -- fonts in a collection (1 for a plain sfnt)
--
-- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Raster = require("@formats/codecs/Raster")
local Cff = require("@formats/codecs/Cff")
local Glyf = require("@formats/codecs/TrueType/Glyf")
local Tables = require("@formats/codecs/TrueType/Tables")
local TrueType = {}
local u16, i16, u32 = Tables.u16, Tables.i16, Tables.u32
local function tag(b: buffer, o: number): string
if o < 0 or o + 4 > buffer.len(b) then
return ""
end
return buffer.readstring(b, o, 4)
end
-- count(buf, offset?) -> the number of fonts (a collection's count, 1 for an sfnt, 0 for neither)
function TrueType.count(b: buffer, offset: number?): number
local o = offset or 0
local t = tag(b, o)
if t == "ttcf" then
return u32(b, o + 8)
end
if t == "\0\1\0\0" or t == "OTTO" or t == "true" or t == "typ1" then
return 1
end
return 0
end
-- tables(buf, file, dir) -> { [tag] = { offset (absolute), length } } of the table directory at dir
function TrueType.tables(b: buffer, file: number, dir: number, limit: number): ({ [string]: { number } }?, string?)
local n = u16(b, dir + 4)
if dir + 12 + n * 16 > limit then
return nil, "table directory past the end"
end
local out: { [string]: { number } } = {}
for i = 0, n - 1 do
local r = dir + 12 + i * 16
local t = tag(b, r)
local off, len = u32(b, r + 8), u32(b, r + 12)
if file + off + len <= limit then
out[t] = { file + off, len }
end
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ the Font value
local Face = {}
Face.__index = Face
function Face.glyphIndex(self: any, cp: number): number
return Tables.glyph(self._cmap, cp)
end
function Face.advance(self: any, g: number): number
if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then
return 0
end
local nh = self._numHMetrics
if nh == 0 then
return 0
end
local h = self._hmtx
return u16(self._buf, h + 4 * math.min(g, nh - 1))
end
function Face.leftSideBearing(self: any, g: number): number
if type(g) ~= "number" or g < 0 or g >= self.numGlyphs then
return 0
end
local nh, h = self._numHMetrics, self._hmtx
if g < nh then
return i16(self._buf, h + 4 * g + 2)
end
return i16(self._buf, h + 4 * nh + 2 * (g - nh))
end
function Face.kern(self: any, a: number, b: number): number
if type(a) ~= "number" or type(b) ~= "number" then
return 0
end
local key = a * 65536 + b
local cache = self._kernCache
local v = cache[key]
if v then
return v
end
v = 0
if self._gpos then
v = Tables.gposKern(self._gpos, a, b)
end
if v == 0 and self._kern then
v = self._kern[key] or 0
end
cache[key] = v
return v
end
-- kernCodepoints(a, b) -> kern between two code points
function Face.kernCodepoints(self: any, a: number, b: number): number
return self:kern(self:glyphIndex(a), self:glyphIndex(b))
end
function Face.outline(self: any, g: number): { any }?
if type(g) ~= "number" or g < 0 or g >= self.numGlyphs or g % 1 ~= 0 then
return nil
end
local ok, cmds, err = pcall(function()
if self._cff then
return Cff.outline(self._cff, g)
end
return Glyf.outline(self._glyf, g)
end)
if not ok then
self.meta.lastError = tostring(cmds)
return nil
end
if not cmds then
self.meta.lastError = err
end
return cmds
end
-- bounds(g) -> xMin, yMin, xMax, yMax of the outline's points (font units), nil for an empty / bad glyph
function Face.bounds(self: any, g: number): (number?, number, number, number)
local cmds = self:outline(g)
if not cmds then
return nil, 0, 0, 0
end
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
for _, c in cmds do
for i = 1, #c - 1, 2 do
local x, y = c[i], c[i + 1]
x0, y0, x1, y1 = math.min(x0, x), math.min(y0, y), math.max(x1, x), math.max(y1, y)
end
end
if x0 > x1 then
return nil, 0, 0, 0
end
return x0, y0, x1, y1
end
-- scale(px) -> pixels per font unit for an em of px pixels
function Face.scale(self: any, px: number): number
return px / self.unitsPerEm
end
export type RasterOptions = {
scaleX: number?, -- pixels per font unit (default px / unitsPerEm); scaleY likewise
scaleY: number?,
shiftX: number?, -- subpixel shift (pixels)
shiftY: number?,
}
-- rasterize(g, px, opts?) -> alpha8 Image (meta.left / meta.top: the bitmap's offset from the pen position, pixels;
-- top counts up from the baseline as FreeType's bitmap_top; meta.advance in pixels) | nil for a bad glyph. Empty
-- glyphs give a 0 x 0 image.
function Face.rasterize(self: any, g: number, px: number, opts: RasterOptions?): Types.Image?
if type(px) ~= "number" or not (px > 0) or px > 4096 then
return nil
end
local cmds = self:outline(g)
if not cmds then
return nil
end
local o = opts or {}
local sx = if type(o.scaleX) == "number" then o.scaleX else px / self.unitsPerEm
local sy = if type(o.scaleY) == "number" then o.scaleY else sx
local tx, ty = o.shiftX or 0, o.shiftY or 0
local m = Raster.mask(cmds, { transform = { sx, 0, 0, -sy, tx, ty }, 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 = m.x
img.meta.top = -m.y
else
img = Types.Image.new(0, 0, "alpha8")
img.meta.left = 0
img.meta.top = 0
end
img.meta.advance = self:advance(g) * sx
img.meta.glyph = g
return img
end
-- ------------------------------------------------------------------------------------------------ parsing
export type Options = { index: number? } -- the font in a collection (default 0)
-- font(buf, offset?, length?, opts?) -> Types.Font | nil, Err
function TrueType.font(buf: buffer, offset: number?, length: number?, opts: Options?): (any, Err.Err?)
local b = buf
local file = offset or 0
local limit = math.min(buffer.len(b), file + (length or (buffer.len(b) - file)))
if limit - file < 12 then
return nil, Err.new(Err.TRUNCATED, "too short for an sfnt header", file)
end
local dir = file
local index = (opts and opts.index) or 0
local count = TrueType.count(b, file)
if tag(b, file) == "ttcf" then
if type(index) ~= "number" or index < 0 or index >= count or index % 1 ~= 0 then
return nil, Err.new(Err.ARG, string.format("font index %s out of range (collection of %d)", tostring(index), count))
end
dir = file + u32(b, file + 12 + index * 4)
if dir + 12 > limit then
return nil, Err.new(Err.TRUNCATED, "collection font directory past the end", file)
end
elseif count == 0 then
return nil, Err.new(Err.CORRUPT, "not an sfnt font", file)
end
local sfntTag = tag(b, dir)
if sfntTag == "typ1" then
return nil, Err.new(Err.UNSUPPORTED, "PostScript Type 1 sfnt", dir)
end
local t, terr = TrueType.tables(b, file, dir, limit)
if not t then
return nil, Err.new(Err.TRUNCATED, terr or "bad table directory", dir)
end
for _, need in { "head", "hhea", "maxp", "hmtx" } do
if not t[need] then
return nil, Err.new(Err.CORRUPT, "missing the " .. need .. " table", dir)
end
end
local head, hhea, maxp, hmtx = t.head[1], t.hhea[1], t.maxp[1], t.hmtx[1]
if t.head[2] < 54 or t.hhea[2] < 36 or t.maxp[2] < 6 then
return nil, Err.new(Err.TRUNCATED, "short head / hhea / maxp table", dir)
end
local upem = u16(b, head + 18)
if upem < 16 or upem > 16384 then
return nil, Err.new(Err.CORRUPT, "bad unitsPerEm " .. upem, head + 18)
end
local numGlyphs = u16(b, maxp + 4)
local nh = math.min(u16(b, hhea + 34), numGlyphs)
if nh * 4 > t.hmtx[2] then
nh = t.hmtx[2] // 4
end
local font: any = setmetatable({
kind = "font",
info = {},
unitsPerEm = upem,
ascent = i16(b, hhea + 4),
descent = i16(b, hhea + 6),
lineGap = i16(b, hhea + 8),
numGlyphs = numGlyphs,
bbox = { i16(b, head + 36), i16(b, head + 38), i16(b, head + 40), i16(b, head + 42) },
pages = nil,
meta = {},
_buf = b,
_hmtx = hmtx,
_numHMetrics = nh,
_kernCache = {},
}, Face)
-- outlines
if t.glyf and t.loca then
font._glyf = {
buf = b,
glyf = t.glyf[1],
glyfLen = t.glyf[2],
loca = t.loca[1],
locaLen = t.loca[2],
longLoca = i16(b, head + 50) ~= 0,
numGlyphs = numGlyphs,
}
font.meta.outlines = "truetype"
elseif t["CFF "] then
local cff, cerr = Cff.parse(b, t["CFF "][1], t["CFF "][2])
if not cff then
local code = if cerr and string.find(cerr, "unsupported", 1, true) then Err.UNSUPPORTED else Err.CORRUPT
return nil, Err.new(code, "CFF: " .. tostring(cerr), t["CFF "][1])
end
font._cff = cff
font.meta.outlines = "cff"
elseif t.CFF2 then
return nil, Err.new(Err.UNSUPPORTED, "CFF2 outlines (variable OpenType)", dir)
else
return nil, Err.new(Err.UNSUPPORTED, "no glyf or CFF outlines (bitmap-only font?)", dir)
end
-- cmap, kerning, names, OS/2, post
if t.cmap then
font._cmap = Tables.cmap(b, t.cmap[1], t.cmap[2])
end
if t.kern then
font._kern = Tables.kern(b, t.kern[1], t.kern[2])
end
if t.GPOS then
font._gpos = Tables.gpos(b, t.GPOS[1], t.GPOS[2])
end
if t.name then
local names = Tables.names(b, t.name[1], t.name[2])
for k, v in names do
font.info[k] = v
end
font.info.family = names.typographicFamily or names.family
font.info.style = names.typographicStyle or names.style
end
if t["OS/2"] and t["OS/2"][2] >= 10 then
font.meta.os2 = Tables.os2(b, t["OS/2"][1], t["OS/2"][2])
end
if t.post and t.post[2] >= 16 then
local p = t.post[1]
font.meta.italicAngle = i16(b, p + 4) + u16(b, p + 6) / 65536
font.meta.underlinePosition = i16(b, p + 8)
font.meta.underlineThickness = i16(b, p + 10)
font.meta.fixedPitch = u32(b, p + 12) ~= 0
end
local tags = {}
for k in t do
table.insert(tags, k)
end
table.sort(tags)
font.meta.tables = tags
font.meta.sfnt = if sfntTag == "OTTO" then "OTTO" else "TrueType"
font.meta.collection = if count > 1 or tag(b, file) == "ttcf" then { index = index, count = count } else nil
return font, nil
end
return TrueType
+177
View File
@@ -0,0 +1,177 @@
# Font reference data (run by tools/fixtures/fonts.py inside a nix python with fonttools, freetype-py, uharfbuzz and
# brotli). Reads a JSON list of {name, path | b64} on stdin; writes JSON on stdout: per font the bytes, the metrics,
# names, cmap samples (fontTools), advances / side bearings / control boxes / areas of sample glyphs (fontTools pens),
# kerning of sample pairs (HarfBuzz GPOS 'kern', or FreeType for 'kern' tables), FreeType renders (no hinting) of
# sample glyphs at a few sizes, and the WOFF / WOFF2 versions (fontTools).
import base64, io, json, sys
import freetype
import uharfbuzz as hb
from fontTools.pens.areaPen import AreaPen
from fontTools.pens.boundsPen import ControlBoundsPen
from fontTools.ttLib import TTFont, newTable
from fontTools.ttLib.tables._k_e_r_n import KernTable_format_0
SAMPLE_TEXT = "AVTWYLPFoaey.,'\"-0147"
SIZES = [11, 24, 47]
def b64(b):
return base64.b64encode(b).decode()
def load(spec):
if "path" in spec:
return open(spec["path"], "rb").read()
return base64.b64decode(spec["b64"])
def with_kern_table(data):
"""a copy with a 'kern' format 0 table of a few pairs (none of the sample fonts has one)"""
f = TTFont(io.BytesIO(data))
cmap = f.getBestCmap()
order = f.getGlyphOrder()
pairs = {}
letters = "AVTWYLoaey"
for i, a in enumerate(letters):
for j, b in enumerate(letters):
if ord(a) in cmap and ord(b) in cmap and (i * 7 + j * 3) % 4 == 0:
pairs[(cmap[ord(a)], cmap[ord(b)])] = -((i * 13 + j * 5) % 90) - 10
k = newTable("kern")
k.version = 0
st = KernTable_format_0()
st.version, st.coverage, st.format = 0, 1, 0
st.kernTable = pairs
k.kernTables = [st]
f["kern"] = k
if "GPOS" in f:
del f["GPOS"]
out = io.BytesIO()
f.save(out)
return out.getvalue()
def collection(datas):
from fontTools.ttLib.ttCollection import TTCollection
c = TTCollection()
c.fonts = [TTFont(io.BytesIO(d)) for d in datas]
out = io.BytesIO()
c.save(out)
return out.getvalue()
def reference(name, data, index=0):
f = TTFont(io.BytesIO(data), fontNumber=index)
gs = f.getGlyphSet()
order = f.getGlyphOrder()
head, hhea, maxp = f["head"], f["hhea"], f["maxp"]
names = f["name"]
def nm(i):
r = names.getName(i, 3, 1, 0x409) or names.getName(i, 3, 1) or names.getName(i, 1, 0, 0) or names.getName(i, 0, 3)
return r.toUnicode() if r else ""
cmap = f.getBestCmap() or {}
cps = sorted(cmap)
sample_cps = cps[:: max(1, len(cps) // 150)] + [0x10FFFF, 0xFFFF, 0x7F, 0x9999]
cm = [[cp, f.getGlyphID(cmap[cp]) if cp in cmap else 0] for cp in sample_cps]
# glyphs: every glyph for small fonts, else a sample (plus the sample text's)
gids = list(range(len(order))) if len(order) <= 400 else list(range(0, len(order), len(order) // 300))
for ch in SAMPLE_TEXT:
if ord(ch) in cmap:
gids.append(f.getGlyphID(cmap[ord(ch)]))
gids = sorted(set(gids))
hmtx = f["hmtx"]
glyphs = []
for g in gids:
gn = order[g]
adv, lsb = hmtx[gn]
bp = ControlBoundsPen(gs)
gs[gn].draw(bp)
ap = AreaPen(gs)
gs[gn].draw(ap)
e = {"gid": g, "adv": adv, "lsb": lsb, "area": float(ap.value)}
if bp.bounds:
e["box"] = [float(v) for v in bp.bounds]
glyphs.append(e)
# kerning
kern = []
letters = [c for c in SAMPLE_TEXT if ord(c) in cmap]
if "kern" in f and "GPOS" not in f:
face = freetype.Face(io.BytesIO(data), index)
for a in letters:
for b in letters:
ga, gb = f.getGlyphID(cmap[ord(a)]), f.getGlyphID(cmap[ord(b)])
v = face.get_kerning(ga, gb, freetype.FT_KERNING_UNSCALED)
kern.append([ga, gb, v.x])
elif "GPOS" in f:
blob = hb.Blob(data)
hface = hb.Face(blob, index)
hfont = hb.Font(hface)
feats = {"kern": True, "liga": False, "clig": False, "calt": False, "mark": False, "mkmk": False, "ccmp": False, "locl": False, "rlig": False, "dist": False, "curs": False}
for a in letters:
for b in letters:
buf = hb.Buffer()
buf.add_str(a + b)
buf.guess_segment_properties()
hb.shape(hfont, buf, feats)
ga, gb = buf.glyph_infos[0].codepoint, buf.glyph_infos[1].codepoint
adv = buf.glyph_positions[0].x_advance - hmtx[order[ga]][0]
kern.append([ga, gb, adv])
# FreeType renders
face = freetype.Face(io.BytesIO(data), index)
renders = []
rg = [f.getGlyphID(cmap[ord(c)]) for c in "AgQ@&e%" if ord(c) in cmap]
for px in SIZES:
face.set_pixel_sizes(0, px)
for g in rg:
face.load_glyph(g, freetype.FT_LOAD_NO_HINTING | freetype.FT_LOAD_NO_BITMAP)
face.glyph.render(freetype.FT_RENDER_MODE_NORMAL)
bm = face.glyph.bitmap
rows = []
for y in range(bm.rows):
rows.append(bytes(bm.buffer[y * bm.pitch: y * bm.pitch + bm.width]))
renders.append({"gid": g, "px": px, "w": bm.width, "h": bm.rows, "left": face.glyph.bitmap_left,
"top": face.glyph.bitmap_top, "pixels": b64(b"".join(rows))})
os2 = f["OS/2"] if "OS/2" in f else None
return {
"name": name, "data": b64(data), "index": index, "upem": head.unitsPerEm, "ascent": hhea.ascent,
"descent": hhea.descent, "lineGap": hhea.lineGap, "numGlyphs": maxp.numGlyphs, "family": nm(16) or nm(1),
"style": nm(17) or nm(2), "fullName": nm(4), "weight": os2.usWeightClass if os2 else 0,
"cff": "CFF " in f, "cmap": cm, "glyphs": glyphs, "kern": kern, "renders": renders,
}
def flavors(data):
out = {}
for fl in ("woff", "woff2"):
f = TTFont(io.BytesIO(data))
f.flavor = fl
b = io.BytesIO()
f.save(b)
out[fl] = b64(b.getvalue())
return out
def main():
specs = json.load(sys.stdin)
fonts = {}
for s in specs:
fonts[s["name"]] = load(s)
res = {"fonts": [], "woff": []}
for name, data in fonts.items():
res["fonts"].append(reference(name, data))
kd = with_kern_table(fonts["ProggyClean"] if "ProggyClean" in fonts else next(iter(fonts.values())))
res["fonts"].append(reference("kern-table", kd))
names = [n for n in ("Karla-Regular", "Cousine-Regular") if n in fonts]
if len(names) == 2:
ttc = collection([fonts[n] for n in names])
r = reference("collection-1", ttc, 1)
res["fonts"].append(r)
res["ttc"] = {"data": b64(ttc), "count": 2, "second": names[1]}
# woff / woff2 of every font (the reference values are the sfnt's own)
for name, data in fonts.items():
fl = flavors(data)
res["woff"].append({"name": name, "woff": fl["woff"], "woff2": fl["woff2"]})
json.dump(res, sys.stdout)
main()