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:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+295
View File
@@ -0,0 +1,295 @@
--!strict
-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the
-- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in
-- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used),
-- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to
-- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for
-- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and
-- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font
-- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification.
-- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Bitmap = require("@rosetta/codecs/font/Bitmap")
-- ------------------------------------------------------------------------------------------------ contract
local Bdf = {
name = "bdf",
category = "font",
extensions = { "bdf" },
mime = { "application/x-font-bdf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
caps = { decode = true, encode = true, bitmap = true },
}
export type DecodeOptions = { maxGlyphs: number? } -- default 1114112
export type EncodeOptions = {
px: number?, -- pixel size for outline fonts (default 16)
chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
name: string?, -- the FONT (XLFD) name (default built from the font's family / style)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Bdf.sniff(r: Bytes.Reader): number
local head = r:peek(32)
return if string.match(head, "^STARTFONT%s+2%.%d") then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function unquote(v: string): any
local s = string.match(v, '^"(.*)"%s*$')
if s then
return (string.gsub(s, '""', '"'))
end
return tonumber(v) or v
end
local function hexRow(line: string, w: number, row: buffer, rowOff: number)
local n = math.min(#line // 2, math.ceil(w / 8))
for i = 0, n - 1 do
local v = tonumber(string.sub(line, i * 2 + 1, i * 2 + 2), 16) or 0
buffer.writeu8(row, rowOff + i, v)
end
end
function Bdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 1114112
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local lines = string.split(text, "\n")
local props: { [string]: any } = {}
local fontName, size = "", 0
local fbb = { 0, 0, 0, 0 }
local fontDw = 0
local glyphs: { Types.BitmapGlyph } = {}
local encodings: { number } = {}
local i = 1
local n = #lines
local function line(): string
local l = string.gsub(lines[i] or "", "\r$", "")
i += 1
return l
end
local first = line()
if not string.match(first, "^STARTFONT%s") then
return nil, Err.new(Err.CORRUPT, "no STARTFONT")
end
local ended = false
while i <= n do
local l = line()
local key, rest = string.match(l, "^(%S+)%s*(.*)$")
if key == "FONT" then
fontName = rest :: string
elseif key == "SIZE" then
size = tonumber(string.match(rest :: string, "^(%S+)")) or 0
elseif key == "FONTBOUNDINGBOX" then
local a, b, c, d = string.match(rest :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)")
fbb = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 }
elseif key == "DWIDTH" then
fontDw = tonumber(string.match(rest :: string, "^(%-?%d+)")) or 0
elseif key == "STARTPROPERTIES" then
while i <= n do
local pl = line()
if string.match(pl, "^ENDPROPERTIES") then
break
end
local pk, pv = string.match(pl, "^(%S+)%s*(.*)$")
if pk then
props[pk :: string] = unquote(pv :: string)
end
end
elseif key == "STARTCHAR" then
if #glyphs >= maxGlyphs then
return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
end
local name = rest :: string
local enc = -1
local dw = fontDw
local bbx = { fbb[1], fbb[2], fbb[3], fbb[4] }
local px: buffer? = nil
while i <= n do
local cl = line()
local ck, cr = string.match(cl, "^(%S+)%s*(.*)$")
if ck == "ENCODING" then
local e1, e2 = string.match(cr :: string, "^(%-?%d+)%s*(%-?%d*)")
enc = tonumber(e1) or -1
if enc == -1 and e2 and e2 ~= "" then
enc = -(tonumber(e2) or 1) - 1 -- a non-standard code: kept negative (meta.encodings)
end
elseif ck == "DWIDTH" then
dw = tonumber(string.match(cr :: string, "^(%-?%d+)")) or dw
elseif ck == "BBX" then
local a, b, c, d = string.match(cr :: string, "^(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)%s+(%-?%d+)")
bbx = { tonumber(a) or 0, tonumber(b) or 0, tonumber(c) or 0, tonumber(d) or 0 }
elseif ck == "BITMAP" then
local w, h = bbx[1], bbx[2]
if w < 0 or h < 0 or w > 4096 or h > 4096 then
return nil, Err.new(Err.CORRUPT, "bad BBX in " .. name)
end
local stride = math.ceil(w / 8)
local rows = buffer.create(stride * h)
for y = 0, h - 1 do
local rl = string.gsub(lines[i] or "", "%s", "")
if string.match(rl, "^ENDCHAR") then
break
end
i += 1
hexRow(rl, w, rows, y * stride)
end
px = Bitmap.unpack(rows, 0, w, h, stride)
elseif ck == "ENDCHAR" then
break
end
end
local gl: Types.BitmapGlyph = {
name = name,
codepoint = nil,
width = bbx[1],
height = bbx[2],
left = bbx[3],
top = bbx[4] + bbx[2],
advance = dw,
pixels = px or buffer.create(math.max(0, bbx[1] * bbx[2])),
}
table.insert(glyphs, gl)
table.insert(encodings, enc)
elseif key == "ENDFONT" then
ended = true
break
end
end
if not ended then
return nil, Err.new(Err.TRUNCATED, "no ENDFONT")
end
local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil
local cset = if type(props.CHARSET_ENCODING) == "string" or type(props.CHARSET_ENCODING) == "number" then tostring(props.CHARSET_ENCODING) else nil
local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1")
local default: number? = nil
for k, gl in glyphs do
local enc = encodings[k]
if unicode and enc >= 0 then
gl.codepoint = enc
end
if type(props.DEFAULT_CHAR) == "number" and enc == props.DEFAULT_CHAR then
default = k - 1
end
end
local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (if fbb[2] > 0 then fbb[2] else size)
local strike: Types.BitmapStrike = {
size = pixelSize,
ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else fbb[2] + fbb[4],
descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else -fbb[4],
glyphs = glyphs,
default = default,
}
local slant = props.SLANT
local weight = props.WEIGHT_NAME
local style = (if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else "")
if slant == "I" or slant == "O" then
style = (if style ~= "" then style .. " " else "") .. "Italic"
end
local info = {
family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else fontName,
style = if style ~= "" then style else "Regular",
fullName = fontName,
}
local font = Bitmap.font(strike, info, {
properties = props,
encodings = encodings,
unicode = unicode,
fontName = fontName,
boundingBox = fbb,
source = { format = "bdf", charset = if registry then registry .. "-" .. tostring(cset) else nil },
})
return font, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function quote(s: string): string
return '"' .. string.gsub(s, '"', '""') .. '"'
end
function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars })
if not strike then
return nil, err
end
local info = if type(font.info) == "table" then font.info else {}
local family = string.gsub(tostring(info.family or "rosetta"), "[%-\n\r\"]", " ")
local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil
local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil
local px = strike.size
-- the font bounding box
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
for _, g in strike.glyphs do
if g.width > 0 and g.height > 0 then
x0 = math.min(x0, g.left)
x1 = math.max(x1, g.left + g.width)
y0 = math.min(y0, g.top - g.height)
y1 = math.max(y1, g.top)
end
end
if x0 == math.huge then
x0, y0, x1, y1 = 0, 0, 0, 0
end
local name = o.name
or string.format("-rosetta-%s-%s-%s-normal--%d-%d-75-75-c-%d-ISO10646-1", family, if bold then "bold" else "medium", if italic then "i" else "r", px, px * 10, (x1 - x0) * 10)
local out = {
"STARTFONT 2.1",
"FONT " .. name,
string.format("SIZE %d 75 75", px),
string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0),
}
-- the default glyph: the strike's default, else glyph 0
local defaultIndex = (strike.default or 0) + 1
local props: { { any } } = {
{ "FAMILY_NAME", quote(family) },
{ "WEIGHT_NAME", quote(if bold then "Bold" else "Medium") },
{ "SLANT", quote(if italic then "I" else "R") },
{ "PIXEL_SIZE", px },
{ "POINT_SIZE", px * 10 },
{ "RESOLUTION_X", 75 },
{ "RESOLUTION_Y", 75 },
{ "CHARSET_REGISTRY", quote("ISO10646") },
{ "CHARSET_ENCODING", quote("1") },
{ "FONT_ASCENT", strike.ascent },
{ "FONT_DESCENT", strike.descent },
}
local dg = strike.glyphs[defaultIndex]
if dg and dg.codepoint then
table.insert(props, { "DEFAULT_CHAR", dg.codepoint })
end
table.insert(out, "STARTPROPERTIES " .. #props)
for _, p in props do
table.insert(out, p[1] .. " " .. tostring(p[2]))
end
table.insert(out, "ENDPROPERTIES")
table.insert(out, "CHARS " .. #strike.glyphs)
for k, g in strike.glyphs do
local gname = g.name or (if g.codepoint then string.format("uni%04X", g.codepoint) else "glyph" .. (k - 1))
table.insert(out, "STARTCHAR " .. string.gsub(gname, "%s", "_"))
table.insert(out, "ENCODING " .. (if g.codepoint then tostring(g.codepoint) else "-1"))
table.insert(out, string.format("SWIDTH %d 0", math.floor(g.advance * 1000 / math.max(1, px) + 0.5)))
table.insert(out, string.format("DWIDTH %d 0", g.advance))
table.insert(out, string.format("BBX %d %d %d %d", g.width, g.height, g.left, g.top - g.height))
table.insert(out, "BITMAP")
local stride = math.ceil(g.width / 8)
local rows = Bitmap.pack(g.pixels, g.width, g.height, stride)
for y = 0, g.height - 1 do
local hex = table.create(stride)
for x = 0, stride - 1 do
hex[x + 1] = string.format("%02X", buffer.readu8(rows, y * stride + x))
end
table.insert(out, table.concat(hex))
end
table.insert(out, "ENDCHAR")
end
table.insert(out, "ENDFONT")
return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil
end
return Bdf
+457
View File
@@ -0,0 +1,457 @@
--!strict
-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one
-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation
-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the
-- descriptor has no nesting that matters, no text content).
--
-- Never throws on bad input: parse functions return nil, message.
local Bytes = require("@rosetta/core/Bytes")
local Parse = {}
export type Char = {
id: number,
x: number,
y: number,
width: number,
height: number,
xoffset: number,
yoffset: number,
xadvance: number,
page: number,
chnl: number,
}
export type Desc = {
info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline
common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl
pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1])
chars: { Char },
kernings: { { number } }, -- { first, second, amount }
}
local LIMIT = 1000000 -- chars / kernings
local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" }
local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" }
local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" }
local function list(s: string?, n: number): { number }
local out = table.create(n, 0)
if s then
local i = 1
for v in string.gmatch(s, "-?%d+") do
if i > n then
break
end
out[i] = tonumber(v) or 0
i += 1
end
end
return out
end
local function new(): Desc
return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} }
end
-- one tag's attributes (already split into key -> string) into the description
local function apply(d: Desc, tag: string, a: { [string]: string }): string?
if tag == "info" then
d.info.face = a.face or ""
d.info.charset = a.charset or ""
for _, k in INFO_NUM do
d.info[k] = tonumber(a[k]) or 0
end
d.info.padding = list(a.padding, 4)
d.info.spacing = list(a.spacing, 2)
elseif tag == "common" then
for _, k in COMMON_NUM do
d.common[k] = tonumber(a[k]) or 0
end
elseif tag == "page" then
local id = tonumber(a.id)
if not id or id < 0 or id > 4096 or id % 1 ~= 0 then
return "bad page id"
end
d.pages[id + 1] = a.file or ""
elseif tag == "char" then
if #d.chars >= LIMIT then
return "too many chars"
end
local c: any = {}
for _, k in CHAR_NUM do
c[k] = tonumber(a[k]) or 0
end
table.insert(d.chars, c)
elseif tag == "kerning" then
if #d.kernings >= LIMIT then
return "too many kerning pairs"
end
table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 })
end
return nil
end
local function fill(d: Desc)
for i = 1, #d.pages do
d.pages[i] = d.pages[i] or ""
end
end
-- ------------------------------------------------------------------------------------------------ text
function Parse.text(s: string): (Desc?, string?)
local d = new()
for line in string.gmatch(s, "[^\r\n]+") do
local tag, rest = string.match(line, "^%s*(%a+)(.*)$")
if tag then
local a: { [string]: string } = {}
-- key=value, key="quoted value"
local i = 1
while i <= #(rest :: string) do
local k, q, e = string.match(rest :: string, '^%s*([%w_]+)="([^"]*)"()', i)
if k then
a[k] = q
i = e
else
local k2, v2, e2 = string.match(rest :: string, "^%s*([%w_]+)=(%S*)()", i)
if not k2 then
break
end
a[k2] = v2
i = e2
end
end
local err = apply(d, tag, a)
if err then
return nil, err
end
end
end
if not d.common.lineHeight then
return nil, "no common line"
end
fill(d)
return d, nil
end
-- ------------------------------------------------------------------------------------------------ XML
local ENTITIES: { [string]: string } = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" }
local function unescape(s: string): string
return (
string.gsub(s, "&(#?x?%w+);", function(e: string): string?
if ENTITIES[e] then
return ENTITIES[e]
end
local n = if string.sub(e, 1, 2) == "#x" then tonumber(string.sub(e, 3), 16) elseif string.sub(e, 1, 1) == "#" then tonumber(string.sub(e, 2)) else nil
if n and n >= 0 and n <= 0x10FFFF then
return utf8.char(n)
end
return nil
end)
)
end
function Parse.xml(s: string): (Desc?, string?)
local d = new()
local seenFont = false
for tag, attrs in string.gmatch(s, "<(%a+)([^>]*)>") do
if tag == "font" then
seenFont = true
end
local a: { [string]: string } = {}
for k, q, v in string.gmatch(attrs :: string, "([%w_]+)%s*=%s*([\"'])(.-)%2") do
a[k] = unescape(v :: string)
local _ = q
end
local err = apply(d, tag, a)
if err then
return nil, err
end
end
if not seenFont or not d.common.lineHeight then
return nil, "not a BMFont XML descriptor"
end
fill(d)
return d, nil
end
-- ------------------------------------------------------------------------------------------------ binary
function Parse.binary(r: Bytes.Reader): (Desc?, string?)
if not r:match("BMF") then
return nil, "bad signature"
end
local version = r:u8()
if version ~= 3 then
return nil, "unsupported binary version " .. version
end
local d = new()
while not r:eof() do
local kind = r:u8()
local size = r:u32le()
if r.err then
return nil, "truncated block header"
end
local b = r:slice(size)
if r.err then
return nil, "block past the end"
end
if kind == 1 then
d.info.size = b:i16le()
local bits = b:u8()
d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0
d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0
d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0
d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0
d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0
d.info.charsetId = b:u8()
d.info.charset = ""
d.info.stretchH = b:u16le()
d.info.aa = b:u8()
d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() }
d.info.spacing = { b:u8(), b:u8() }
d.info.outline = b:u8()
d.info.face = b:cstring()
elseif kind == 2 then
d.common.lineHeight = b:u16le()
d.common.base = b:u16le()
d.common.scaleW = b:u16le()
d.common.scaleH = b:u16le()
d.common.pages = b:u16le()
d.common.packed = if bit32.band(b:u8(), 1) ~= 0 then 1 else 0
d.common.alphaChnl = b:u8()
d.common.redChnl = b:u8()
d.common.greenChnl = b:u8()
d.common.blueChnl = b:u8()
elseif kind == 3 then
while not b:eof() and #d.pages < 4096 do
table.insert(d.pages, b:cstring())
end
elseif kind == 4 then
local n = size // 20
if n > LIMIT then
return nil, "too many chars"
end
for _ = 1, n do
table.insert(d.chars, {
id = b:u32le(),
x = b:u16le(),
y = b:u16le(),
width = b:u16le(),
height = b:u16le(),
xoffset = b:i16le(),
yoffset = b:i16le(),
xadvance = b:i16le(),
page = b:u8(),
chnl = b:u8(),
})
end
elseif kind == 5 then
local n = size // 10
if n > LIMIT then
return nil, "too many kerning pairs"
end
for _ = 1, n do
table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() })
end
end
if b.err then
return nil, "truncated block " .. kind
end
end
if not d.common.lineHeight then
return nil, "no common block"
end
return d, nil
end
-- ------------------------------------------------------------------------------------------------ writers
local function num(v: any): string
return string.format("%d", math.floor(tonumber(v) or 0))
end
local function textLines(d: Desc, quote: (string) -> string): { { any } }
local i, c = d.info, d.common
local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
local lines: { { any } } = {
{
"info",
{
{ "face", quote(i.face or "") },
{ "size", num(i.size) },
{ "bold", num(i.bold) },
{ "italic", num(i.italic) },
{ "charset", quote(i.charset or "") },
{ "unicode", num(i.unicode) },
{ "stretchH", num(i.stretchH or 100) },
{ "smooth", num(i.smooth) },
{ "aa", num(i.aa) },
{ "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") },
{ "spacing", num(sp[1]) .. "," .. num(sp[2]) },
{ "outline", num(i.outline) },
},
},
}
local cf = {}
for _, k in COMMON_NUM do
table.insert(cf, { k, num(c[k]) })
end
table.insert(lines, { "common", cf })
return lines
end
function Parse.writeText(d: Desc): string
local out = {}
local function q(s: string): string
return '"' .. string.gsub(s, '"', "") .. '"'
end
for _, l in textLines(d, q) do
local parts = { l[1] }
for _, kv in l[2] do
table.insert(parts, kv[1] .. "=" .. kv[2])
end
table.insert(out, table.concat(parts, " "))
end
for id, file in d.pages do
table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', ""))))
end
table.insert(out, "chars count=" .. #d.chars)
for _, c in d.chars do
local parts = { "char" }
for _, k in CHAR_NUM do
table.insert(parts, k .. "=" .. num((c :: any)[k]))
end
table.insert(out, table.concat(parts, " "))
end
if #d.kernings > 0 then
table.insert(out, "kernings count=" .. #d.kernings)
for _, k in d.kernings do
table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3])))
end
end
return table.concat(out, "\n") .. "\n"
end
local function esc(s: string): string
return (string.gsub(s, '[&<>"]', { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;" }))
end
function Parse.writeXml(d: Desc): string
local out = { '<?xml version="1.0"?>', "<font>" }
for _, l in textLines(d, function(s: string): string
return s
end) do
local parts = { " <" .. l[1] }
for _, kv in l[2] do
table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"')
end
table.insert(out, table.concat(parts, " ") .. "/>")
end
table.insert(out, " <pages>")
for id, file in d.pages do
table.insert(out, string.format(' <page id="%d" file="%s"/>', id - 1, esc(file)))
end
table.insert(out, " </pages>")
table.insert(out, string.format(' <chars count="%d">', #d.chars))
for _, c in d.chars do
local parts = { " <char" }
for _, k in CHAR_NUM do
table.insert(parts, k .. '="' .. num((c :: any)[k]) .. '"')
end
table.insert(out, table.concat(parts, " ") .. "/>")
end
table.insert(out, " </chars>")
if #d.kernings > 0 then
table.insert(out, string.format(' <kernings count="%d">', #d.kernings))
for _, k in d.kernings do
table.insert(out, string.format(' <kerning first="%s" second="%s" amount="%s"/>', num(k[1]), num(k[2]), num(k[3])))
end
table.insert(out, " </kernings>")
end
table.insert(out, "</font>")
return table.concat(out, "\n") .. "\n"
end
function Parse.writeBinary(d: Desc): buffer
local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10)
w:string("BMF")
w:u8(3)
local i, c = d.info, d.common
local face = i.face or ""
w:u8(1)
w:u32le(14 + #face + 1)
w:u16le((tonumber(i.size) or 0) % 65536)
local bits = 0
if (tonumber(i.smooth) or 0) ~= 0 then
bits += 0x80
end
if (tonumber(i.unicode) or 0) ~= 0 then
bits += 0x40
end
if (tonumber(i.italic) or 0) ~= 0 then
bits += 0x20
end
if (tonumber(i.bold) or 0) ~= 0 then
bits += 0x10
end
if (tonumber(i.fixedHeight) or 0) ~= 0 then
bits += 0x08
end
w:u8(bits)
w:u8(tonumber(i.charsetId) or 0)
w:u16le(tonumber(i.stretchH) or 100)
w:u8(tonumber(i.aa) or 1)
local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
for k = 1, 4 do
w:u8(pad[k] or 0)
end
w:u8(sp[1] or 0)
w:u8(sp[2] or 0)
w:u8(tonumber(i.outline) or 0)
w:cstring(face)
w:u8(2)
w:u32le(15)
for _, k in { "lineHeight", "base", "scaleW", "scaleH", "pages" } do
w:u16le((tonumber(c[k]) or 0) % 65536)
end
w:u8(if (tonumber(c.packed) or 0) ~= 0 then 1 else 0)
for _, k in { "alphaChnl", "redChnl", "greenChnl", "blueChnl" } do
w:u8(tonumber(c[k]) or 0)
end
if #d.pages > 0 then
local len = 0
for _, p in d.pages do
len += #p + 1
end
w:u8(3)
w:u32le(len)
for _, p in d.pages do
w:cstring(p)
end
end
w:u8(4)
w:u32le(#d.chars * 20)
for _, ch in d.chars do
w:u32le(ch.id)
w:u16le(ch.x)
w:u16le(ch.y)
w:u16le(ch.width)
w:u16le(ch.height)
w:u16le(ch.xoffset % 65536)
w:u16le(ch.yoffset % 65536)
w:u16le(ch.xadvance % 65536)
w:u8(ch.page)
w:u8(ch.chnl)
end
if #d.kernings > 0 then
w:u8(5)
w:u32le(#d.kernings * 10)
for _, k in d.kernings do
w:u32le(k[1])
w:u32le(k[2])
w:u16le(k[3] % 65536)
end
end
return w:finish()
end
return Parse
+440
View File
@@ -0,0 +1,440 @@
--!strict
-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and
-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize
-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are
-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the
-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf /
-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation.
-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Parse = require("@rosetta/font/bmfont/Parse")
-- ------------------------------------------------------------------------------------------------ contract
local Bmfont = {
name = "bmfont",
category = "font",
extensions = { "fnt" },
mime = { "application/x-bmfont" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true },
}
export type DecodeOptions = {
pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first)
loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one)
}
export type EncodeOptions = {
variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text"
px: number?, -- fonts without a BMFont description are baked first (see bake)
chars: (string | { number })?,
file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font")
name: string?, -- the destination's file name (set by the api)
files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes
-- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages
encodeImage: ((img: any, format: string) -> (buffer?, any))?,
}
export type BakeOptions = {
px: number?, -- pixels per em (default 32)
chars: (string | { number })?, -- code points to include (default printable ASCII 32..126)
pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096)
padding: number?, -- empty pixels around each glyph (default 1)
file: string?, -- page file name prefix (default "font"): pages are <file>_<n>.png
}
-- ------------------------------------------------------------------------------------------------ sniff
function Bmfont.sniff(r: Bytes.Reader): number
local head = r:peek(64)
if string.sub(head, 1, 4) == "BMF\3" then
return 1
end
if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then
return 0.9
end
if string.find(head, "<font>", 1, true) or (string.find(head, "<?xml", 1, true) and string.find(r:peek(512), "<font>", 1, true)) then
return if string.find(r:peek(512), "<info", 1, true) then 0.9 else 0.3
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- the Font value
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 c = self._chars[g]
return if c then c.xadvance else 0
end
function Face.kern(self: any, a: number, b: number): number
local ca, cb = self._chars[a], self._chars[b]
if not ca or not cb then
return 0
end
return self._kern[ca.id * 2097152 + cb.id] or 0
end
function Face.outline(_self: any, _g: number): { any }?
return nil -- bitmap font
end
-- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil
function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?)
local load = loader or self.meta.pageLoader
if type(load) ~= "function" then
return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))")
end
local pages = {}
for i, file in self.meta.pageFiles do
local ok, img, err = pcall(load, file, i - 1)
if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, if Err.is(err) then err else Err.new(Err.IO, "page " .. file .. ": " .. tostring(if ok then err else img))
end
pages[i] = img
end
self.pages = pages
return true, nil
end
local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8
-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size;
-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available.
function Face.rasterize(self: any, g: number, px: number?): Types.Image?
local c = self._chars[g]
if not c then
return nil
end
if not self.pages and self.meta.pageLoader then
self:loadPages()
end
local page = self.pages and self.pages[c.page + 1]
local img = Types.Image.new(c.width, c.height, "alpha8")
img.meta.left = c.xoffset
img.meta.top = (self.meta.base or 0) - c.yoffset
img.meta.advance = c.xadvance
img.meta.glyph = g
img.meta.scale = if type(px) == "number" and self.unitsPerEm > 0 then px / self.unitsPerEm else 1
if not page then
return nil
end
local pw, ph = page.width, page.height
local bpp = Types.Image.bpp(page.format) or 4
local ch = if page.format == "rgba8" then CHANNEL[c.chnl] or 3 else 0
if page.format == "graya8" then
ch = 1
end
for y = 0, c.height - 1 do
local sy = c.y + y
for x = 0, c.width - 1 do
local sx = c.x + x
if sx >= 0 and sy >= 0 and sx < pw and sy < ph then
buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1)))
end
end
end
return img
end
-- the Font value of a description
local function face(d: Parse.Desc, variant: string): any
local f: any = setmetatable({
kind = "font",
info = {
family = d.info.face,
style = if (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 then "Bold Italic" elseif (d.info.bold or 0) ~= 0 then "Bold" elseif (d.info.italic or 0) ~= 0 then "Italic" else "Regular",
fullName = d.info.face,
},
unitsPerEm = math.abs(d.info.size or 0),
ascent = d.common.base or 0,
descent = (d.common.base or 0) - (d.common.lineHeight or 0),
lineGap = 0,
numGlyphs = #d.chars + 1,
pages = nil,
meta = {
bmfont = d,
variant = variant,
pageFiles = d.pages,
lineHeight = d.common.lineHeight,
base = d.common.base,
source = { format = "bmfont", variant = variant },
},
_chars = {},
_index = {},
_kern = {},
}, Face)
for i, c in d.chars do
f._chars[i] = c
if f._index[c.id] == nil then
f._index[c.id] = i
end
end
for _, k in d.kernings do
f._kern[k[1] * 2097152 + k[2]] = k[3]
end
return f
end
function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local d, err, variant
if r:peek(3) == "BMF" then
d, err = Parse.binary(r:sub(0))
variant = "binary"
else
local s = r:peek(r:size())
if string.find(string.sub(s, 1, 512), "<font", 1, true) then
d, err = Parse.xml(s)
variant = "xml"
else
d, err = Parse.text(s)
variant = "text"
end
end
if not d then
return nil, Err.from(err or "bad descriptor", r.base)
end
local f = face(d, variant)
if opts and type(opts.pages) == "table" then
f.pages = opts.pages
end
if opts and type(opts.loadPage) == "function" then
f.meta.pageLoader = opts.loadPage
end
return f, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function validDesc(d: any): boolean
if type(d) ~= "table" or type(d.info) ~= "table" or type(d.common) ~= "table" or type(d.pages) ~= "table" or type(d.chars) ~= "table" or type(d.kernings) ~= "table" then
return false
end
for _, c in d.chars do
for _, k in { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" } do
local v = c[k]
if type(v) ~= "number" or v % 1 ~= 0 then
return false
end
end
if c.id < 0 or c.x < 0 or c.y < 0 or c.width < 0 or c.height < 0 or c.page < 0 or c.page > 255 or c.chnl < 0 or c.chnl > 255 then
return false
end
end
for _, k in d.kernings do
if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then
return false
end
end
for _, p in d.pages do
if type(p) ~= "string" then
return false
end
end
return true
end
function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(font) ~= "table" or font.kind ~= "font" then
return nil, Err.new(Err.ARG, "expected a Font")
end
local d = type(font.meta) == "table" and font.meta.bmfont or nil
local pages = font.pages
if d == nil then
-- page names: opts.file, else the destination's base name (the api passes opts.name), else "font"
local file = opts and opts.file
if file == nil and opts and type(opts.name) == "string" then
file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$")
if file == "" then
file = nil
end
end
local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file })
if not baked then
return nil, err
end
d = baked.meta.bmfont
pages = baked.pages
end
if not validDesc(d) then
return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont")
end
-- the page images into opts.files, under the names the descriptor gives them
local files = opts and opts.files
local encodeImage = opts and opts.encodeImage
if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then
for i, name in d.pages do
local img = pages[i]
if type(img) == "table" and type(name) == "string" and name ~= "" then
local ext = string.lower(string.match(name, "%.([%w]+)$") or "png")
local bytes, eerr = encodeImage(img, ext)
if not bytes then
return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr))
end
files[name] = bytes
end
end
end
local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text"
if variant == "text" then
return buffer.fromstring(Parse.writeText(d)), nil
elseif variant == "xml" then
return buffer.fromstring(Parse.writeXml(d)), nil
elseif variant == "binary" then
return Parse.writeBinary(d), nil
end
return nil, Err.new(Err.ARG, "variant must be text, xml or binary")
end
-- ------------------------------------------------------------------------------------------------ extras
local function codepoints(chars: any): { number }
local out = {}
if type(chars) == "string" then
for _, c in utf8.codes(chars) do
table.insert(out, c)
end
elseif type(chars) == "table" then
for _, c in chars do
if type(c) == "number" then
table.insert(out, c)
end
end
else
for c = 32, 126 do
table.insert(out, c)
end
end
return out
end
-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are
-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are
-- kept (rounded to pixels).
function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?)
if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then
return nil, Err.new(Err.ARG, "bake: expected an outline Font")
end
local o: BakeOptions = opts or {}
local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32
local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1
local scale = px / font.unitsPerEm
local glyphs: { { cp: number, g: number, img: Types.Image } } = {}
local area = 0
local seen = {}
for _, cp in codepoints(o.chars) do
local g = (font :: any):glyphIndex(cp)
if (g ~= 0 or cp == 0) and not seen[cp] then
seen[cp] = true
local img: Types.Image? = (font :: any):rasterize(g, px)
if img then
table.insert(glyphs, { cp = cp, g = g, img = img })
area += (img.width + pad) * (img.height + pad)
end
end
end
local size: number
if type(o.pageSize) == "number" then
size = o.pageSize
else
size = 64
while size * size < area * 1.3 and size < 4096 do
size *= 2
end
end
local order = table.clone(glyphs)
table.sort(order, function(a: any, b: any): boolean
if a.img.height ~= b.img.height then
return a.img.height > b.img.height
end
return a.cp < b.cp
end)
local ascent = math.ceil(font.ascent * scale)
local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale)
local prefix = o.file or "font"
local d: Parse.Desc = {
info = {
face = font.info and font.info.family or "font",
size = px,
bold = 0,
italic = 0,
charset = "",
unicode = 1,
stretchH = 100,
smooth = 1,
aa = 1,
padding = { 0, 0, 0, 0 },
spacing = { pad, pad },
outline = 0,
},
common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 },
pages = {},
chars = {},
kernings = {},
}
local pages: { Types.Image } = {}
local page: Types.Image? = nil
local x, y, rowH = pad, pad, 0
local placed: { [number]: Parse.Char } = {}
for _, gl in order do
local w, h = gl.img.width, gl.img.height
if w + 2 * pad > size or h + 2 * pad > size then
return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page")
end
if x + w + pad > size then
x, y, rowH = pad, y + rowH + pad, 0
end
if not page or y + h + pad > size then
page = Types.Image.new(size, size)
table.insert(pages, page :: Types.Image)
table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1))
x, y, rowH = pad, pad, 0
end
local pg = page :: Types.Image
for yy = 0, h - 1 do
for xx = 0, w - 1 do
local a = buffer.readu8(gl.img.pixels, yy * w + xx)
buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216)
end
end
local c: Parse.Char = {
id = gl.cp,
x = x,
y = y,
width = w,
height = h,
xoffset = gl.img.meta.left,
yoffset = ascent - gl.img.meta.top,
xadvance = math.floor(gl.img.meta.advance + 0.5),
page = #pages - 1,
chnl = 15,
}
placed[gl.cp] = c
x += w + pad
rowH = math.max(rowH, h)
end
for _, gl in glyphs do
table.insert(d.chars, placed[gl.cp])
end
d.common.pages = #pages
if type(font.kern) == "function" then
for _, a in glyphs do
for _, b in glyphs do
local k = font:kern(a.g, b.g)
if k ~= 0 then
local v = math.floor(k * scale + 0.5)
if v ~= 0 then
table.insert(d.kernings, { a.cp, b.cp, v })
end
end
end
end
end
local f = face(d, "text")
f.pages = pages
return f, nil
end
return Bmfont
+233
View File
@@ -0,0 +1,233 @@
--!strict
-- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset,
-- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and
-- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot
-- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string,
-- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C
-- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Text = require("@rosetta/codecs/text/Text")
local TrueType = require("@rosetta/codecs/font/TrueType")
-- ------------------------------------------------------------------------------------------------ contract
local Eot = {
name = "eot",
category = "font",
extensions = { "eot" },
mime = { "application/vnd.ms-fontobject" },
deps = { "core/Err", "core/Bytes", "codecs/text/Text", "codecs/font/TrueType" },
caps = { decode = true, encode = true, variants = { "1.0", "2.1", "2.2" } },
}
export type DecodeOptions = {}
export type EncodeOptions = {
xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false)
rootString: string?, -- the URLs allowed to use the font (default "")
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = 0x504C
local COMPRESSED, XOR = 0x4, 0x10000000
-- ------------------------------------------------------------------------------------------------ sniff
function Eot.sniff(r: Bytes.Reader): number
local h = r:peek(36)
if #h < 36 then
return 0
end
local ver = string.sub(h, 9, 12)
local magic = string.byte(h, 35) + string.byte(h, 36) * 256
if magic == MAGIC and (ver == "\0\0\1\0" or ver == "\1\0\2\0" or ver == "\2\0\2\0") then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Eot.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local eotSize, dataSize, version, flags = r:u32le(), r:u32le(), r:u32le(), r:u32le()
local panose = r:string(10)
local charset, italic = r:u8(), r:u8()
local weight = r:u32le()
local fsType, magic = r:u16le(), r:u16le()
local ranges = { r:u32le(), r:u32le(), r:u32le(), r:u32le() }
local codepages = { r:u32le(), r:u32le() }
local checksum = r:u32le()
r:skip(16)
if r.err then
return nil, r.err
end
if magic ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad magic number")
end
if version ~= 0x00010000 and version ~= 0x00020001 and version ~= 0x00020002 then
return nil, Err.new(Err.UNSUPPORTED, string.format("version 0x%08x", version))
end
local function name(): string
r:skip(2)
local n = r:u16le()
local s = r:bytes(n)
return Text.utf16(s, 0, buffer.len(s))
end
local eot: { [string]: any } = {
version = version,
flags = flags,
panose = panose,
charset = charset,
italic = italic ~= 0,
weight = weight,
fsType = fsType,
unicodeRange = ranges,
codePageRange = codepages,
checkSumAdjustment = checksum,
eotSize = eotSize,
}
eot.familyName, eot.styleName, eot.versionName, eot.fullName = name(), name(), name(), name()
if version >= 0x00020001 then
eot.rootString = name()
end
if version == 0x00020002 then
eot.rootStringChecksum = r:u32le()
eot.eudcCodePage = r:u32le()
r:skip(2)
r:skip(r:u16le()) -- signature
eot.eudcFlags = r:u32le()
r:skip(r:u32le()) -- EUDC font data
end
if r.err then
return nil, r.err
end
if bit32.band(flags, COMPRESSED) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "MicroType Express compressed font data")
end
local data = r:bytes(dataSize)
if r.err then
return nil, r.err
end
if bit32.band(flags, XOR) ~= 0 then
for i = 0, dataSize - 1 do
buffer.writeu8(data, i, bit32.bxor(buffer.readu8(data, i), 0x50))
end
end
local font, ferr = TrueType.font(data)
if not font then
return nil, ferr
end
font.meta.eot = eot
font.meta.fontData = data
font.meta.source = { format = "eot", version = version, outlines = font.meta.outlines }
return font, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function utf16(s: string): string
local out = {}
if utf8.len(s) then
for _, c in utf8.codes(s) do
if c >= 0x10000 then
c -= 0x10000
local hi, lo = 0xD800 + bit32.rshift(c, 10), 0xDC00 + bit32.band(c, 0x3FF)
table.insert(out, string.char(hi % 256, hi // 256, lo % 256, lo // 256))
else
table.insert(out, string.char(c % 256, c // 256))
end
end
end
return table.concat(out)
end
function Eot.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local data: buffer
if type(value) == "buffer" then
data = value
elseif type(value) == "string" then
data = buffer.fromstring(value)
elseif type(value) == "table" and type(value.meta) == "table" and type(value.meta.fontData) == "buffer" then
data = value.meta.fontData
else
return nil, Err.new(Err.ARG, "expected TrueType bytes (or a Font read from an EOT)")
end
local font, ferr = TrueType.font(data)
if not font then
return nil, ferr
end
local tables: { [string]: { number } } = TrueType.tables(data, 0, 0, buffer.len(data)) or {}
local function tab(tagName: string): Bytes.Reader?
local t: { number }? = tables[tagName]
return if t then Bytes.reader(data, t[1], t[2]) else nil
end
-- OS/2: PANOSE, weight, fsType, ranges, selection; head: checkSumAdjustment
local panose, weight, fsType, italic, charset = string.rep("\0", 10), 400, 0, 0, 1
local ranges, codepages = { 0, 0, 0, 0 }, { 0, 0 }
local os2 = tab("OS/2")
if os2 then
os2:seek(4)
weight = os2:u16be()
os2:seek(8)
fsType = os2:u16be()
os2:seek(32)
panose = os2:string(10)
ranges = { os2:u32be(), os2:u32be(), os2:u32be(), os2:u32be() }
os2:seek(62)
local sel = os2:u16be()
italic = if bit32.band(sel, 1) ~= 0 then 1 else 0
os2:seek(78)
codepages = { os2:u32be(), os2:u32be() }
if os2.err then
codepages = { 0, 0 }
end
end
local head = tab("head")
local checksum = 0
if head then
head:seek(8)
checksum = head:u32be()
end
local info = font.info or {}
local names = { info.family or "", info.style or "", info.version or "", info.fullName or "" }
local w = Bytes.writer(buffer.len(data) + 512)
w:u32le(0) -- EOTSize, patched
w:u32le(buffer.len(data))
w:u32le(0x00020001)
w:u32le(if o.xor then XOR else 0)
w:string(panose)
w:u8(charset)
w:u8(italic)
w:u32le(weight)
w:u16le(fsType)
w:u16le(MAGIC)
for _, v in ranges do
w:u32le(v)
end
for _, v in codepages do
w:u32le(v)
end
w:u32le(checksum)
w:string(string.rep("\0", 16))
for _, s in names do
local u = utf16(tostring(s))
w:u16le(0)
w:u16le(#u)
w:string(u)
end
local root = utf16(o.rootString or "")
w:u16le(0)
w:u16le(#root)
w:string(root)
local start = w:tell()
w:bytes(data)
local out = w:finish()
if o.xor then
for i = start, start + buffer.len(data) - 1 do
buffer.writeu8(out, i, bit32.bxor(buffer.readu8(out, i), 0x50))
end
end
buffer.writeu32(out, 0, buffer.len(out))
return out, nil
end
return Eot
+288
View File
@@ -0,0 +1,288 @@
--!strict
-- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the
-- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE
-- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first
-- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI
-- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset).
-- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts.
-- Not supported: vector FNT (Err.UNSUPPORTED), writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Text = require("@rosetta/codecs/text/Text")
local Bitmap = require("@rosetta/codecs/font/Bitmap")
-- ------------------------------------------------------------------------------------------------ contract
local Fon = {
name = "fon",
category = "font",
extensions = { "fon", "fnt" },
mime = { "application/x-font-fnt" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text", "codecs/font/Bitmap" },
caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } },
}
export type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first)
-- ------------------------------------------------------------------------------------------------ sniff
local function isFnt(h: string): boolean
if #h < 4 then
return false
end
local ver = string.byte(h, 1) + string.byte(h, 2) * 256
return ver == 0x200 or ver == 0x300
end
function Fon.sniff(r: Bytes.Reader): number
local h = r:peek(64)
if string.sub(h, 1, 2) == "MZ" and #h >= 64 then
local lfanew = string.byte(h, 61) + string.byte(h, 62) * 256 + string.byte(h, 63) * 65536
local sig = r:peek(2, lfanew)
return if sig == "NE" then 0.6 elseif sig == "PE" then 0.2 else 0
end
if isFnt(h) and #h >= 6 then
local size = string.byte(h, 3) + string.byte(h, 4) * 256 + string.byte(h, 5) * 65536 + string.byte(h, 6) * 16777216
return if size == r:size() then 0.9 elseif size <= r:size() and size > 118 then 0.3 else 0
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- one FNT resource -> Font
local function fnt(r: Bytes.Reader): (any, Err.Err?)
local version = r:u16le()
local total = r:u32le()
local copyright = string.match(r:string(60), "^[^%z]*") or ""
local ftype = r:u16le()
local points, vres, hres = r:u16le(), r:u16le(), r:u16le()
local ascent = r:u16le()
r:skip(4) -- internal / external leading
local italic = r:u8()
r:skip(2)
local weight = r:u16le()
local charset = r:u8()
local pixWidth, pixHeight = r:u16le(), r:u16le()
r:skip(5) -- pitch and family, average / max width
local first, last, default = r:u8(), r:u8(), r:u8()
r:skip(1 + 2 + 4)
local faceAt = r:u32le()
if r.err then
return nil, r.err
end
if version ~= 0x200 and version ~= 0x300 then
return nil, Err.new(Err.CORRUPT, "not a FNT resource")
end
if bit32.band(ftype, 1) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "vector fonts")
end
if last < first or pixHeight == 0 or pixHeight > 1024 then
return nil, Err.new(Err.CORRUPT, "bad character range or height")
end
r:seek(if version == 0x300 then 148 else 118)
local glyphs: { Types.BitmapGlyph } = {}
for c = first, last do
local w = r:u16le()
local off = if version == 0x300 then r:u32le() else r:u16le()
if r.err then
return nil, r.err
end
if w > 4096 then
return nil, Err.new(Err.CORRUPT, "bad glyph width")
end
-- column-major: byte column k holds pixels 8k .. 8k + 7 of every row
local h = pixHeight
local px = buffer.create(w * h)
local cols = math.ceil(w / 8)
local base = r.base + off
local limit = r.base + r:size()
for k = 0, cols - 1 do
for y = 0, h - 1 do
local p = base + k * h + y
if p >= 0 and p < limit then
local byte = buffer.readu8(r.buf, p)
for b = 0, 7 do
local x = k * 8 + b
if x < w and bit32.band(byte, bit32.rshift(0x80, b)) ~= 0 then
buffer.writeu8(px, y * w + x, 255)
end
end
end
end
end
local cp: number? = nil
if charset == 0 then
cp = if c >= 0x80 and c < 0xA0 then Text.CP1252[c] else c
elseif c < 0x80 then
cp = c
end
table.insert(glyphs, { codepoint = cp, width = w, height = h, left = 0, top = ascent, advance = w, pixels = px })
end
local face = ""
if faceAt > 0 and faceAt < r:size() then
face = r:sub(faceAt):cstring(256)
end
local dflt = default + first
local strike: Types.BitmapStrike = {
size = pixHeight,
ascent = ascent,
descent = pixHeight - ascent,
glyphs = glyphs,
default = if dflt >= first and dflt <= last then dflt - first else nil,
}
local style = (if weight >= 600 then "Bold" else "") .. (if italic ~= 0 then " Italic" else "")
style = string.gsub(style, "^ ", "")
return Bitmap.font(strike, { family = face, style = if style ~= "" then style else "Regular", fullName = face }, {
copyright = copyright,
points = points,
resolution = { hres, vres },
charset = charset,
weight = weight,
pixWidth = pixWidth,
firstChar = first,
source = { format = "fon", version = if version == 0x300 then 3 else 2, size = total },
}), nil
end
-- the RT_FONT resources of an NE executable: { { offset, length } }
local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?)
local rt = r:sub(ne + 0x24, 2):u16le()
local t = r:sub(ne + rt)
local shift = t:u16le()
if shift > 16 then
return nil, "bad resource alignment"
end
local out = {}
for _ = 1, 64 do
local typeId = t:u16le()
if typeId == 0 or t.err then
break
end
local count = t:u16le()
t:skip(4)
for _ = 1, count do
local off, len = t:u16le(), t:u16le()
t:skip(8)
if typeId == 0x8008 then
table.insert(out, { off * 2 ^ shift, len * 2 ^ shift })
end
end
end
if t.err then
return nil, "truncated resource table"
end
return out, nil
end
-- the RT_FONT (8) resources of a PE executable: { { offset, length } }
local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?)
local h = r:sub(pe + 4, 20)
h:skip(2)
local nsec = h:u16le()
h:skip(12)
local optSize = h:u16le()
local opt = r:sub(pe + 24, optSize)
local magic = opt:u16le()
local ddAt = if magic == 0x20B then 112 else 96
opt:seek(ddAt + 2 * 8)
local rsrcRva = opt:u32le()
if opt.err or rsrcRva == 0 then
return {}, nil
end
-- the section holding the resources
local secs = r:sub(pe + 24 + optSize, nsec * 40)
local base, rva0 = -1, 0
for _ = 1, nsec do
secs:skip(8)
local vsize, va, rawSize, rawAt = secs:u32le(), secs:u32le(), secs:u32le(), secs:u32le()
secs:skip(16)
if rsrcRva >= va and rsrcRva < va + math.max(vsize, rawSize) then
base, rva0 = rawAt + (rsrcRva - va), va - rawAt
end
end
if base < 0 then
return nil, "no resource section"
end
local out = {}
local function dir(at: number, depth: number, isFont: boolean)
if depth > 3 then
return
end
local d = r:sub(base + at, 16)
d:skip(12)
local named, ids = d:u16le(), d:u16le()
local e = r:sub(base + at + 16, (named + ids) * 8)
for _ = 1, math.min(named + ids, 512) do
local id, target = e:u32le(), e:u32le()
if e.err then
return
end
if depth == 0 and id ~= 8 then
continue
end
if bit32.band(target, 0x80000000) ~= 0 then
dir(bit32.band(target, 0x7FFFFFFF), depth + 1, isFont or depth == 0)
elseif isFont then
local leaf = r:sub(base + target, 8)
local dataRva, size = leaf:u32le(), leaf:u32le()
table.insert(out, { dataRva - rva0, size })
end
end
end
dir(0, 0, false)
return out, nil
end
function Fon.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local list: { { number } }
if r:peek(2) == "MZ" then
local lfanew = r:sub(0x3C, 4):u32le()
local sig = r:peek(2, lfanew)
local l, err
if sig == "NE" then
l, err = neFonts(r, lfanew)
elseif sig == "PE" then
l, err = peFonts(r, lfanew)
else
return nil, Err.new(Err.CORRUPT, "an MZ file without an NE / PE header")
end
if not l then
return nil, Err.from(err)
end
list = l
else
if r:size() < 118 then
return nil, Err.new(Err.TRUNCATED, "shorter than a FNT header")
end
list = { { 0, r:size() } }
end
local fonts: { any } = {}
local firstErr: Err.Err? = nil
for _, res in list do
if res[1] + 118 <= r:size() then
local f, err = fnt(r:sub(res[1], res[2]))
if f then
table.insert(fonts, f)
else
firstErr = firstErr or err
end
end
end
if #fonts == 0 then
return nil, firstErr or Err.new(Err.CORRUPT, "no font resources")
end
local pick = fonts[1]
if type(o.size) == "number" then
for _, f in fonts do
if math.abs(f.unitsPerEm - o.size) < math.abs(pick.unitsPerEm - o.size) then
pick = f
end
end
end
pick.meta.strikes = fonts
return pick, nil
end
return Fon
+200
View File
@@ -0,0 +1,200 @@
--!strict
-- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph
-- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R",
-- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths
-- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster
-- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of
-- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i
-- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph
-- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported:
-- writing, the Hershey "occidental" index files (.hmp), filled rendering.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Raster = require("@rosetta/codecs/image/Raster")
-- ------------------------------------------------------------------------------------------------ contract
local Hershey = {
name = "hershey",
category = "font",
extensions = { "jhf" },
mime = { "application/x-hershey-font" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster" },
caps = { decode = true, encode = false, strokes = true },
}
export type DecodeOptions = {
map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii")
strokeWidth: number?, -- stroke width in font units for rasterize (default 2)
maxGlyphs: number?, -- default 65536
}
-- ------------------------------------------------------------------------------------------------ constants
local BASELINE = 9 -- the Hershey y of the Roman fonts' baseline (y grows downwards)
-- ------------------------------------------------------------------------------------------------ sniff
-- the first record: 5-digit id, 3-digit count, then coordinate characters in " " .. "~" (the pen-up pair " R")
local function header(line: string): (number?, number?)
if #line < 10 then
return nil, nil
end
local id = tonumber((string.gsub(string.sub(line, 1, 5), "^%s+", "")))
local n = tonumber((string.gsub(string.sub(line, 6, 8), "^%s+", "")))
if not id or not n or n < 1 or string.find(string.sub(line, 1, 8), "[^%d ]") then
return nil, nil
end
return id, n
end
function Hershey.sniff(r: Bytes.Reader): number
local head = r:peek(256)
local line = string.match(head, "^([^\r\n]*)")
local id, n = header(line or "")
if not id or not n then
return 0
end
local body = string.sub(line :: string, 9)
if string.find(body, "[^ -~]") then
return 0
end
return if #body == math.min(2 * n, 64) or #body == 2 * n then 0.7 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
type Glyph = { id: number, left: number, right: number, cmds: { any } }
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._glyphs[g + 1]
return if gl then gl.right - gl.left else 0
end
function Face.kern(_self: any, _a: number, _b: number): number
return 0
end
function Face.outline(self: any, g: number): { any }?
local gl = self._glyphs[g + 1]
if not gl then
return nil
end
local out = table.create(#gl.cmds)
for i, c in gl.cmds do
out[i] = table.clone(c)
end
return out
end
-- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels)
function Face.rasterize(self: any, g: number, px: number): Types.Image?
local gl = self._glyphs[g + 1]
if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then
return nil
end
local s = px / self.unitsPerEm
local stroke = Raster.stroke(gl.cmds, { width = self.meta.strokeWidth, join = "round", cap = "round" })
local m = Raster.mask(stroke, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 })
local img
if m then
img = Types.Image.new(m.width, m.height, "alpha8")
buffer.copy(img.pixels, 0, m.coverage)
img.meta.left = m.x
img.meta.top = -m.y
else
img = Types.Image.new(0, 0, "alpha8")
img.meta.left, img.meta.top = 0, 0
end
img.meta.advance = (gl.right - gl.left) * s
img.meta.glyph = g
return img
end
function Hershey.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 65536
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local lines = string.split((string.gsub(text, "\r", "")), "\n")
local glyphs: { Glyph } = {}
local i = 1
while i <= #lines do
local line = lines[i]
i += 1
if string.match(line, "^%s*$") then
continue
end
local id, n = header(line)
if not id or not n then
return nil, Err.new(Err.CORRUPT, "bad record header on line " .. (i - 1))
end
local data = string.sub(line, 9)
while #data < 2 * n and i <= #lines do
data ..= lines[i]
i += 1
end
if #data < 2 * n then
return nil, Err.new(Err.TRUNCATED, "glyph " .. id .. " has fewer vertices than its count")
end
if #glyphs >= maxGlyphs then
return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
end
local left = string.byte(data, 1) - 82
local right = string.byte(data, 2) - 82
local cmds: { any } = {}
local pen = false
for k = 1, n - 1 do
local a, b = string.byte(data, 2 * k + 1), string.byte(data, 2 * k + 2)
if a == 32 and b == 82 then
pen = false
else
local x, y = a - 82 - left, BASELINE - (b - 82)
local cmd: any = { op = if pen then "lineTo" else "moveTo" }
cmd[1], cmd[2] = x, y
table.insert(cmds, cmd)
pen = true
end
end
table.insert(glyphs, { id = id, left = left, right = right, cmds = cmds })
end
if #glyphs == 0 then
return nil, Err.new(Err.CORRUPT, "no glyphs")
end
local index: { [number]: number } = {}
local byId = o.map == "id"
for k, g in glyphs do
local cp = if byId then g.id else 31 + k
if index[cp] == nil then
index[cp] = k - 1
end
end
local font = setmetatable({
kind = "font",
info = { family = "Hershey", style = "Regular" },
unitsPerEm = 32,
ascent = 21,
descent = -7,
lineGap = 4,
numGlyphs = #glyphs,
meta = {
strokes = true,
strokeWidth = o.strokeWidth or 2,
ids = table.create(#glyphs, 0),
source = { format = "hershey", map = if byId then "id" else "ascii" },
},
_glyphs = glyphs,
_index = index,
}, Face)
for k, g in glyphs do
font.meta.ids[k] = g.id
end
return font, nil
end
return Hershey
+290
View File
@@ -0,0 +1,290 @@
--!strict
-- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the
-- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties),
-- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad
-- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES.
-- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets
-- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver
-- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Bitmap = require("@rosetta/codecs/font/Bitmap")
-- ------------------------------------------------------------------------------------------------ contract
local Pcf = {
name = "pcf",
category = "font",
extensions = { "pcf" },
mime = { "application/x-font-pcf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
caps = { decode = true, encode = false, bitmap = true },
}
export type DecodeOptions = { maxGlyphs: number? } -- default 1114112
-- ------------------------------------------------------------------------------------------------ constants
local PROPERTIES, ACCELERATORS, METRICS, BITMAPS = 1, 2, 4, 8
local BDF_ENCODINGS, SWIDTHS, GLYPH_NAMES, BDF_ACCELERATORS = 32, 64, 128, 256
local COMPRESSED = 0x100
-- ------------------------------------------------------------------------------------------------ sniff
function Pcf.sniff(r: Bytes.Reader): number
return if r:peek(4) == "\1fcp" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Table = { format: number, size: number, offset: number }
-- a reader positioned after a table's format word, with the integer readers for its byte order
type TR = { r: Bytes.Reader, format: number, big: boolean }
local function open(r: Bytes.Reader, t: Table?): TR?
if not t or t.offset + 4 > r:size() then
return nil
end
local s = r:sub(t.offset, t.size)
local format = s:u32le()
return { r = s, format = format, big = bit32.band(format, 4) ~= 0 }
end
local function u32(t: TR): number
return if t.big then t.r:u32be() else t.r:u32le()
end
local function i32(t: TR): number
return if t.big then t.r:i32be() else t.r:i32le()
end
local function i16(t: TR): number
return if t.big then t.r:i16be() else t.r:i16le()
end
local function u16(t: TR): number
return if t.big then t.r:u16be() else t.r:u16le()
end
local REV = buffer.create(256)
for i = 0, 255 do
local v, rv = i, 0
for _ = 1, 8 do
rv = rv * 2 + v % 2
v //= 2
end
buffer.writeu8(REV, i, rv)
end
function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 1114112
if r:string(4) ~= "\1fcp" then
return nil, Err.new(if r.err then Err.TRUNCATED else Err.CORRUPT, "not a PCF file")
end
local count = r:u32le()
if count > 64 then
return nil, Err.new(Err.CORRUPT, "too many tables")
end
local tables: { [number]: Table } = {}
for _ = 1, count do
local ty, format, size, offset = r:u32le(), r:u32le(), r:u32le(), r:u32le()
tables[ty] = { format = format, size = size, offset = offset }
end
if r.err then
return nil, r.err
end
-- properties
local props: { [string]: any } = {}
local pt = open(r, tables[PROPERTIES])
if pt then
local n = i32(pt)
if n < 0 or n > 4096 then
return nil, Err.new(Err.CORRUPT, "bad property count")
end
local raw = {}
for k = 1, n do
raw[k] = { i32(pt), pt.r:u8(), i32(pt) }
end
if n % 4 ~= 0 then
pt.r:skip(4 - n % 4)
end
local strSize = i32(pt)
local strAt = pt.r:tell()
local function str(off: number): string
if off < 0 or off >= strSize then
return ""
end
local s = pt.r:sub(strAt + off, strSize - off)
return s:cstring()
end
for _, p in raw do
props[str(p[1])] = if p[2] ~= 0 then str(p[3]) else p[3]
end
if pt.r.err then
return nil, Err.new(Err.TRUNCATED, "properties table")
end
end
-- accelerators: ascent / descent
local ascent: number?, descent: number? = nil, nil
local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS])
if at then
at.r:skip(8)
ascent, descent = i32(at), i32(at)
end
-- metrics
local mt = open(r, tables[METRICS])
if not mt then
return nil, Err.new(Err.CORRUPT, "no METRICS table")
end
local metrics = {}
local compressed = bit32.band(mt.format, COMPRESSED) ~= 0
local nm = if compressed then u16(mt) else u32(mt)
if nm > maxGlyphs then
return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
end
for k = 1, nm do
if compressed then
local b = mt.r
metrics[k] = { b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80, b:u8() - 0x80 }
else
metrics[k] = { i16(mt), i16(mt), i16(mt), i16(mt), i16(mt) }
mt.r:skip(2)
end
end
if mt.r.err then
return nil, Err.new(Err.TRUNCATED, "metrics table")
end
-- bitmaps
local bt = open(r, tables[BITMAPS])
if not bt then
return nil, Err.new(Err.CORRUPT, "no BITMAPS table")
end
local nb = u32(bt)
if nb ~= nm then
return nil, Err.new(Err.CORRUPT, "bitmap count differs from metrics count")
end
local offsets = table.create(nb, 0)
for k = 1, nb do
offsets[k] = u32(bt)
end
local sizes = { u32(bt), u32(bt), u32(bt), u32(bt) }
local padIndex = bit32.band(bt.format, 3)
local pad = bit32.lshift(1, padIndex)
local unit = bit32.lshift(1, bit32.band(bit32.rshift(bt.format, 4), 3))
local msbBit = bit32.band(bt.format, 8) ~= 0
local dataAt = bt.r:tell()
local dataSize = sizes[padIndex + 1]
if bt.r.err or dataAt + dataSize > bt.r:size() then
return nil, Err.new(Err.TRUNCATED, "bitmaps table")
end
-- the bitmap data normalised to MSB-first bits and bytes
local bits = bt.r:sub(dataAt, dataSize):bytes(dataSize)
if not msbBit then
for k = 0, dataSize - 1 do
buffer.writeu8(bits, k, buffer.readu8(REV, buffer.readu8(bits, k)))
end
end
if bt.big ~= msbBit and unit > 1 then
for k = 0, dataSize - unit, unit do
for j = 0, unit // 2 - 1 do
local x, y = buffer.readu8(bits, k + j), buffer.readu8(bits, k + unit - 1 - j)
buffer.writeu8(bits, k + j, y)
buffer.writeu8(bits, k + unit - 1 - j, x)
end
end
end
local glyphs: { Types.BitmapGlyph } = {}
for k = 1, nm do
local m = metrics[k]
local w, h = m[2] - m[1], m[4] + m[5]
if w < 0 or h < 0 or w > 4096 or h > 4096 then
return nil, Err.new(Err.CORRUPT, "bad glyph metrics")
end
local stride = math.ceil(w / (pad * 8)) * pad
local px = Bitmap.unpack(bits, offsets[k], w, h, stride)
glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px }
end
-- encodings
local encodings: { [number]: number } = {}
local default: number? = nil
local et = open(r, tables[BDF_ENCODINGS])
if et then
local min2, max2, min1, max1, def = i16(et), i16(et), i16(et), i16(et), i16(et)
if min2 < 0 or max2 > 255 or min1 < 0 or max1 > 255 or max2 < min2 or max1 < min1 then
return nil, Err.new(Err.CORRUPT, "bad encoding ranges")
end
for b1 = min1, max1 do
for b2 = min2, max2 do
local g = u16(et)
if g ~= 0xFFFF and g < nm and encodings[g + 1] == nil then
encodings[g + 1] = b1 * 256 + b2
end
end
end
if et.r.err then
return nil, Err.new(Err.TRUNCATED, "encodings table")
end
local dcols = max2 - min2 + 1
local d1, d2 = def // 256, def % 256
if d1 >= min1 and d1 <= max1 and d2 >= min2 and d2 <= max2 then
local slot = (d1 - min1) * dcols + (d2 - min2)
local dr = r:sub(tables[BDF_ENCODINGS].offset + 14 + slot * 2, 2)
local g = if et.big then dr:u16be() else dr:u16le()
if g ~= 0xFFFF and g < nm then
default = g
end
end
end
-- glyph names
local nt = open(r, tables[GLYPH_NAMES])
if nt then
local n = u32(nt)
if n == nm then
local offs = table.create(n, 0)
for k = 1, n do
offs[k] = u32(nt)
end
local strSize = u32(nt)
local strAt = nt.r:tell()
for k = 1, n do
if offs[k] < strSize then
glyphs[k].name = nt.r:sub(strAt + offs[k], strSize - offs[k]):cstring()
end
end
end
end
local registry = if type(props.CHARSET_REGISTRY) == "string" then string.upper(props.CHARSET_REGISTRY) else nil
local cset = if props.CHARSET_ENCODING ~= nil then tostring(props.CHARSET_ENCODING) else nil
local unicode = registry == nil or registry == "ISO10646" or (registry == "ISO8859" and cset == "1")
local encList = table.create(nm, -1)
for k = 1, nm do
local enc = encodings[k]
encList[k] = enc or -1
if unicode and enc then
glyphs[k].codepoint = enc
end
end
local pixelSize = if type(props.PIXEL_SIZE) == "number" then props.PIXEL_SIZE else (ascent or 0) + (descent or 0)
local strike: Types.BitmapStrike = {
size = pixelSize,
ascent = if type(props.FONT_ASCENT) == "number" then props.FONT_ASCENT else ascent or 0,
descent = if type(props.FONT_DESCENT) == "number" then props.FONT_DESCENT else descent or 0,
glyphs = glyphs,
default = default,
}
local weight = props.WEIGHT_NAME
local style = if type(weight) == "string" and string.lower(weight) ~= "medium" and string.lower(weight) ~= "regular" then weight else ""
if props.SLANT == "I" or props.SLANT == "O" then
style = (if style ~= "" then style .. " " else "") .. "Italic"
end
return Bitmap.font(strike, {
family = if type(props.FAMILY_NAME) == "string" then props.FAMILY_NAME else nil,
style = if style ~= "" then style else "Regular",
fullName = if type(props.FONT) == "string" then props.FONT else nil,
}, {
properties = props,
encodings = encList,
unicode = unicode,
source = { format = "pcf", pad = pad, unit = unit, msbBit = msbBit, msbByte = bt.big, charset = if registry then registry .. "-" .. tostring(cset) else nil },
}), nil
end
return Pcf
+328
View File
@@ -0,0 +1,328 @@
--!strict
-- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2
-- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and
-- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry
-- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map
-- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell
-- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing:
-- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through
-- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps
-- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd
-- project's psf documentation (Andries Brouwer).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Bitmap = require("@rosetta/codecs/font/Bitmap")
-- ------------------------------------------------------------------------------------------------ contract
local Psf = {
name = "psf",
category = "font",
extensions = { "psf", "psfu" },
mime = { "application/x-font-linux-psf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/font/Bitmap" },
caps = { decode = true, encode = true, bitmap = true, variants = { "psf1", "psf2" } },
}
export type DecodeOptions = { maxGlyphs: number? } -- default 65536
export type EncodeOptions = {
version: number?, -- 1 or 2 (default 2)
px: number?, -- pixel size for outline fonts (default 16)
chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
unicode: boolean?, -- write the Unicode table (default true)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Psf.sniff(r: Bytes.Reader): number
local h = r:peek(4)
if h == "\114\181\74\134" then
return 1
end
if string.sub(h, 1, 2) == "\54\4" and #h >= 4 and string.byte(h, 3) <= 7 and string.byte(h, 4) > 0 then
return 0.9
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 65536
local version, count, width, height, stride, glyphAt, hasTable
if r:peek(4) == "\114\181\74\134" then
r:skip(4)
local ver, hsize, flags = r:u32le(), r:u32le(), r:u32le()
count = r:u32le()
local charsize = r:u32le()
height, width = r:u32le(), r:u32le()
if r.err then
return nil, r.err
end
if ver ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "PSF 2 version " .. ver)
end
stride = math.ceil(width / 8)
if width < 1 or height < 1 or width > 4096 or height > 4096 or charsize ~= stride * height then
return nil, Err.new(Err.CORRUPT, "bad glyph size")
end
version, glyphAt, hasTable = 2, hsize, bit32.band(flags, 1) ~= 0
elseif r:peek(2) == "\54\4" then
r:skip(2)
local mode, charsize = r:u8(), r:u8()
if r.err then
return nil, r.err
end
version, width, height, stride = 1, 8, charsize, 1
count = if bit32.band(mode, 1) ~= 0 then 512 else 256
glyphAt, hasTable = 4, bit32.band(mode, 6) ~= 0
if height < 1 then
return nil, Err.new(Err.CORRUPT, "zero glyph height")
end
else
return nil, Err.new(Err.CORRUPT, "not a PSF font")
end
if count < 1 or count > maxGlyphs then
return nil, Err.new(Err.LIMIT, "glyph count " .. count .. " over maxGlyphs")
end
local size = stride * height
if glyphAt + count * size > r:size() then
return nil, Err.new(Err.TRUNCATED, "glyph data past the end")
end
local glyphs: { Types.BitmapGlyph } = {}
for i = 0, count - 1 do
glyphs[i + 1] = {
width = width,
height = height,
left = 0,
top = height,
advance = width,
pixels = Bitmap.unpack(r.buf, r.base + glyphAt + i * size, width, height, stride),
}
end
local map: { [number]: number } = {}
local sequences = {}
local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order
if hasTable then
local t = r:sub(glyphAt + count * size)
for i = 0, count - 1 do
local inSeq = false
local seq: { number } = {}
local entry: { any } = {}
unicodeTable[i + 1] = entry
local function endSeq()
if #seq > 0 then
table.insert(sequences, { glyph = i, codepoints = seq })
table.insert(entry, seq)
end
seq = {}
end
while true do
if t:eof() then
break
end
local cp
if version == 1 then
cp = t:u16le()
if cp == 0xFFFF then
break
elseif cp == 0xFFFE then
endSeq()
inSeq = true
continue
end
else
local b = t:u8()
if b == 0xFF then
break
elseif b == 0xFE then
endSeq()
inSeq = true
continue
end
-- UTF-8
local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1
if n < 0 then
return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table")
end
cp = if n == 0 then b elseif n == 1 then bit32.band(b, 0x1F) elseif n == 2 then bit32.band(b, 0x0F) else bit32.band(b, 0x07)
for _ = 1, n do
cp = cp * 64 + bit32.band(t:u8(), 0x3F)
end
end
if inSeq then
table.insert(seq, cp)
continue
end
table.insert(entry, cp)
if map[cp] == nil then
map[cp] = i
if glyphs[i + 1].codepoint == nil then
glyphs[i + 1].codepoint = cp
end
end
end
endSeq()
end
if t.err then
return nil, Err.new(Err.TRUNCATED, "Unicode table")
end
else
for i = 0, count - 1 do
glyphs[i + 1].codepoint = i
end
end
local strike: Types.BitmapStrike = { size = height, ascent = height, descent = 0, glyphs = glyphs, map = map, default = 0 }
local defaultGlyph = map[0xFFFD] or map[0x3F]
if defaultGlyph then
strike.default = defaultGlyph
end
return Bitmap.font(strike, {}, {
unicode = hasTable,
sequences = sequences,
unicodeTable = if hasTable then unicodeTable else nil,
width = width,
height = height,
source = { format = "psf", version = version, glyphs = count },
}), nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function utf8Bytes(cp: number): string
return utf8.char(cp)
end
function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local version = o.version or 2
if version ~= 1 and version ~= 2 then
return nil, Err.new(Err.ARG, "version must be 1 or 2")
end
local strike, err = Bitmap.strike(font, { px = o.px, chars = o.chars })
if not strike then
return nil, err
end
local glyphs = strike.glyphs
local n = #glyphs
if n == 0 then
return nil, Err.new(Err.ARG, "no glyphs")
end
-- the cell
local width = 0
for _, g in glyphs do
width = math.max(width, g.advance, g.left + g.width)
end
local height = math.max(1, strike.ascent + strike.descent)
if version == 1 then
if width > 8 then
return nil, Err.new(Err.ARG, "PSF 1 glyphs are 8 pixels wide (this font needs " .. width .. ")")
end
if n > 512 then
return nil, Err.new(Err.ARG, "PSF 1 holds 256 or 512 glyphs (this font has " .. n .. ")")
end
width = 8
end
width = math.max(width, 1)
local count = if version == 1 then (if n > 256 then 512 else 256) else n
local stride = math.ceil(width / 8)
local size = stride * height
local cells = buffer.create(count * size)
for i, g in glyphs do
local cell = buffer.create(width * height)
local x0, y0 = g.left, strike.ascent - g.top
for y = 0, g.height - 1 do
for x = 0, g.width - 1 do
local cx, cy = x0 + x, y0 + y
if cx >= 0 and cy >= 0 and cx < width and cy < height and buffer.readu8(g.pixels, y * g.width + x) >= 128 then
buffer.writeu8(cell, cy * width + cx, 255)
end
end
end
buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride))
end
-- the Unicode table: each glyph's code point and the extra mappings onto it
local cps: { { number } } = {}
for i = 1, count do
cps[i] = {}
end
local seen: { [number]: boolean } = {}
for i, g in glyphs do
if g.codepoint and not seen[g.codepoint] then
seen[g.codepoint] = true
table.insert(cps[i], g.codepoint)
end
end
if strike.map then
local extra: { { number } } = {}
for cp, gi in strike.map do
if not seen[cp] and gi >= 0 and gi < count then
table.insert(extra, { cp, gi })
end
end
table.sort(extra, function(a: { number }, b: { number }): boolean
return a[1] < b[1]
end)
for _, e in extra do
seen[e[1]] = true
table.insert(cps[e[2] + 1], e[1])
end
end
local meta = if type(font.meta) == "table" then font.meta else {}
local srcTable = if font.bitmap == strike and type(meta.unicodeTable) == "table" and #meta.unicodeTable == n then meta.unicodeTable else nil
local withTable = if o.unicode ~= nil then o.unicode else meta.unicode ~= false
local w = Bytes.writer(count * size + 64)
if version == 2 then
w:string("\114\181\74\134")
w:u32le(0)
w:u32le(32)
w:u32le(if withTable then 1 else 0)
w:u32le(count)
w:u32le(size)
w:u32le(height)
w:u32le(width)
else
w:string("\54\4")
w:u8((if count == 512 then 1 else 0) + (if withTable then 2 else 0))
w:u8(height)
end
w:bytes(cells)
if withTable then
local function put(cp: number)
if version == 2 then
w:string(utf8Bytes(cp))
elseif cp < 0xFFFE then
w:u16le(cp)
end
end
for i = 1, count do
-- a PSF read earlier writes its table back as it was (code points on several glyphs, sequences)
local list = if srcTable and srcTable[i] then srcTable[i] else cps[i]
for _, x in list do
if type(x) == "number" then
put(x)
end
end
for _, x in list do
if type(x) == "table" then
if version == 2 then
w:u8(0xFE)
else
w:u16le(0xFFFE)
end
for _, cp in x do
put(cp)
end
end
end
if version == 2 then
w:u8(0xFF)
else
w:u16le(0xFFFF)
end
end
end
return w:finish(), nil
end
return Psf
+52
View File
@@ -0,0 +1,52 @@
--!strict
-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the
-- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table,
-- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain /
-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection.
-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local TrueType = require("@rosetta/codecs/font/TrueType")
-- ------------------------------------------------------------------------------------------------ contract
local Ttf = {
name = "ttf",
category = "font",
extensions = { "ttf", "otf", "ttc", "otc" },
mime = { "font/ttf", "font/otf", "font/collection" },
deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true },
}
export type DecodeOptions = {
index: number?, -- the font of a collection (default 0)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Ttf.sniff(r: Bytes.Reader): number
local m = r:peek(4)
if m == "\0\1\0\0" or m == "OTTO" or m == "ttcf" or m == "true" then
return 0.9
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts)
if not font then
return nil, err
end
font.meta.source = { format = "ttf", outlines = font.meta.outlines, sfnt = font.meta.sfnt }
return font, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- count(r) -> the number of fonts in the file (1 unless a collection)
function Ttf.count(r: Bytes.Reader): number
return TrueType.count(r.buf, r.base)
end
return Ttf
+283
View File
@@ -0,0 +1,283 @@
--!strict
-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted
-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side
-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div,
-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement;
-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes,
-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the
-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops).
local Charstring = {}
export type Result = { cmds: { any }, advance: number, sbx: number }
-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result
export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? }
local readu8 = buffer.readu8
function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
local cmds: { any } = {}
local stack: { number } = {}
local sp = 0
local ps: { number } = {} -- the PostScript stack callothersubr / pop use
local x, y = 0, 0
local advance, sbx = 0, 0
local open = false
local flex = false
local flexPts: { number } = {}
local budget = 200000
local finished = false
local function push(v: number)
if sp < 48 then
sp += 1
stack[sp] = v
end
end
local function arg(i: number): number
return stack[i] or 0
end
local function close()
if open then
table.insert(cmds, { op = "close" })
open = false
end
end
local function moveTo(dx: number, dy: number)
x += dx
y += dy
if flex then
table.insert(flexPts, x)
table.insert(flexPts, y)
return
end
close()
local c: any = { op = "moveTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
end
local function ensureOpen()
if not open then
-- a drawing operator without a moveto starts at the current point
local c: any = { op = "moveTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
open = true
end
end
local function lineTo(dx: number, dy: number)
ensureOpen()
x += dx
y += dy
local c: any = { op = "lineTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
end
local function curveTo(a: number, b: number, c: number, d: number, e: number, f: number)
ensureOpen()
local x1, y1 = x + a, y + b
local x2, y2 = x1 + c, y1 + d
x, y = x2 + e, y2 + f
local cmd: any = { op = "cubicTo" }
cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = x1, y1, x2, y2, x, y
table.insert(cmds, cmd)
end
local function exec(b: buffer, depth: number): string?
if depth > 10 then
return "subroutines nested too deep"
end
local n = buffer.len(b)
local p = 0
while p < n do
budget -= 1
if budget <= 0 then
return "operation budget exceeded"
end
local v = readu8(b, p)
p += 1
if v >= 32 then
if v <= 246 then
push(v - 139)
elseif v <= 250 then
if p >= n then
return "truncated number"
end
push((v - 247) * 256 + readu8(b, p) + 108)
p += 1
elseif v <= 254 then
if p >= n then
return "truncated number"
end
push(-(v - 251) * 256 - readu8(b, p) - 108)
p += 1
else
if p + 4 > n then
return "truncated number"
end
local u = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3)
push(if u >= 0x80000000 then u - 0x100000000 else u)
p += 4
end
continue
end
local op = v
if op == 12 then
if p >= n then
return "truncated escape"
end
op = 1200 + readu8(b, p)
p += 1
end
if op == 13 then -- hsbw
sbx, advance = arg(1), arg(2)
x, y = sbx, 0
sp = 0
elseif op == 1207 then -- sbw
sbx, advance = arg(1), arg(3)
x, y = arg(1), arg(2)
sp = 0
elseif op == 21 then
moveTo(arg(1), arg(2))
sp = 0
elseif op == 22 then
moveTo(arg(1), 0)
sp = 0
elseif op == 4 then
moveTo(0, arg(1))
sp = 0
elseif op == 5 then
lineTo(arg(1), arg(2))
sp = 0
elseif op == 6 then
lineTo(arg(1), 0)
sp = 0
elseif op == 7 then
lineTo(0, arg(1))
sp = 0
elseif op == 8 then
curveTo(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6))
sp = 0
elseif op == 30 then -- vhcurveto
curveTo(0, arg(1), arg(2), arg(3), arg(4), 0)
sp = 0
elseif op == 31 then -- hvcurveto
curveTo(arg(1), 0, arg(2), arg(3), 0, arg(4))
sp = 0
elseif op == 9 then
close()
sp = 0
elseif op == 10 then -- callsubr
local idx = arg(sp)
sp = math.max(0, sp - 1)
local sub = ctx.subrs[idx + 1]
if not sub then
return "call of a missing subroutine " .. idx
end
local err = exec(sub, depth + 1)
if err or finished then
return err
end
elseif op == 11 then -- return
return nil
elseif op == 14 then -- endchar
close()
finished = true
return nil
elseif op == 1212 then -- div
if sp >= 2 then
local d = stack[sp]
stack[sp - 1] = if d ~= 0 then stack[sp - 1] / d else 0
sp -= 1
end
elseif op == 1216 then -- callothersubr: args... n othersubr#
local num = arg(sp)
local count = arg(sp - 1)
sp = math.max(0, sp - 2)
count = math.clamp(count, 0, sp)
local args = {}
for i = 1, count do
args[i] = stack[sp - count + i]
end
sp -= count
if num == 1 then
flex = true
table.clear(flexPts)
elseif num == 2 then
-- a flex point: the rmoveto before it already recorded the point
elseif num == 0 and flex then
flex = false
-- flexPts: the reference point, then 6 control / end points
local f = flexPts
if #f >= 14 then
-- restore the current point to before the flex sequence's moves
local function curve(i: number)
ensureOpen()
local cmd: any = { op = "cubicTo" }
cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = f[i], f[i + 1], f[i + 2], f[i + 3], f[i + 4], f[i + 5]
table.insert(cmds, cmd)
end
curve(3)
curve(9)
x, y = f[13], f[14]
end
table.clear(ps)
table.insert(ps, args[3] or y)
table.insert(ps, args[2] or x)
elseif num == 3 then
table.clear(ps)
table.insert(ps, 3)
else
table.clear(ps)
for i = #args, 1, -1 do
table.insert(ps, args[i])
end
end
elseif op == 1217 then -- pop
push(table.remove(ps) or 0)
elseif op == 1233 then -- setcurrentpoint
x, y = arg(1), arg(2)
sp = 0
elseif op == 1206 then -- seac: asb adx ady bchar achar
local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5)
sp = 0
local seac = ctx.seac
if not seac then
return "seac without base glyphs"
end
local base = seac(bchar)
local accent = seac(achar)
if not base or not accent then
return "seac of a missing glyph"
end
close()
for _, c in base.cmds do
table.insert(cmds, c)
end
local ox, oy = adx - asb, ady
for _, c in accent.cmds do
local t: any = { op = c.op }
for i = 1, #c, 2 do
t[i], t[i + 1] = c[i] + ox, c[i + 1] + oy
end
table.insert(cmds, t)
end
finished = true
return nil
elseif op == 1 or op == 3 or op == 1200 or op == 1201 or op == 1202 then
sp = 0 -- hints
else
sp = 0 -- unknown operators clear the stack
end
end
return nil
end
local err = exec(cs, 0)
if err then
return nil, err
end
close()
return { cmds = cmds, advance = advance, sbx = sbx }, nil
end
return Charstring
+368
View File
@@ -0,0 +1,368 @@
--!strict
-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the
-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox,
-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV,
-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring
-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph
-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through
-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple
-- Master and CID-keyed (Type 9 / 11) fonts, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Raster = require("@rosetta/codecs/image/Raster")
local GlyphNames = require("@rosetta/codecs/font/GlyphNames")
local Charstring = require("@rosetta/font/type1/Charstring")
-- ------------------------------------------------------------------------------------------------ contract
local Type1 = {
name = "type1",
category = "font",
extensions = { "pfb", "pfa", "t1" },
mime = { "application/x-font-type1" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" },
caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } },
}
export type DecodeOptions = { maxGlyphs: number? } -- default 65536
-- ------------------------------------------------------------------------------------------------ sniff
function Type1.sniff(r: Bytes.Reader): number
local h = r:peek(64)
if string.sub(h, 1, 2) == "\128\1" then
h = string.sub(h, 7)
end
if string.sub(h, 1, 14) == "%!PS-AdobeFont" or string.sub(h, 1, 10) == "%!FontType" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA
local function sections(r: Bytes.Reader): (string?, buffer?, string?)
local b = r.buf
local n = r:size()
if r:peek(2) == "\128\1" then
local clear, bin = {}, Bytes.writer()
local p = 0
while p + 2 <= n do
local h = r:sub(p, 6)
local m, ty, len = h:u8(), h:u8(), h:u32le()
if m ~= 128 then
return nil, nil, "bad PFB segment marker"
end
if ty == 3 then
break
end
if h.err or p + 6 + len > n then
return nil, nil, "truncated PFB segment"
end
if ty == 1 then
if #clear == 0 or bin:tell() == 0 then
table.insert(clear, buffer.readstring(b, r.base + p + 6, len))
end
elseif ty == 2 then
bin:bytes(r:sub(p + 6, len):bytes(len))
else
return nil, nil, "bad PFB segment type " .. ty
end
p += 6 + len
end
return table.concat(clear), bin:finish(), nil
end
local text = buffer.readstring(b, r.base, n)
local e = string.find(text, "eexec", 1, true)
if not e then
return nil, nil, "no eexec section"
end
local clear = string.sub(text, 1, e + 4)
-- PFA: hex digits after eexec, up to the zeros trailer (or binary if not hex)
local rest = string.sub(text, e + 5)
local hexPart = string.match(rest, "^%s*([%x%s]+)")
if hexPart and #hexPart > 8 then
local digits = string.gsub(hexPart, "%s", "")
local out = buffer.create(#digits // 2)
for i = 0, #digits // 2 - 1 do
buffer.writeu8(out, i, tonumber(string.sub(digits, i * 2 + 1, i * 2 + 2), 16) or 0)
end
return clear, out, nil
end
local s = string.match(rest, "^[\r\n]*(.*)$") or rest
return clear, buffer.fromstring(s), nil
end
local function decrypt(src: buffer, off: number, n: number, key: number, skip: number): buffer
local r = key
local out = buffer.create(math.max(0, n - skip))
for i = 0, n - 1 do
local c = buffer.readu8(src, off + i)
local p = bit32.bxor(c, bit32.rshift(r, 8))
r = ((c + r) * 52845 + 22719) % 65536
if i >= skip then
buffer.writeu8(out, i - skip, p)
end
end
return out
end
-- binary strings of the private dictionary: "<len> RD <bytes>" / "<len> -| <bytes>"
local function binaryAt(priv: buffer, p: number, len: number): buffer?
if p < 0 or len < 0 or p + len > buffer.len(priv) then
return nil
end
local out = buffer.create(len)
buffer.copy(out, 0, priv, p, len)
return out
end
local function psString(clear: string, key: string): string?
return string.match(clear, "/" .. key .. "%s*%((.-)%)%s*[rd]") or string.match(clear, "/" .. key .. "%s*%((.-)%)")
end
local Face = {}
Face.__index = Face
function Face.glyphIndex(self: any, cp: number): number
return self._cmap[cp] or 0
end
function Face.advance(self: any, g: number): number
local res = self:_run(g)
return if res then res.advance else 0
end
function Face.kern(_self: any, _a: number, _b: number): number
return 0
end
function Face._run(self: any, g: number): Charstring.Result?
local cached = self._cache[g]
if cached ~= nil then
return if cached == false then nil else cached
end
local cs = self._charstrings[g + 1]
if not cs then
return nil
end
local res = Charstring.run(cs, self._ctx)
self._cache[g] = res or false
return res
end
function Face.outline(self: any, g: number): { any }?
local res = self:_run(g)
if not res then
return nil
end
local out = table.create(#res.cmds)
for i, c in res.cmds do
out[i] = table.clone(c)
end
return out
end
function Face.rasterize(self: any, g: number, px: number): Types.Image?
if type(px) ~= "number" or not (px > 0) or px > 4096 then
return nil
end
local res = self:_run(g)
if not res then
return nil
end
local s = px / self.unitsPerEm
local m = Raster.mask(res.cmds, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 })
local img
if m then
img = Types.Image.new(m.width, m.height, "alpha8")
buffer.copy(img.pixels, 0, m.coverage)
img.meta.left, img.meta.top = m.x, -m.y
else
img = Types.Image.new(0, 0, "alpha8")
img.meta.left, img.meta.top = 0, 0
end
img.meta.advance = res.advance * s
img.meta.glyph = g
return img
end
function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 65536
local clear, enc, serr = sections(r)
if not clear or not enc then
return nil, Err.from(serr)
end
if not string.find(clear, "eexec", 1, true) and buffer.len(enc) == 0 then
return nil, Err.new(Err.CORRUPT, "no eexec section")
end
if buffer.len(enc) < 4 then
return nil, Err.new(Err.TRUNCATED, "eexec section too short")
end
local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4)
local ptext = buffer.tostring(priv)
local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4
-- Subrs
local subrs: { buffer } = {}
local function charstring(p: number, len: number): buffer?
local raw = binaryAt(priv, p, len)
if not raw then
return nil
end
if lenIV < 0 then
return raw
end
return decrypt(raw, 0, len, 4330, lenIV)
end
local sAt = string.find(ptext, "/Subrs", 1, true)
local csAt = string.find(ptext, "/CharStrings", 1, true)
if not csAt then
return nil, Err.new(Err.CORRUPT, "no CharStrings")
end
if sAt and sAt < csAt then
local p = sAt
while true do
local s, e0, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p)
if not s or s > csAt then
break
end
local e = e0 :: number
local i, n = tonumber(idx) :: number, tonumber(len) :: number
if i > 65535 then
return nil, Err.new(Err.LIMIT, "too many subroutines")
end
local cs = charstring(e, n)
if not cs then
return nil, Err.new(Err.TRUNCATED, "subroutine " .. i .. " past the end")
end
subrs[i + 1] = cs
p = e + n
end
end
-- CharStrings
local names: { string } = {}
local charstrings: { buffer } = {}
local byName: { [string]: number } = {}
local p = csAt + 12
while true do
local s, e0, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p)
if not s then
break
end
local e = e0 :: number
-- stop at the end of the dictionary
if string.find(string.sub(ptext, p, s), "%send%s") then
break
end
local n = tonumber(len) :: number
local cs = charstring(e, n)
if not cs then
return nil, Err.new(Err.TRUNCATED, "charstring " .. tostring(name) .. " past the end")
end
if #names >= maxGlyphs then
return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
end
table.insert(names, name :: string)
table.insert(charstrings, cs)
if byName[name :: string] == nil then
byName[name :: string] = #names - 1
end
p = e + n
end
if #names == 0 then
return nil, Err.new(Err.CORRUPT, "no glyphs")
end
-- .notdef first: glyph 0
local nd = byName[".notdef"]
if nd and nd ~= 0 then
names[1], names[nd + 1] = names[nd + 1], names[1]
charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1]
byName[names[1]], byName[names[nd + 1]] = 0, nd
end
-- the encoding
local encoding: { [number]: string } = {}
if string.find(clear, "/Encoding%s+StandardEncoding") then
for code, gname in GlyphNames.STANDARD do
encoding[code] = gname
end
else
for code, gname in string.gmatch(clear, "dup%s+(%d+)%s*/([^%s/]+)%s+put") do
encoding[tonumber(code) :: number] = gname
end
end
local cmap: { [number]: number } = {}
for _, gname in encoding do
local g = byName[gname]
local cp = GlyphNames.unicode(gname)
if g and cp and cmap[cp] == nil then
cmap[cp] = g
end
end
for k, gname in names do
local cp = GlyphNames.unicode(gname)
if cp and cmap[cp] == nil then
cmap[cp] = k - 1
end
end
-- font matrix / bbox
local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]")
local scale = 0.001
if fm then
local a = tonumber(string.match(fm, "^%s*(%S+)"))
if a and a > 0 then
scale = a
end
end
local bb = string.match(clear, "/FontBBox%s*[{%[]([^}%]]*)[}%]]")
local bbox = { 0, 0, 0, 0 }
if bb then
local k = 1
for v in string.gmatch(bb, "%S+") do
bbox[k] = tonumber(v) or 0
k += 1
end
end
local upm = math.floor(1 / scale + 0.5)
local font = setmetatable({
kind = "font",
info = {
family = psString(clear, "FamilyName") or string.match(clear, "/FontName%s*/(%S+)"),
style = psString(clear, "Weight") or "Regular",
fullName = psString(clear, "FullName"),
postscriptName = string.match(clear, "/FontName%s*/(%S+)"),
},
unitsPerEm = upm,
ascent = bbox[4],
descent = bbox[2],
lineGap = 0,
numGlyphs = #names,
meta = {
glyphNames = names,
encoding = encoding,
bbox = bbox,
italicAngle = tonumber(string.match(clear, "/ItalicAngle%s+(%-?[%d%.]+)") or "0"),
lenIV = lenIV,
source = { format = "type1", variant = if r:peek(2) == "\128\1" then "pfb" else "pfa" },
},
_cmap = cmap,
_charstrings = charstrings,
_cache = {},
}, Face)
font._ctx = {
subrs = subrs,
seac = function(code: number): Charstring.Result?
local gname = GlyphNames.STANDARD[code]
local g = if gname then byName[gname] else nil
if not g then
return nil
end
local res = Charstring.run(charstrings[g + 1], { subrs = subrs })
return res
end,
}
return font, nil
end
return Type1
+132
View File
@@ -0,0 +1,132 @@
--!strict
-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding
-- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended
-- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local TrueType = require("@rosetta/codecs/font/TrueType")
-- ------------------------------------------------------------------------------------------------ contract
local Woff = {
name = "woff",
category = "font",
extensions = { "woff" },
mime = { "font/woff" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Woff.sniff(r: Bytes.Reader): number
return if r:peek(4) == "wOFF" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err
function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?)
local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
local base = r.base
if not r:match("wOFF") then
return nil, Err.new(Err.CORRUPT, "bad signature", base), nil
end
local flavor = r:string(4)
local length = r:u32be()
local numTables = r:u16be()
r:skip(2)
local total = r:u32be()
r:skip(4)
local metaOffset, metaLength, metaOrig = r:u32be(), r:u32be(), r:u32be()
r:skip(8)
if r.err then
return nil, r.err, nil
end
if flavor == "ttcf" then
return nil, Err.new(Err.UNSUPPORTED, "font collections in WOFF", base + 4), nil
end
if length > r:size() then
return nil, Err.new(Err.TRUNCATED, string.format("file is %d bytes, header says %d", r:size(), length), base + 8), nil
end
if numTables == 0 or total > maxBytes or total < 12 + 16 * numTables then
return nil, Err.new(if total > maxBytes then Err.LIMIT else Err.CORRUPT, "bad table count or sfnt size", base + 12), nil
end
local dir = {}
for i = 1, numTables do
local e = { tag = r:string(4), offset = r:u32be(), comp = r:u32be(), orig = r:u32be(), sum = r:u32be() }
dir[i] = e
end
if r.err then
return nil, r.err, nil
end
local out = buffer.create(total)
local w = Bytes.writer(12)
w:string(flavor)
w:u16be(numTables)
local es, sel = 1, 0
while es * 2 <= numTables do
es *= 2
sel += 1
end
w:u16be(es * 16)
w:u16be(sel)
w:u16be(numTables * 16 - es * 16)
buffer.copy(out, 0, w.buf, 0, 12)
local p = 12 + 16 * numTables
for i, e in dir do
if e.offset + e.comp > r:size() or e.comp > e.orig then
return nil, Err.new(Err.CORRUPT, "table " .. e.tag .. " out of range", base + 44 + (i - 1) * 20), nil
end
if p + e.orig > total then
return nil, Err.new(Err.CORRUPT, "tables larger than totalSfntSize", base + 16), nil
end
local d = 12 + (i - 1) * 16
buffer.writestring(out, d, e.tag)
buffer.writeu32(out, d + 4, bit32.byteswap(e.sum))
buffer.writeu32(out, d + 8, bit32.byteswap(p))
buffer.writeu32(out, d + 12, bit32.byteswap(e.orig))
if e.comp < e.orig then
local t, err = Deflate.zlib(r.buf, base + e.offset, e.comp, e.orig)
if not t then
return nil, Err.new((err :: any).code, "table " .. e.tag .. ": " .. (err :: any).message, base + e.offset), nil
end
buffer.copy(out, p, t, 0, e.orig)
else
buffer.copy(out, p, r.buf, base + e.offset, e.orig)
end
p += e.orig
p = (p + 3) // 4 * 4
if p > total then
p = total
end
end
local xml = nil
if metaLength > 0 and metaOffset + metaLength <= r:size() then
local m = Deflate.zlib(r.buf, base + metaOffset, metaLength, metaOrig)
if m then
xml = buffer.tostring(m)
end
end
return out, nil, xml
end
function Woff.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local sfnt, err, xml = Woff.sfnt(r, opts)
if not sfnt then
return nil, err
end
local font, ferr = TrueType.font(sfnt)
if not font then
return nil, ferr
end
font.meta.woffMetadata = xml
font.meta.source = { format = "woff", outlines = font.meta.outlines }
return font, nil
end
return Woff
+548
View File
@@ -0,0 +1,548 @@
--!strict
-- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table
-- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph,
-- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx
-- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor).
--
-- Never throws: malformed data returns nil, message.
local Bytes = require("@rosetta/core/Bytes")
local Brotli = require("@rosetta/codecs/compress/Brotli")
local Rebuild = {}
local readu8 = buffer.readu8
local band, rshift = bit32.band, bit32.rshift
local KNOWN = {
"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post", "cvt ", "fpgm", "glyf", "loca", "prep", "CFF ",
"VORG", "EBDT", "EBLC", "gasp", "hdmx", "kern", "LTSH", "PCLT", "VDMX", "vhea", "vmtx", "BASE", "GDEF", "GPOS",
"GSUB", "EBSC", "JSTF", "MATH", "CBDT", "CBLC", "COLR", "CPAL", "SVG ", "sbix", "acnt", "avar", "bdat", "bloc",
"bsln", "cvar", "fdsc", "feat", "fmtx", "fvar", "gvar", "hsty", "just", "lcar", "mort", "morx", "opbd", "prop",
"trak", "Zapf", "Silf", "Glat", "Gloc", "Feat", "Sill",
}
-- UIntBase128 from r
local function base128(r: Bytes.Reader): number?
local v = 0
for i = 1, 5 do
local b = r:u8()
if r.err or (i == 1 and b == 0x80) then
return nil
end
if v >= 2 ^ 25 then
return nil
end
v = v * 128 + band(b, 0x7F)
if b < 0x80 then
return v
end
end
return nil
end
-- a cursor over a stream inside the decompressed block
type Stream = { buf: buffer, p: number, e: number, bad: boolean }
local function stream(b: buffer, p: number, n: number): Stream
return { buf = b, p = p, e = p + n, bad = false }
end
local function su8(s: Stream): number
if s.p >= s.e then
s.bad = true
return 0
end
local v = readu8(s.buf, s.p)
s.p += 1
return v
end
local function su16(s: Stream): number
return su8(s) * 256 + su8(s)
end
local function si16(s: Stream): number
local v = su16(s)
return if v >= 32768 then v - 65536 else v
end
local function s255(s: Stream): number
local c = su8(s)
if c == 253 then
return su16(s)
elseif c == 255 then
return su8(s) + 253
elseif c == 254 then
return su8(s) + 506
end
return c
end
local function withSign(flag: number, v: number): number
return if band(flag, 1) ~= 0 then v else -v
end
-- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat
local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?)
local h = stream(b, p, n)
su16(h) -- reserved
local option = su16(h)
local numGlyphs = su16(h)
local indexFormat = su16(h)
local sizes = {}
for i = 1, 7 do
sizes[i] = su16(h) * 65536 + su16(h)
end
if h.bad then
return nil, "truncated glyf transform header"
end
local at = h.p
local streams: { Stream } = {}
for i = 1, 7 do
if at + sizes[i] > p + n then
return nil, "glyf transform stream past the end"
end
streams[i] = stream(b, at, sizes[i])
at += sizes[i]
end
local nContour, nPoints, flagS, glyphS, compS, bboxS, instrS = streams[1], streams[2], streams[3], streams[4], streams[5], streams[6], streams[7]
local overlap: Stream? = nil
if band(option, 1) ~= 0 then
overlap = stream(b, at, (numGlyphs + 7) // 8)
if at + (numGlyphs + 7) // 8 > p + n then
return nil, "overlap bitmap past the end"
end
end
-- the bbox bitmap leads the bbox stream
local bitmapLen = 4 * ((numGlyphs + 31) // 32)
if bitmapLen > sizes[6] then
return nil, "bbox bitmap past the end"
end
local bboxBits = bboxS.p
bboxS.p += bitmapLen
local function hasBox(g: number): boolean
return band(readu8(b, bboxBits + g // 8), rshift(0x80, g % 8)) ~= 0
end
local w = Bytes.writer(n * 2)
local loca = table.create(numGlyphs + 1, 0)
local xMins = table.create(numGlyphs, 0)
for g = 0, numGlyphs - 1 do
loca[g + 1] = w.pos
local nc = si16(nContour)
if nContour.bad then
return nil, "nContour stream truncated"
end
if nc == 0 then
if hasBox(g) then
return nil, "empty glyph with a bounding box"
end
elseif nc > 0 then
-- simple glyph
local ends = table.create(nc, 0)
local total = 0
for c = 1, nc do
total += s255(nPoints)
ends[c] = total - 1
end
if nPoints.bad or total > 65535 then
return nil, "bad point counts"
end
local xs, ys, on = table.create(total, 0), table.create(total, 0), table.create(total, false)
local x, y = 0, 0
for k = 1, total do
local fl = su8(flagS)
on[k] = rshift(fl, 7) == 0
fl = band(fl, 0x7F)
local dx, dy
if fl < 10 then
dx = 0
dy = withSign(fl, band(fl, 14) * 128 + su8(glyphS))
elseif fl < 20 then
dx = withSign(fl, band(fl - 10, 14) * 128 + su8(glyphS))
dy = 0
elseif fl < 84 then
local b0 = fl - 20
local b1 = su8(glyphS)
dx = withSign(fl, 1 + band(b0, 0x30) + rshift(b1, 4))
dy = withSign(rshift(fl, 1), 1 + band(b0, 0x0C) * 4 + band(b1, 0x0F))
elseif fl < 120 then
local b0 = fl - 84
dx = withSign(fl, 1 + (b0 // 12) * 256 + su8(glyphS))
dy = withSign(rshift(fl, 1), 1 + rshift(b0 % 12, 2) * 256 + su8(glyphS))
elseif fl < 124 then
local b1, b2, b3 = su8(glyphS), su8(glyphS), su8(glyphS)
dx = withSign(fl, b1 * 16 + rshift(b2, 4))
dy = withSign(rshift(fl, 1), band(b2, 0x0F) * 256 + b3)
else
local b1, b2, b3, b4 = su8(glyphS), su8(glyphS), su8(glyphS), su8(glyphS)
dx = withSign(fl, b1 * 256 + b2)
dy = withSign(rshift(fl, 1), b3 * 256 + b4)
end
x += dx
y += dy
xs[k], ys[k] = x, y
end
local ilen = s255(glyphS)
if flagS.bad or glyphS.bad then
return nil, "flag / glyph stream truncated"
end
local x0, y0, x1, y1
if hasBox(g) then
x0 = si16(bboxS)
y0 = si16(bboxS)
x1 = si16(bboxS)
y1 = si16(bboxS)
else
x0, y0, x1, y1 = 32767, 32767, -32768, -32768
for k = 1, total do
x0 = math.min(x0, xs[k])
y0 = math.min(y0, ys[k])
x1 = math.max(x1, xs[k])
y1 = math.max(y1, ys[k])
end
if total == 0 then
x0, y0, x1, y1 = 0, 0, 0, 0
end
end
xMins[g + 1] = x0
w:u16be(nc % 65536)
w:u16be(x0 % 65536)
w:u16be(y0 % 65536)
w:u16be(x1 % 65536)
w:u16be(y1 % 65536)
for c = 1, nc do
w:u16be(ends[c])
end
w:u16be(ilen)
if instrS.p + ilen > instrS.e then
return nil, "instruction stream truncated"
end
w:bytes(b, instrS.p, ilen)
instrS.p += ilen
local ov = overlap ~= nil and band(readu8(b, (overlap :: Stream).p + g // 8), rshift(0x80, g % 8)) ~= 0
-- flags (short vectors, same-as-previous, repeats) and the coordinate deltas, as compilers write them
local fls = table.create(total, 0)
for k = 1, total do
local fl = if on[k] then 1 else 0
if k == 1 and ov then
fl += 0x40
end
local dx = xs[k] - (if k > 1 then xs[k - 1] else 0)
local dy = ys[k] - (if k > 1 then ys[k - 1] else 0)
if dx == 0 then
fl += 0x10
elseif dx > -256 and dx < 256 then
fl += if dx > 0 then 0x12 else 0x02
end
if dy == 0 then
fl += 0x20
elseif dy > -256 and dy < 256 then
fl += if dy > 0 then 0x24 else 0x04
end
fls[k] = fl
end
local k = 1
while k <= total do
local fl = fls[k]
local run = 0
while k + run + 1 <= total and fls[k + run + 1] == fl and run < 255 do
run += 1
end
if run > 1 then
w:u8(fl + 8)
w:u8(run)
k += run + 1
else
w:u8(fl)
k += 1
end
end
for pass = 0, 1 do
local cs = if pass == 0 then xs else ys
local short, same = if pass == 0 then 0x02 else 0x04, if pass == 0 then 0x10 else 0x20
local prev = 0
for q = 1, total do
local d = cs[q] - prev
prev = cs[q]
local fl = fls[q]
if band(fl, short) ~= 0 then
w:u8(math.abs(d))
elseif band(fl, same) == 0 then
w:u16be(d % 65536)
end
end
end
elseif nc == -1 then
if not hasBox(g) then
return nil, "composite glyph without a bounding box"
end
local x0, y0, x1, y1 = si16(bboxS), si16(bboxS), si16(bboxS), si16(bboxS)
xMins[g + 1] = x0
w:u16be(0xFFFF)
w:u16be(x0 % 65536)
w:u16be(y0 % 65536)
w:u16be(x1 % 65536)
w:u16be(y1 % 65536)
-- copy the component records: their length follows from the flags
local start = compS.p
local instr = false
while true do
local fl = su16(compS)
su16(compS) -- glyph index
local len = if band(fl, 1) ~= 0 then 4 else 2
if band(fl, 8) ~= 0 then
len += 2
elseif band(fl, 0x40) ~= 0 then
len += 4
elseif band(fl, 0x80) ~= 0 then
len += 8
end
compS.p += len
if band(fl, 0x100) ~= 0 then
instr = true
end
if compS.bad or compS.p > compS.e then
return nil, "composite stream truncated"
end
if band(fl, 0x20) == 0 then
break
end
end
w:bytes(b, start, compS.p - start)
if instr then
local ilen = s255(glyphS)
if glyphS.bad or instrS.p + ilen > instrS.e then
return nil, "instruction stream truncated"
end
w:u16be(ilen)
w:bytes(b, instrS.p, ilen)
instrS.p += ilen
end
else
return nil, "bad contour count " .. nc
end
if bboxS.bad then
return nil, "bbox stream truncated"
end
-- 4-byte alignment
while w.pos % 4 ~= 0 do
w:u8(0)
end
if w.pos > maxBytes then
return nil, "limit"
end
end
loca[numGlyphs + 1] = w.pos
if indexFormat == 0 and w.pos > 0x1FFFE then
indexFormat = 1 -- (head.indexToLocFormat is patched to match)
end
return { glyf = w:finish(), loca = loca, xMins = xMins, numGlyphs = numGlyphs, indexFormat = indexFormat }, nil
end
-- hmtx transform (version 1): advances + the side bearings that were not dropped
local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: number, xMins: { number }): (buffer?, string?)
local s = stream(b, p, n)
local flags = su8(s)
local out = Bytes.writer(numH * 4 + (numGlyphs - numH) * 2)
local adv = table.create(numH, 0)
for i = 1, numH do
adv[i] = su16(s)
end
local lsb = table.create(numGlyphs, 0)
for i = 1, numH do
lsb[i] = if band(flags, 1) == 0 then si16(s) else (xMins[i] or 0)
end
for i = numH + 1, numGlyphs do
lsb[i] = if band(flags, 2) == 0 then si16(s) else (xMins[i] or 0)
end
if s.bad then
return nil, "hmtx transform truncated"
end
for i = 1, numH do
out:u16be(adv[i])
out:u16be(lsb[i] % 65536)
end
for i = numH + 1, numGlyphs do
out:u16be(lsb[i] % 65536)
end
return out:finish(), nil
end
-- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit")
function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?)
if not r:match("wOF2") then
return nil, "bad signature", "corrupt"
end
local flavor = r:string(4)
local length = r:u32be()
local numTables = r:u16be()
r:skip(2)
local totalSfnt = r:u32be()
local totalComp = r:u32be()
r:skip(24)
if r.err then
return nil, "truncated header", "truncated"
end
if flavor == "ttcf" then
return nil, "font collections in WOFF2", "unsupported"
end
if length > r:size() then
return nil, "file shorter than its header says", "truncated"
end
if numTables == 0 or numTables > 1024 then
return nil, "bad table count", "corrupt"
end
local dir = {}
local streamTotal = 0
for i = 1, numTables do
local flags = r:u8()
local tag = KNOWN[band(flags, 63) + 1]
if band(flags, 63) == 63 then
tag = r:string(4)
end
local version = rshift(flags, 6)
local orig = base128(r)
if not tag or not orig then
return nil, "bad table directory entry " .. i, if r.err then "truncated" else "corrupt"
end
local transformed = if tag == "glyf" or tag == "loca" then version == 0 else version ~= 0
local tlen = orig
if transformed then
local t = base128(r)
if not t then
return nil, "bad transformLength", "corrupt"
end
tlen = t
end
if (tag == "glyf" or tag == "loca") and not transformed and version ~= 3 then
return nil, "bad glyf / loca transform version", "corrupt"
end
if transformed and tag ~= "glyf" and tag ~= "loca" and tag ~= "hmtx" then
return nil, "unknown transform of " .. tag, "unsupported"
end
dir[i] = { tag = tag, orig = orig, len = tlen, transformed = transformed, at = streamTotal }
streamTotal += tlen
if streamTotal > maxBytes or orig > maxBytes then
return nil, "limit", "limit"
end
end
local compAt = r.pos
if compAt + totalComp > r.limit then
return nil, "compressed data past the end", "truncated"
end
local data, berr = Brotli.decompress(r.buf, compAt, totalComp, { maxBytes = math.max(streamTotal, 1) })
if not data then
local e = berr :: any
return nil, "brotli: " .. tostring(e.message), if e.code == "LIMIT" then "limit" else "corrupt"
end
if buffer.len(data) < streamTotal then
return nil, "decompressed stream shorter than the tables", "corrupt"
end
-- the tables, glyf / loca / hmtx rebuilt
local byTag: { [string]: any } = {}
for _, e in dir do
byTag[e.tag] = e
end
local tables: { [string]: buffer } = {}
local g = byTag.glyf
local xMins: { number } = {}
local locaLong: boolean? = nil
if g and g.transformed then
if not byTag.loca then
return nil, "glyf without loca", "corrupt"
end
local res, gerr = glyf(data, g.at, g.len, maxBytes)
if not res then
return nil, "glyf: " .. tostring(gerr), if gerr == "limit" then "limit" else "corrupt"
end
tables.glyf = res.glyf
xMins = res.xMins
local short = res.indexFormat == 0
local lw = Bytes.writer((res.numGlyphs + 1) * 4)
for _, o in res.loca do
if short then
lw:u16be(o // 2)
else
lw:u32be(o)
end
end
tables.loca = lw:finish()
locaLong = not short
end
for _, e in dir do
if e.tag == "glyf" or e.tag == "loca" then
if not e.transformed then
local t = buffer.create(e.len)
buffer.copy(t, 0, data, e.at, e.len)
tables[e.tag] = t
end
elseif e.tag == "hmtx" and e.transformed then
-- needs numGlyphs (maxp) and numberOfHMetrics (hhea)
local mp, hh = byTag.maxp, byTag.hhea
if not mp or not hh or mp.len < 6 or hh.len < 36 then
return nil, "hmtx transform without maxp / hhea", "corrupt"
end
local numGlyphs = readu8(data, mp.at + 4) * 256 + readu8(data, mp.at + 5)
local numH = readu8(data, hh.at + 34) * 256 + readu8(data, hh.at + 35)
if numH < 1 or numH > numGlyphs then
return nil, "bad numberOfHMetrics", "corrupt"
end
local t, herr = hmtx(data, e.at, e.len, numGlyphs, numH, xMins)
if not t then
return nil, herr, "corrupt"
end
tables.hmtx = t
else
local t = buffer.create(e.len)
buffer.copy(t, 0, data, e.at, e.len)
tables[e.tag] = t
end
end
-- head.indexToLocFormat must agree with the rebuilt loca
if locaLong ~= nil and tables.head and buffer.len(tables.head) >= 54 then
buffer.writeu8(tables.head, 50, 0)
buffer.writeu8(tables.head, 51, if locaLong then 1 else 0)
end
-- the sfnt: directory sorted by tag, tables 4-byte aligned
local tags = {}
for t in tables do
table.insert(tags, t)
end
table.sort(tags)
local n = #tags
local size = 12 + 16 * n
for _, t in tags do
size += (buffer.len(tables[t]) + 3) // 4 * 4
end
if size > maxBytes then
return nil, "limit", "limit"
end
local out = buffer.create(size)
buffer.writestring(out, 0, flavor)
local es, sel = 1, 0
while es * 2 <= n do
es *= 2
sel += 1
end
local function be16(o: number, v: number)
buffer.writeu8(out, o, rshift(v, 8))
buffer.writeu8(out, o + 1, band(v, 255))
end
local function be32(o: number, v: number)
buffer.writeu32(out, o, bit32.byteswap(v))
end
be16(4, n)
be16(6, es * 16)
be16(8, sel)
be16(10, n * 16 - es * 16)
local p = 12 + 16 * n
for i, t in tags do
local tb = tables[t]
local d = 12 + (i - 1) * 16
buffer.writestring(out, d, t)
be32(d + 4, 0) -- checksums are not recomputed
be32(d + 8, p)
be32(d + 12, buffer.len(tb))
buffer.copy(out, p, tb)
p += (buffer.len(tb) + 3) // 4 * 4
end
local _ = totalSfnt
return out, nil, nil
end
return Rebuild
+57
View File
@@ -0,0 +1,57 @@
--!strict
-- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx
-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF
-- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local TrueType = require("@rosetta/codecs/font/TrueType")
local Rebuild = require("@rosetta/font/woff2/Rebuild")
-- ------------------------------------------------------------------------------------------------ contract
local Woff2 = {
name = "woff2",
category = "font",
extensions = { "woff2" },
mime = { "font/woff2" },
deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
-- ------------------------------------------------------------------------------------------------ sniff
function Woff2.sniff(r: Bytes.Reader): number
return if r:peek(4) == "wOF2" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err
function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
local at = r.base
local out, msg, code = Rebuild.sfnt(r, maxBytes)
if not out then
return nil, Err.from(msg or "rebuild failed", at, code or "corrupt")
end
return out, nil
end
function Woff2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local sfnt, err = Woff2.sfnt(r, opts)
if not sfnt then
return nil, err
end
local font, ferr = TrueType.font(sfnt)
if not font then
return nil, ferr
end
font.meta.source = { format = "woff2", outlines = font.meta.outlines }
return font, nil
end
return Woff2