rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,220 @@
|
||||
--!strict
|
||||
-- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike
|
||||
-- (one pixel size, glyphs as u8 bitmaps, 0 = off / 255 = on) wrapped as a Types.Font whose units are pixels
|
||||
-- (unitsPerEm = the pixel size), glyphIndex / advance / kern work, outline is nil, and rasterize(g) returns the glyph's
|
||||
-- bitmap as an alpha8 Image (img.meta.left / top / advance, as codecs/font/TrueType does; the px argument is ignored,
|
||||
-- img.meta.scale = px / size tells the caller how much to scale). Also: the strike of any Font (its own bitmap, or an
|
||||
-- outline font rasterized at a pixel size and thresholded), which the bitmap font encoders write, and the bit-row
|
||||
-- packing every bitmap font format shares. New code.
|
||||
--
|
||||
-- local font = Bitmap.font(strike, { family = "Fixed" }, { source = { format = "bdf" } })
|
||||
-- local strike, err = Bitmap.strike(anyFont, { px = 16, chars = "abc" }) -- font.bitmap, or rasterized
|
||||
-- local pixels = Bitmap.unpack(buf, off, w, h, stride) -- MSB-first 1-bit rows -> u8 0 / 255
|
||||
-- local bytes = Bitmap.pack(pixels, w, h, stride) -- u8 -> MSB-first rows (buffer)
|
||||
--
|
||||
-- Never throws: rasterize of a bad glyph index returns nil; unpack reads only inside the buffer (missing bits are 0).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Bitmap = {}
|
||||
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bits
|
||||
-- unpack(buf, off, w, h, stride, lsbFirst?) -> u8 pixels (w * h, 0 / 255) from 1-bit rows of stride bytes (MSB = left
|
||||
-- pixel unless lsbFirst); bytes past the end of buf read as 0
|
||||
function Bitmap.unpack(b: buffer, off: number, w: number, h: number, stride: number, lsbFirst: boolean?): buffer
|
||||
local out = buffer.create(math.max(0, w * h))
|
||||
local n = buffer.len(b)
|
||||
for y = 0, h - 1 do
|
||||
local row = off + y * stride
|
||||
for x = 0, w - 1 do
|
||||
local p = row + bit32.rshift(x, 3)
|
||||
if p >= 0 and p < n then
|
||||
local byte = readu8(b, p)
|
||||
local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7)
|
||||
if bit32.band(bit32.rshift(byte, bitn), 1) ~= 0 then
|
||||
writeu8(out, y * w + x, 255)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- pack(pixels, w, h, stride?, lsbFirst?) -> 1-bit rows (stride bytes each, default ceil(w / 8)); a pixel >= 128 is on
|
||||
function Bitmap.pack(px: buffer, w: number, h: number, stride: number?, lsbFirst: boolean?): buffer
|
||||
local s = stride or math.ceil(w / 8)
|
||||
local out = buffer.create(math.max(0, s * h))
|
||||
local n = buffer.len(px)
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local i = y * w + x
|
||||
if i < n and readu8(px, i) >= 128 then
|
||||
local p = y * s + bit32.rshift(x, 3)
|
||||
local bitn = if lsbFirst then bit32.band(x, 7) else 7 - bit32.band(x, 7)
|
||||
writeu8(out, p, bit32.bor(readu8(out, p), bit32.lshift(1, bitn)))
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ font
|
||||
local Face = {}
|
||||
Face.__index = Face
|
||||
|
||||
function Face.glyphIndex(self: any, cp: number): number
|
||||
return self._index[cp] or 0
|
||||
end
|
||||
|
||||
function Face.advance(self: any, g: number): number
|
||||
local gl = self.bitmap.glyphs[g + 1]
|
||||
return if gl then gl.advance else 0
|
||||
end
|
||||
|
||||
function Face.kern(_self: any, _a: number, _b: number): number
|
||||
return 0
|
||||
end
|
||||
|
||||
function Face.outline(_self: any, _g: number): { any }?
|
||||
return nil
|
||||
end
|
||||
|
||||
-- rasterize(g, px?) -> the glyph as an alpha8 Image (px is ignored: meta.scale = px / size)
|
||||
function Face.rasterize(self: any, g: number, px: number?): Types.Image?
|
||||
local gl: Types.BitmapGlyph? = self.bitmap.glyphs[g + 1]
|
||||
if not gl or gl.width < 0 or gl.height < 0 then
|
||||
return nil
|
||||
end
|
||||
local img = Types.Image.new(gl.width, gl.height, "alpha8")
|
||||
local n = math.min(buffer.len(img.pixels), buffer.len(gl.pixels))
|
||||
if n > 0 then
|
||||
buffer.copy(img.pixels, 0, gl.pixels, 0, n)
|
||||
end
|
||||
img.meta.left = gl.left
|
||||
img.meta.top = gl.top
|
||||
img.meta.advance = gl.advance
|
||||
img.meta.glyph = g
|
||||
img.meta.scale = if type(px) == "number" and self.bitmap.size > 0 then px / self.bitmap.size else 1
|
||||
return img
|
||||
end
|
||||
|
||||
-- font(strike, info?, meta?) -> a Types.Font over the strike (font.bitmap = strike)
|
||||
function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta: { [string]: any }?): any
|
||||
local index: { [number]: number } = {}
|
||||
for i, gl in strike.glyphs do
|
||||
local cp = gl.codepoint
|
||||
if cp and index[cp] == nil then
|
||||
index[cp] = i - 1
|
||||
end
|
||||
end
|
||||
if strike.map then
|
||||
for cp, g in strike.map do
|
||||
if index[cp] == nil and g >= 0 and g < #strike.glyphs then
|
||||
index[cp] = g
|
||||
end
|
||||
end
|
||||
end
|
||||
local f = setmetatable({
|
||||
kind = "font",
|
||||
info = info or {},
|
||||
unitsPerEm = strike.size,
|
||||
ascent = strike.ascent,
|
||||
descent = -strike.descent,
|
||||
lineGap = 0,
|
||||
numGlyphs = #strike.glyphs,
|
||||
bitmap = strike,
|
||||
meta = meta or {},
|
||||
_index = index,
|
||||
}, Face)
|
||||
if strike.default then
|
||||
setmetatable(index, { __index = function()
|
||||
return strike.default
|
||||
end })
|
||||
end
|
||||
return f
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ strike
|
||||
export type StrikeOptions = {
|
||||
px: number?, -- pixel size for outline fonts (default 16)
|
||||
chars: (string | { number })?, -- code points for outline fonts (default 32..126)
|
||||
threshold: number?, -- coverage 0..255 at or above which a pixel is on (default 128)
|
||||
}
|
||||
|
||||
local function codepoints(chars: (string | { number })?): { number }
|
||||
if type(chars) == "table" then
|
||||
return chars
|
||||
end
|
||||
local out = {}
|
||||
if type(chars) == "string" then
|
||||
for _, c in utf8.codes(chars) do
|
||||
table.insert(out, c)
|
||||
end
|
||||
return out
|
||||
end
|
||||
for c = 32, 126 do
|
||||
table.insert(out, c)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- strike(font, opts?) -> the font's BitmapStrike: font.bitmap, else the outline font rasterized at opts.px
|
||||
function Bitmap.strike(font: any, opts: StrikeOptions?): (Types.BitmapStrike?, Err.Err?)
|
||||
if type(font) ~= "table" or font.kind ~= "font" then
|
||||
return nil, Err.new(Err.ARG, "expected a Font")
|
||||
end
|
||||
if type(font.bitmap) == "table" and type(font.bitmap.glyphs) == "table" then
|
||||
return font.bitmap, nil
|
||||
end
|
||||
if type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then
|
||||
return nil, Err.new(Err.ARG, "font has no glyphs to rasterize")
|
||||
end
|
||||
local o: StrikeOptions = opts or {}
|
||||
local px = o.px or 16
|
||||
if type(px) ~= "number" or px < 1 or px > 1024 then
|
||||
return nil, Err.new(Err.ARG, "px must be 1..1024")
|
||||
end
|
||||
local threshold = o.threshold or 128
|
||||
local upm = if type(font.unitsPerEm) == "number" and font.unitsPerEm > 0 then font.unitsPerEm else px
|
||||
local scale = px / upm
|
||||
local ascent = math.ceil((font.ascent or upm) * scale)
|
||||
local descent = math.ceil(math.abs(font.descent or 0) * scale)
|
||||
local glyphs: { Types.BitmapGlyph } = {}
|
||||
local function add(cp: number?, g: number)
|
||||
local ok, img = pcall(font.rasterize, font, g, px)
|
||||
local adv = 0
|
||||
local aok, a = pcall(font.advance, font, g)
|
||||
if aok and type(a) == "number" then
|
||||
adv = math.floor(a * scale + 0.5)
|
||||
end
|
||||
local gl: Types.BitmapGlyph = { codepoint = cp, width = 0, height = 0, left = 0, top = 0, advance = adv, pixels = buffer.create(0) }
|
||||
if ok and type(img) == "table" and type(img.pixels) == "buffer" and img.format == "alpha8" then
|
||||
local n = img.width * img.height
|
||||
local pxs = buffer.create(n)
|
||||
for i = 0, math.min(n, buffer.len(img.pixels)) - 1 do
|
||||
if readu8(img.pixels, i) >= threshold then
|
||||
writeu8(pxs, i, 255)
|
||||
end
|
||||
end
|
||||
gl.width, gl.height, gl.pixels = img.width, img.height, pxs
|
||||
gl.left = math.floor(img.meta.left or 0)
|
||||
gl.top = math.floor(img.meta.top or 0)
|
||||
if type(img.meta.advance) == "number" then
|
||||
gl.advance = math.floor(img.meta.advance + 0.5)
|
||||
end
|
||||
end
|
||||
table.insert(glyphs, gl)
|
||||
end
|
||||
add(nil, 0)
|
||||
for _, cp in codepoints(o.chars) do
|
||||
local ok, g = pcall(font.glyphIndex, font, cp)
|
||||
if ok and type(g) == "number" and g > 0 then
|
||||
add(cp, g)
|
||||
end
|
||||
end
|
||||
return { size = px, ascent = ascent, descent = descent, glyphs = glyphs, default = 0 }, nil
|
||||
end
|
||||
|
||||
return Bitmap
|
||||
@@ -0,0 +1,657 @@
|
||||
--!strict
|
||||
-- codecs/font/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 = table.create(32, 0) :: { number }
|
||||
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
|
||||
@@ -0,0 +1,154 @@
|
||||
--!strict
|
||||
-- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a
|
||||
-- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause:
|
||||
-- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and
|
||||
-- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name).
|
||||
-- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding.
|
||||
--
|
||||
-- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown)
|
||||
-- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef)
|
||||
local GlyphNames = {}
|
||||
|
||||
-- AGLFN: "name hex" pairs
|
||||
local AGL = "" ..
|
||||
"A 41 AE C6 AEacute 1FC Aacute C1 Abreve 102 Acircumflex C2 Adieresis C4 Agrave C0 Alpha 391 " ..
|
||||
"Alphatonos 386 Amacron 100 Aogonek 104 Aring C5 Aringacute 1FA Atilde C3 B 42 Beta 392 C 43 Cacute " ..
|
||||
"106 Ccaron 10C Ccedilla C7 Ccircumflex 108 Cdotaccent 10A Chi 3A7 D 44 Dcaron 10E Dcroat 110 Delta " ..
|
||||
"2206 E 45 Eacute C9 Ebreve 114 Ecaron 11A Ecircumflex CA Edieresis CB Edotaccent 116 Egrave C8 " ..
|
||||
"Emacron 112 Eng 14A Eogonek 118 Epsilon 395 Epsilontonos 388 Eta 397 Etatonos 389 Eth D0 Euro 20AC " ..
|
||||
"F 46 G 47 Gamma 393 Gbreve 11E Gcaron 1E6 Gcircumflex 11C Gdotaccent 120 H 48 H18533 25CF H18543 " ..
|
||||
"25AA H18551 25AB H22073 25A1 Hbar 126 Hcircumflex 124 I 49 IJ 132 Iacute CD Ibreve 12C Icircumflex " ..
|
||||
"CE Idieresis CF Idotaccent 130 Ifraktur 2111 Igrave CC Imacron 12A Iogonek 12E Iota 399 " ..
|
||||
"Iotadieresis 3AA Iotatonos 38A Itilde 128 J 4A Jcircumflex 134 K 4B Kappa 39A L 4C Lacute 139 " ..
|
||||
"Lambda 39B Lcaron 13D Ldot 13F Lslash 141 M 4D Mu 39C N 4E Nacute 143 Ncaron 147 Ntilde D1 Nu 39D O " ..
|
||||
"4F OE 152 Oacute D3 Obreve 14E Ocircumflex D4 Odieresis D6 Ograve D2 Ohorn 1A0 Ohungarumlaut 150 " ..
|
||||
"Omacron 14C Omega 2126 Omegatonos 38F Omicron 39F Omicrontonos 38C Oslash D8 Oslashacute 1FE Otilde " ..
|
||||
"D5 P 50 Phi 3A6 Pi 3A0 Psi 3A8 Q 51 R 52 Racute 154 Rcaron 158 Rfraktur 211C Rho 3A1 S 53 SF010000 " ..
|
||||
"250C SF020000 2514 SF030000 2510 SF040000 2518 SF050000 253C SF060000 252C SF070000 2534 SF080000 " ..
|
||||
"251C SF090000 2524 SF100000 2500 SF110000 2502 SF190000 2561 SF200000 2562 SF210000 2556 SF220000 " ..
|
||||
"2555 SF230000 2563 SF240000 2551 SF250000 2557 SF260000 255D SF270000 255C SF280000 255B SF360000 " ..
|
||||
"255E SF370000 255F SF380000 255A SF390000 2554 SF400000 2569 SF410000 2566 SF420000 2560 SF430000 " ..
|
||||
"2550 SF440000 256C SF450000 2567 SF460000 2568 SF470000 2564 SF480000 2565 SF490000 2559 SF500000 " ..
|
||||
"2558 SF510000 2552 SF520000 2553 SF530000 256B SF540000 256A Sacute 15A Scaron 160 Scedilla 15E " ..
|
||||
"Scircumflex 15C Sigma 3A3 T 54 Tau 3A4 Tbar 166 Tcaron 164 Theta 398 Thorn DE U 55 Uacute DA Ubreve " ..
|
||||
"16C Ucircumflex DB Udieresis DC Ugrave D9 Uhorn 1AF Uhungarumlaut 170 Umacron 16A Uogonek 172 " ..
|
||||
"Upsilon 3A5 Upsilon1 3D2 Upsilondieresis 3AB Upsilontonos 38E Uring 16E Utilde 168 V 56 W 57 Wacute " ..
|
||||
"1E82 Wcircumflex 174 Wdieresis 1E84 Wgrave 1E80 X 58 Xi 39E Y 59 Yacute DD Ycircumflex 176 " ..
|
||||
"Ydieresis 178 Ygrave 1EF2 Z 5A Zacute 179 Zcaron 17D Zdotaccent 17B Zeta 396 a 61 aacute E1 abreve " ..
|
||||
"103 acircumflex E2 acute B4 acutecomb 301 adieresis E4 ae E6 aeacute 1FD agrave E0 aleph 2135 alpha " ..
|
||||
"3B1 alphatonos 3AC amacron 101 ampersand 26 angle 2220 angleleft 2329 angleright 232A anoteleia 387 " ..
|
||||
"aogonek 105 approxequal 2248 aring E5 aringacute 1FB arrowboth 2194 arrowdblboth 21D4 arrowdbldown " ..
|
||||
"21D3 arrowdblleft 21D0 arrowdblright 21D2 arrowdblup 21D1 arrowdown 2193 arrowleft 2190 arrowright " ..
|
||||
"2192 arrowup 2191 arrowupdn 2195 arrowupdnbse 21A8 asciicircum 5E asciitilde 7E asterisk 2A " ..
|
||||
"asteriskmath 2217 at 40 atilde E3 b 62 backslash 5C bar 7C beta 3B2 block 2588 braceleft 7B " ..
|
||||
"braceright 7D bracketleft 5B bracketright 5D breve 2D8 brokenbar A6 bullet 2022 c 63 cacute 107 " ..
|
||||
"caron 2C7 carriagereturn 21B5 ccaron 10D ccedilla E7 ccircumflex 109 cdotaccent 10B cedilla B8 cent " ..
|
||||
"A2 chi 3C7 circle 25CB circlemultiply 2297 circleplus 2295 circumflex 2C6 club 2663 colon 3A " ..
|
||||
"colonmonetary 20A1 comma 2C congruent 2245 copyright A9 currency A4 d 64 dagger 2020 daggerdbl 2021 " ..
|
||||
"dcaron 10F dcroat 111 degree B0 delta 3B4 diamond 2666 dieresis A8 dieresistonos 385 divide F7 " ..
|
||||
"dkshade 2593 dnblock 2584 dollar 24 dong 20AB dotaccent 2D9 dotbelowcomb 323 dotlessi 131 dotlessj " ..
|
||||
"237 dotmath 22C5 e 65 eacute E9 ebreve 115 ecaron 11B ecircumflex EA edieresis EB edotaccent 117 " ..
|
||||
"egrave E8 eight 38 element 2208 ellipsis 2026 emacron 113 emdash 2014 emptyset 2205 endash 2013 eng " ..
|
||||
"14B eogonek 119 epsilon 3B5 epsilontonos 3AD equal 3D equivalence 2261 estimated 212E eta 3B7 " ..
|
||||
"etatonos 3AE eth F0 exclam 21 exclamdbl 203C exclamdown A1 existential 2203 f 66 female 2640 ff " ..
|
||||
"FB00 ffi FB03 ffl FB04 fi FB01 figuredash 2012 filledbox 25A0 filledrect 25AC five 35 fiveeighths " ..
|
||||
"215D fl FB02 florin 192 four 34 fraction 2044 franc 20A3 g 67 gamma 3B3 gbreve 11F gcaron 1E7 " ..
|
||||
"gcircumflex 11D gdotaccent 121 germandbls DF gradient 2207 grave 60 gravecomb 300 greater 3E " ..
|
||||
"greaterequal 2265 guillemotleft AB guillemotright BB guilsinglleft 2039 guilsinglright 203A h 68 " ..
|
||||
"hbar 127 hcircumflex 125 heart 2665 hookabovecomb 309 house 2302 hungarumlaut 2DD hyphen 2D i 69 " ..
|
||||
"iacute ED ibreve 12D icircumflex EE idieresis EF igrave EC ij 133 imacron 12B infinity 221E " ..
|
||||
"integral 222B integralbt 2321 integraltp 2320 intersection 2229 invbullet 25D8 invcircle 25D9 " ..
|
||||
"invsmileface 263B iogonek 12F iota 3B9 iotadieresis 3CA iotadieresistonos 390 iotatonos 3AF itilde " ..
|
||||
"129 j 6A jcircumflex 135 k 6B kappa 3BA kgreenlandic 138 l 6C lacute 13A lambda 3BB lcaron 13E ldot " ..
|
||||
"140 less 3C lessequal 2264 lfblock 258C lira 20A4 logicaland 2227 logicalnot AC logicalor 2228 " ..
|
||||
"longs 17F lozenge 25CA lslash 142 ltshade 2591 m 6D macron AF male 2642 minus 2212 minute 2032 mu " ..
|
||||
"B5 multiply D7 musicalnote 266A musicalnotedbl 266B n 6E nacute 144 napostrophe 149 ncaron 148 nine " ..
|
||||
"39 notelement 2209 notequal 2260 notsubset 2284 ntilde F1 nu 3BD numbersign 23 o 6F oacute F3 " ..
|
||||
"obreve 14F ocircumflex F4 odieresis F6 oe 153 ogonek 2DB ograve F2 ohorn 1A1 ohungarumlaut 151 " ..
|
||||
"omacron 14D omega 3C9 omega1 3D6 omegatonos 3CE omicron 3BF omicrontonos 3CC one 31 onedotenleader " ..
|
||||
"2024 oneeighth 215B onehalf BD onequarter BC onethird 2153 openbullet 25E6 ordfeminine AA " ..
|
||||
"ordmasculine BA orthogonal 221F oslash F8 oslashacute 1FF otilde F5 p 70 paragraph B6 parenleft 28 " ..
|
||||
"parenright 29 partialdiff 2202 percent 25 period 2E periodcentered B7 perpendicular 22A5 " ..
|
||||
"perthousand 2030 peseta 20A7 phi 3C6 phi1 3D5 pi 3C0 plus 2B plusminus B1 prescription 211E product " ..
|
||||
"220F propersubset 2282 propersuperset 2283 proportional 221D psi 3C8 q 71 question 3F questiondown " ..
|
||||
"BF quotedbl 22 quotedblbase 201E quotedblleft 201C quotedblright 201D quoteleft 2018 quotereversed " ..
|
||||
"201B quoteright 2019 quotesinglbase 201A quotesingle 27 r 72 racute 155 radical 221A rcaron 159 " ..
|
||||
"reflexsubset 2286 reflexsuperset 2287 registered AE revlogicalnot 2310 rho 3C1 ring 2DA rtblock " ..
|
||||
"2590 s 73 sacute 15B scaron 161 scedilla 15F scircumflex 15D second 2033 section A7 semicolon 3B " ..
|
||||
"seven 37 seveneighths 215E shade 2592 sigma 3C3 sigma1 3C2 similar 223C six 36 slash 2F smileface " ..
|
||||
"263A space 20 spade 2660 sterling A3 suchthat 220B summation 2211 sun 263C t 74 tau 3C4 tbar 167 " ..
|
||||
"tcaron 165 therefore 2234 theta 3B8 theta1 3D1 thorn FE three 33 threeeighths 215C threequarters BE " ..
|
||||
"tilde 2DC tildecomb 303 tonos 384 trademark 2122 triagdn 25BC triaglf 25C4 triagrt 25BA triagup " ..
|
||||
"25B2 two 32 twodotenleader 2025 twothirds 2154 u 75 uacute FA ubreve 16D ucircumflex FB udieresis " ..
|
||||
"FC ugrave F9 uhorn 1B0 uhungarumlaut 171 umacron 16B underscore 5F underscoredbl 2017 union 222A " ..
|
||||
"universal 2200 uogonek 173 upblock 2580 upsilon 3C5 upsilondieresis 3CB upsilondieresistonos 3B0 " ..
|
||||
"upsilontonos 3CD uring 16F utilde 169 v 76 w 77 wacute 1E83 wcircumflex 175 wdieresis 1E85 " ..
|
||||
"weierstrass 2118 wgrave 1E81 x 78 xi 3BE y 79 yacute FD ycircumflex 177 ydieresis FF yen A5 ygrave " ..
|
||||
"1EF3 z 7A zacute 17A zcaron 17E zdotaccent 17C zero 30 zeta 3B6 " ..
|
||||
""
|
||||
|
||||
-- StandardEncoding: 256 names, "-" = .notdef
|
||||
local STD = "" ..
|
||||
"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - space exclam quotedbl numbersign " ..
|
||||
"dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash " ..
|
||||
"zero one two three four five six seven eight nine colon semicolon less equal greater question at A " ..
|
||||
"B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " ..
|
||||
"underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright " ..
|
||||
"asciitilde - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exclamdown cent " ..
|
||||
"sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft " ..
|
||||
"guilsinglright fi fl - endash dagger daggerdbl periodcentered - paragraph bullet quotesinglbase " ..
|
||||
"quotedblbase quotedblright guillemotright ellipsis perthousand - questiondown - grave acute " ..
|
||||
"circumflex tilde macron breve dotaccent dieresis - ring cedilla - hungarumlaut ogonek caron emdash " ..
|
||||
"- - - - - - - - - - - - - - - - AE - ordfeminine - - - - Lslash Oslash OE ordmasculine - - - - - ae " ..
|
||||
"- - - dotlessi - - lslash oslash oe germandbls - - - - " ..
|
||||
""
|
||||
|
||||
local byName: { [string]: number }? = nil
|
||||
|
||||
local function load(): { [string]: number }
|
||||
local t: { [string]: number } = {}
|
||||
for name, hex in string.gmatch(AGL, "(%S+) (%x+)") do
|
||||
t[name] = tonumber(hex, 16) :: number
|
||||
end
|
||||
byName = t
|
||||
return t
|
||||
end
|
||||
|
||||
local STANDARD: { [number]: string } = {}
|
||||
do
|
||||
local i = 0
|
||||
for name in string.gmatch(STD, "%S+") do
|
||||
if name ~= "-" then
|
||||
STANDARD[i] = name
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
GlyphNames.STANDARD = STANDARD
|
||||
|
||||
-- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil
|
||||
function GlyphNames.unicode(name: string): number?
|
||||
local base = string.match(name, "^([^%.]+)") or name
|
||||
local t = byName or load()
|
||||
local v = t[base]
|
||||
if v then
|
||||
return v
|
||||
end
|
||||
local hex = string.match(base, "^uni(%x%x%x%x)")
|
||||
if hex then
|
||||
local c = tonumber(hex, 16) :: number
|
||||
return if c >= 0xD800 and c < 0xE000 then nil else c
|
||||
end
|
||||
hex = string.match(base, "^u(%x%x%x%x%x?%x?)$")
|
||||
if hex then
|
||||
local c = tonumber(hex, 16) :: number
|
||||
return if c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) then nil else c
|
||||
end
|
||||
local first = string.match(base, "^([^_]+)_")
|
||||
if first then
|
||||
return GlyphNames.unicode(first)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
return GlyphNames
|
||||
@@ -0,0 +1,403 @@
|
||||
--!strict
|
||||
-- codecs/font/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) :: number
|
||||
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) :: { number }
|
||||
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 = table.create(nc) :: { Contour }
|
||||
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) :: number
|
||||
else
|
||||
a1, a2 = u16(b, p), u16(b, p + 2) :: number
|
||||
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) :: number
|
||||
else
|
||||
a1, a2 = readu8(b, p), readu8(b, p + 1) :: number
|
||||
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 = table.create(#child) :: { Contour }
|
||||
for i, c in child do
|
||||
local nx, ny = table.create(#c.x) :: { number }, table.create(#c.x) :: { number }
|
||||
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/image/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
|
||||
@@ -0,0 +1,519 @@
|
||||
--!strict
|
||||
-- codecs/font/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 Text = require("@rosetta/codecs/text/Text")
|
||||
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
|
||||
return Text.utf16(b, o, n, true)
|
||||
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: { [number]: string } = {
|
||||
[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: number, s: string? = 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
|
||||
@@ -0,0 +1,338 @@
|
||||
--!strict
|
||||
-- codecs/font/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/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments),
|
||||
-- names, and rasterize(glyph, px) through codecs/image/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/image/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("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Raster = require("@rosetta/codecs/image/Raster")
|
||||
local Cff = require("@rosetta/codecs/font/Cff")
|
||||
local Glyf = require("@rosetta/codecs/font/TrueType/Glyf")
|
||||
local Tables = require("@rosetta/codecs/font/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: RasterOptions = 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
|
||||
Reference in new issue
Block a user