Files
rosetta/src/Rosetta/font/bdf/init.luau
T

288 lines
11 KiB
Luau

--!strict
-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1
-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes
-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR 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?, -- default 16
chars: (string | { number })?, -- default printable ASCII
name: string?, -- XLFD; default built from the 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
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),
}
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