ws-arch2: font/psf (PSF 1 / 2 read + write, Unicode tables kept on round trip, .psfu.gz via the api); Types.BitmapStrike.map (extra code points per glyph, additive)

This commit is contained in:
4DBug committed 2026-10-31 15:03:35 -05:00
1 parent 1b0bc158e8
commit 19f486031d
9 files changed
+545 -8

No files matched your search

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