Files
rosetta/src/Formats/font/fon/init.luau
T

289 lines
9.1 KiB
Luau

--!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("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Text = require("@formats/codecs/text/Text")
local Bitmap = require("@formats/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