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:
1 parent
1b0bc158e8
commit
19f486031d
9 files changed
+545
-8
No files matched your search
@@ -48,6 +48,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| font | bdf | .bdf | yes | yes | bitmap: true | `tests/font/bdf.luau` |
|
||||
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary", extraFiles: true | `tests/font/bmfont.luau` |
|
||||
| font | pcf | .pcf | yes | - | bitmap: true | `tests/font/pcf.luau` |
|
||||
| font | psf | .psf .psfu | yes | yes | bitmap: true, variants: "psf1", "psf2" | `tests/font/psf.luau` |
|
||||
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
|
||||
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
|
||||
| font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` |
|
||||
|
||||
@@ -530,6 +530,18 @@ local list: { Entry } = {
|
||||
return require("@formats/font/pcf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "psf",
|
||||
category = "font",
|
||||
path = "font/psf",
|
||||
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" } },
|
||||
load = function()
|
||||
return require("@formats/font/psf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ttf",
|
||||
category = "font",
|
||||
|
||||
@@ -663,6 +663,7 @@ export type BitmapStrike = {
|
||||
descent: number, -- pixels below the baseline (positive)
|
||||
glyphs: { BitmapGlyph }, -- glyph index i + 1 is font glyph i (glyph 0 = the default / .notdef glyph)
|
||||
default: number?, -- glyph index (0-based) used for unmapped code points
|
||||
map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Archive
|
||||
|
||||
@@ -109,6 +109,13 @@ function Bitmap.font(strike: Types.BitmapStrike, info: { [string]: any }?, meta:
|
||||
index[cp] = i - 1
|
||||
end
|
||||
end
|
||||
if strike.map then
|
||||
for cp, g in strike.map do
|
||||
if index[cp] == nil and g >= 0 and g < #strike.glyphs then
|
||||
index[cp] = g
|
||||
end
|
||||
end
|
||||
end
|
||||
local f = setmetatable({
|
||||
kind = "font",
|
||||
info = info or {},
|
||||
|
||||
@@ -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
|
||||
@@ -240,7 +240,7 @@ end
|
||||
-- .tar.gz) load as that inner archive, with meta.compression = the outer format. opts.unwrap = false keeps the outer
|
||||
-- one; an explicit opts.format also does. Package archives name their payload entry in meta.payload (a .deb's
|
||||
-- data.tar.xz): they load as that inner archive too, with meta.container = the outer format and meta.outer = the
|
||||
-- outer archive (its control data). A single-stream archive holding a .pcf / .psf / .bdf font loads as the font.
|
||||
-- outer archive (its control data). A single-stream archive holding a .pcf / .psf(u) / .bdf font loads as the font.
|
||||
local function unwrap(value: any, formatName: string, o: Options): any
|
||||
if o.unwrap == false or o.format ~= nil or (o._depth or 0) >= 3 then
|
||||
return value
|
||||
@@ -263,7 +263,8 @@ local function unwrap(value: any, formatName: string, o: Options): any
|
||||
end
|
||||
local category = "archive"
|
||||
local e = detect(inner, nil, "archive", nil)
|
||||
if not e and value.meta.stream and ((Input.extension(entryName) or "") == "pcf" or (Input.extension(entryName) or "") == "psf" or (Input.extension(entryName) or "") == "bdf") then
|
||||
local innerExt = Input.extension(entryName) or ""
|
||||
if not e and value.meta.stream and (innerExt == "pcf" or innerExt == "psf" or innerExt == "psfu" or innerExt == "bdf") then
|
||||
-- compressed bitmap fonts (.pcf.gz, .psf.gz, .bdf.gz: X11 and console font directories) load as the font
|
||||
e = detect(inner, entryName, "font", nil)
|
||||
category = "font"
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
-- font/psf tests: kbd / Spleen / Tamzen / Terminus / Cozette console fonts (PSF 1 and 2, with and without Unicode
|
||||
-- tables) against an independent parser (sizes, glyph bitmaps) and kbd's psfgettable (every code point -> glyph
|
||||
-- pair); our PSF 2 / PSF 1 output read back by psfgettable and the parser (fixture step) and round-tripping; an
|
||||
-- outline font written as PSF; .psfu.gz through the api; errors; the fuzz pass. Fixtures: tools/fixtures/psf.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Psf = require("@formats/font/psf")
|
||||
local Ttf = require("@formats/font/ttf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Fx = require("@tests/gen/psf")
|
||||
local Fonts = require("@tests/gen/fonts")
|
||||
|
||||
local t = T.suite("psf")
|
||||
t:eq(Psf.name, "psf", "name")
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.fonts do
|
||||
local data = buffer.fromstring(c.data)
|
||||
if c.gz then
|
||||
data = Deflate.gunzip(data, 0, buffer.len(data)) :: buffer
|
||||
end
|
||||
local font, err = Psf.decode(Bytes.reader(data))
|
||||
t:check(font, c.name .. ": " .. tostring(err))
|
||||
if font then
|
||||
t:eq(font.meta.source.version, c.version, c.name .. ": version")
|
||||
t:eq(#font.bitmap.glyphs, c.count, c.name .. ": glyph count")
|
||||
t:eq(font.meta.width, c.width, c.name .. ": width")
|
||||
t:eq(font.meta.height, c.height, c.name .. ": height")
|
||||
for _, g in c.glyphs do
|
||||
local img = font:rasterize(g.index, c.height)
|
||||
t:check(img and buffer.tostring(img.pixels) == g.pixels, c.name .. ": glyph " .. g.index)
|
||||
end
|
||||
local mismatched = 0
|
||||
for _, p in c.table do
|
||||
local gi = font:glyphIndex(p.cp)
|
||||
-- a code point on several glyphs maps to the first: the glyph images are equal or the pair is an alias
|
||||
if gi ~= p.glyph and font.meta.unicodeTable[gi + 1] == nil then
|
||||
mismatched += 1
|
||||
end
|
||||
end
|
||||
t:eq(mismatched, 0, c.name .. ": Unicode table (" .. #c.table .. " pairs)")
|
||||
t:check(c.ours2.ok, c.name .. ": our PSF 2 reads back: " .. c.ours2.detail)
|
||||
if c.ours1 then
|
||||
t:check(c.ours1.ok, c.name .. ": our PSF 1 reads back: " .. c.ours1.detail)
|
||||
end
|
||||
local back = Psf.decode(Bytes.reader(Psf.encode(font) :: buffer)) :: any
|
||||
t:check(back and #back.bitmap.glyphs == c.count and back:glyphIndex(65) == font:glyphIndex(65), c.name .. ": round trip")
|
||||
end
|
||||
t:eq(F.detect(data), "psf", c.name .. ": detect")
|
||||
if c.gz then
|
||||
local v = F.load(c.data, { name = c.name }) :: any
|
||||
t:check(v and v.kind == "font" and v.meta.compression == "gzip", c.name .. ": F.load unwraps the gzip")
|
||||
end
|
||||
if #samples < 3 then
|
||||
table.insert(samples, data)
|
||||
end
|
||||
end
|
||||
|
||||
-- an outline font as PSF 2
|
||||
local ttf = Ttf.decode(Bytes.reader(buffer.fromstring(Fonts.fonts[1].data)))
|
||||
local out, err = Psf.encode(ttf, { px = 16, chars = "AB" })
|
||||
t:check(out, "ttf -> psf: " .. tostring(err))
|
||||
local back = Psf.decode(Bytes.reader(out :: buffer)) :: any
|
||||
t:check(back and back:glyphIndex(66) == 2 and back.meta.source.version == 2, "ttf -> psf glyphs")
|
||||
|
||||
-- errors
|
||||
local function code(s: string): string?
|
||||
local _, e = Psf.decode(Bytes.reader(buffer.fromstring(s)))
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("\54\4\0\16"), Err.TRUNCATED, "psf1 without glyphs")
|
||||
t:eq(code("\114\181\74\134"), Err.TRUNCATED, "psf2 header cut")
|
||||
t:eq(code("\114\181\74\134\0\0\0\0\32\0\0\0\0\0\0\0\1\0\0\0\99\0\0\0\8\0\0\0\8\0\0\0"), Err.CORRUPT, "bad charsize")
|
||||
t:eq(code("hello"), Err.CORRUPT, "not psf")
|
||||
t:eq((select(2, Psf.encode(back, { version = 3 })) :: any).code, Err.ARG, "bad version")
|
||||
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Psf.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 30 })
|
||||
t:done()
|
||||
@@ -1,10 +1,14 @@
|
||||
-- tools/fixtures/_bitmapfonts_ours.luau: our bitmap font writers' output for FreeType to read back (run by
|
||||
-- tools/fixtures/bitmapfonts.py after it wrote tests/gen/bitmapfonts_src.luau): decodes each source font with its
|
||||
-- format and prints "<case> <hex of our BDF>" lines.
|
||||
-- tools/fixtures/_bitmapfonts_ours.luau: our bitmap font writers' output for the reference tools to read back (run by
|
||||
-- tools/fixtures/bitmapfonts.py / psf.py after they wrote the source fonts to tests/gen/<src>.luau:
|
||||
-- `luau _bitmapfonts_ours.luau -a <src> <format> [version]`): decodes each source font with its format, encodes it
|
||||
-- with <format> (default bdf) and prints "<case> <hex>" lines.
|
||||
local F = require("@formats")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Src = require("@tests/gen/bitmapfonts_src")
|
||||
|
||||
local srcName, outFormat, version = ...
|
||||
local Src = if srcName == "psf_src" then require("@tests/gen/psf_src") else require("@tests/gen/bitmapfonts_src")
|
||||
local enc = F.format(outFormat or "bdf") :: any
|
||||
|
||||
local function hex(b: buffer): string
|
||||
local t = table.create(buffer.len(b))
|
||||
@@ -21,8 +25,8 @@ for _, c in Src.fonts do
|
||||
end
|
||||
local mod = F.format(c.format) :: any
|
||||
local font = if mod then mod.decode(Bytes.reader(data)) else nil
|
||||
if font and F.format("bdf") then
|
||||
local out = (F.format("bdf") :: any).encode(font)
|
||||
if font and enc then
|
||||
local out = enc.encode(font, { version = tonumber(version) })
|
||||
if out then
|
||||
print(c.name .. " " .. hex(out))
|
||||
end
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# PSF fixtures (tools/fixtures.py): Linux console fonts from kbd (nixpkgs#kbd: PSF 2 with and without Unicode tables,
|
||||
# PSF 1 with 512 glyphs), Spleen / Tamzen / Terminus / Cozette console fonts, read from the nix store at fixture time.
|
||||
# FreeType does not read PSF: the reference is kbd's `psfgettable` (the Unicode table) and the independent parser
|
||||
# below (header and glyph bitmaps). Our PSF 2 and PSF 1 output (tools/fixtures/_bitmapfonts_ours.luau) is read back
|
||||
# by psfgettable and the parser.
|
||||
# tests/gen/psf.luau { fonts = { { name, data, gz?, version, count, width, height, glyphs = { { index, pixels } },
|
||||
# table = { { glyph, cp } }, ours2 = { ok, detail }, ours1? } } }
|
||||
import gzip, importlib.util, os, shutil, subprocess
|
||||
|
||||
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
|
||||
A = importlib.util.module_from_spec(_s)
|
||||
_s.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["tools/fixtures/_bitmapfonts_ours.luau", "src/Formats/font/psf"]
|
||||
|
||||
|
||||
def store(pkg):
|
||||
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
|
||||
|
||||
|
||||
def parse(b):
|
||||
"""(version, count, width, height, [glyph pixel bytes as 0/255]) of a PSF file"""
|
||||
if b[:4] == b"\x72\xb5\x4a\x86":
|
||||
_, hsize, flags, count, charsize, height, width = [int.from_bytes(b[4 + 4 * i:8 + 4 * i], "little") for i in range(7)]
|
||||
ver, at = 2, hsize
|
||||
else:
|
||||
mode, height = b[2], b[3]
|
||||
ver, at, width, count = 1, 4, 8, 512 if mode & 1 else 256
|
||||
stride = (width + 7) // 8
|
||||
glyphs = []
|
||||
for i in range(count):
|
||||
g = b[at + i * stride * height: at + (i + 1) * stride * height]
|
||||
px = bytearray(width * height)
|
||||
for y in range(height):
|
||||
for x in range(width):
|
||||
if g[y * stride + x // 8] >> (7 - x % 8) & 1:
|
||||
px[y * width + x] = 255
|
||||
glyphs.append(bytes(px))
|
||||
return ver, count, width, height, glyphs
|
||||
|
||||
|
||||
def table(path):
|
||||
out = A.tool(["kbd"], ["psfgettable", path]).decode()
|
||||
pairs = []
|
||||
for line in out.splitlines():
|
||||
if line.startswith("#") or not line.strip():
|
||||
continue
|
||||
parts = line.split()
|
||||
g = int(parts[0], 16)
|
||||
for p in parts[1:]:
|
||||
if p.startswith("U+") and "," not in p:
|
||||
pairs.append({"glyph": g, "cp": int(p[2:], 16)})
|
||||
return pairs
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
kbd = os.path.join(store("kbd"), "share", "consolefonts")
|
||||
items = [(os.path.join(kbd, f), f) for f in ("lat9w-16.psfu.gz", "default8x16.psfu.gz", "cp866-8x16.psf.gz", "eurlatgr.psfu.gz", "iso01-12x22.psfu.gz")]
|
||||
items += [(os.path.join(store("spleen"), "share", "consolefonts", "spleen-12x24.psfu"), "spleen-12x24.psfu"),
|
||||
(os.path.join(store("tamzen"), "share", "consolefonts", "Tamzen8x16.psf"), "Tamzen8x16.psf"),
|
||||
(os.path.join(store("terminus_font"), "share", "consolefonts", "ter-v16n.psf.gz"), "ter-v16n.psf.gz"),
|
||||
(os.path.join(store("cozette"), "share", "consolefonts", "cozette.psf"), "cozette.psf")]
|
||||
tmp = A.tmpdir()
|
||||
try:
|
||||
fonts = []
|
||||
for path, name in items:
|
||||
raw = open(path, "rb").read()
|
||||
data = gzip.decompress(raw) if name.endswith(".gz") else raw
|
||||
p = os.path.join(tmp, name.replace(".gz", ""))
|
||||
open(p, "wb").write(data)
|
||||
ver, count, width, height, glyphs = parse(data)
|
||||
sample = sorted({0, 1, 65, 97, count // 2, count - 1})
|
||||
e = {"name": name, "data": raw, "version": ver, "count": count, "width": width, "height": height,
|
||||
"glyphs": [{"index": i, "pixels": glyphs[i]} for i in sample], "table": table(p)}
|
||||
if name.endswith(".gz"):
|
||||
e["gz"] = True
|
||||
fonts.append(e)
|
||||
ctx.emit("psf_src", {"fonts": [{"name": f["name"], "format": "psf", "data": f["data"], **({"gz": True} if f.get("gz") else {})} for f in fonts]})
|
||||
subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True)
|
||||
exe = shutil.which("luau")
|
||||
base = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ours.luau"), "-a", "psf_src", "psf"]
|
||||
for ver in ("2", "1"):
|
||||
r = subprocess.run(base + [ver], capture_output=True, cwd=ctx.root)
|
||||
outs = dict(line.rsplit(" ", 1) for line in r.stdout.decode().splitlines())
|
||||
for f in fonts:
|
||||
key = "ours" + ver
|
||||
if f["name"] not in outs:
|
||||
if ver == "2" or (f["width"] <= 8):
|
||||
f[key] = {"ok": False, "detail": "no output: " + r.stderr.decode(errors="replace")[-300:]}
|
||||
continue
|
||||
data = bytes.fromhex(outs[f["name"]])
|
||||
p = os.path.join(tmp, "ours%s-%s" % (ver, f["name"]))
|
||||
open(p, "wb").write(data)
|
||||
over, ocount, ow, oh, og = parse(data)
|
||||
_, _, _, _, src = parse(gzip.decompress(f["data"]) if f.get("gz") else f["data"])
|
||||
same_glyphs = ow == f["width"] and oh == f["height"] and og[:f["count"]] == src
|
||||
same_table = sorted((x["glyph"], x["cp"]) for x in table(p)) == sorted((x["glyph"], x["cp"]) for x in f["table"])
|
||||
f[key] = {"ok": over == int(ver) and same_glyphs and same_table, "detail": "version %d, glyphs %s, table %s" % (over, same_glyphs, same_table)}
|
||||
ctx.emit("psf", {"fonts": fonts})
|
||||
finally:
|
||||
A.rmtree(tmp)
|
||||
Reference in new issue
Block a user