ws-arch2: font/eot (EOT 1.0 / 2.1 / 2.2, XOR; read via codecs/font/TrueType, write 2.1; MTX unsupported)
This commit is contained in:
1 parent
375140ece2
commit
e34e32901f
5 files changed
+377
No files matched your search
@@ -47,6 +47,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` |
|
||||
| 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 | eot | .eot | yes | yes | variants: "1.0", "2.1", "2.2" | `tests/font/eot.luau` |
|
||||
| font | fon | .fon .fnt | yes | - | bitmap: true, variants: "fnt2", "fnt3", "ne", "pe" | `tests/font/fon.luau` |
|
||||
| font | hershey | .jhf | yes | - | strokes: true | `tests/font/hershey.luau` |
|
||||
| font | pcf | .pcf | yes | - | bitmap: true | `tests/font/pcf.luau` |
|
||||
|
||||
@@ -518,6 +518,18 @@ local list: { Entry } = {
|
||||
return require("@formats/font/bmfont")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "eot",
|
||||
category = "font",
|
||||
path = "font/eot",
|
||||
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" } },
|
||||
load = function()
|
||||
return require("@formats/font/eot")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "fon",
|
||||
category = "font",
|
||||
|
||||
@@ -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("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Text = require("@formats/codecs/text/Text")
|
||||
local TrueType = require("@formats/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 = TrueType.tables(data, 0, 0, buffer.len(data)) or {}
|
||||
local function tab(tagName: string): Bytes.Reader?
|
||||
local t = 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
|
||||
@@ -0,0 +1,55 @@
|
||||
-- font/eot tests: EOT 1.0 / 2.1 / 2.1 XOR / 2.2 files around DejaVu Sans Mono (TrueType) and Source Sans 3 (CFF) give
|
||||
-- the header fields and the inner font (units per em, glyph count, cmap glyph ids and advances from fontTools); our
|
||||
-- EOT writer round-trips (same font bytes, header from the font's tables), XOR too; MTX is unsupported; errors; the fuzz
|
||||
-- pass. Fixtures: tools/fixtures/eot.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Eot = require("@formats/font/eot")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Fx = require("@tests/gen/eot")
|
||||
|
||||
local t = T.suite("eot")
|
||||
t:eq(Eot.name, "eot", "name")
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
local font, err = Eot.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(font, c.name .. ": " .. tostring(err))
|
||||
if font then
|
||||
local h = font.meta.eot
|
||||
t:eq(h.version, c.version, c.name .. ": version")
|
||||
t:eq(h.familyName, c.family, c.name .. ": family")
|
||||
t:eq(h.styleName, c.style, c.name .. ": style")
|
||||
t:eq(h.fullName, c.fullName, c.name .. ": full name")
|
||||
t:eq(h.weight, c.weight, c.name .. ": weight")
|
||||
t:eq(h.fsType, c.fsType, c.name .. ": fsType")
|
||||
t:eq(font.unitsPerEm, c.upem, c.name .. ": units per em")
|
||||
t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": glyph count")
|
||||
t:eq(Crc32.of(font.meta.fontData), c.fontCrc, c.name .. ": font data")
|
||||
for _, g in c.glyphs do
|
||||
t:eq(font:glyphIndex(g.cp), g.gid, c.name .. ": cmap " .. g.cp)
|
||||
t:eq(font:advance(g.gid), g.advance, c.name .. ": advance " .. g.cp)
|
||||
end
|
||||
-- our writer
|
||||
for _, xor in { false, true } do
|
||||
local out, werr = Eot.encode(font, { xor = xor })
|
||||
t:check(out, c.name .. ": encode: " .. tostring(werr))
|
||||
local back = out and Eot.decode(Bytes.reader(out)) :: any
|
||||
t:check(back and Crc32.of(back.meta.fontData) == c.fontCrc and back.meta.eot.weight == c.weight and back.meta.eot.familyName == font.info.family, c.name .. ": round trip (xor " .. tostring(xor) .. ")")
|
||||
end
|
||||
end
|
||||
t:eq(F.detect(c.data), "eot", c.name .. ": detect")
|
||||
table.insert(samples, string.sub(c.data, 1, 3000))
|
||||
end
|
||||
local _, merr = Eot.decode(Bytes.reader(buffer.fromstring(Fx.mtx)))
|
||||
t:eq(merr and merr.code, Err.UNSUPPORTED, "MTX compressed")
|
||||
local _, serr = Eot.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.cases[1].data, 1, 50))))
|
||||
t:eq(serr and serr.code, Err.TRUNCATED, "cut header")
|
||||
t:eq((select(2, Eot.encode({}))) and (select(2, Eot.encode({})) :: any).code, Err.ARG, "encode a non-font")
|
||||
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Eot.decode(Bytes.reader(b))
|
||||
end, samples, { mutations = 20 })
|
||||
t:done()
|
||||
@@ -0,0 +1,76 @@
|
||||
# EOT fixtures (tools/fixtures.py): no EOT tool is packaged in nixpkgs, so Embedded OpenType files are built here per
|
||||
# the W3C EOT submission (versions 1.0, 2.1 plain and XOR-obfuscated, 2.2 with an empty signature and EUDC data, one
|
||||
# MTX-flagged file) around TrueType / CFF fonts (DejaVu Sans Mono from nixpkgs#dejavu_fonts, Source Sans 3 OTF from
|
||||
# nixpkgs#source-sans); the header fields come from fontTools, and the inner font's facts (units per em, glyph count,
|
||||
# cmap glyph ids, advances) from fontTools too.
|
||||
# tests/gen/eot.luau { cases = { { name, data, version, xor, family, style, fullName, weight, fsType, upem,
|
||||
# numGlyphs, glyphs = { { cp, gid, advance } } } }, mtx }
|
||||
import json, os, struct, subprocess
|
||||
|
||||
CODE = r'''
|
||||
import json, sys
|
||||
from fontTools.ttLib import TTFont
|
||||
out = []
|
||||
for p in json.load(sys.stdin):
|
||||
f = TTFont(p)
|
||||
os2, head, name = f["OS/2"], f["head"], f["name"]
|
||||
cmap = f.getBestCmap()
|
||||
glyphs = []
|
||||
order = f.getGlyphOrder()
|
||||
for cp in (65, 97, 48, 0x20AC, 0x3A9):
|
||||
if cp in cmap:
|
||||
g = cmap[cp]
|
||||
glyphs.append({"cp": cp, "gid": order.index(g), "advance": f["hmtx"][g][0]})
|
||||
out.append({"panose": bytes([getattr(os2.panose, k) for k in ("bFamilyType", "bSerifStyle", "bWeight", "bProportion", "bContrast", "bStrokeVariation", "bArmStyle", "bLetterForm", "bMidline", "bXHeight")]).hex(),
|
||||
"weight": os2.usWeightClass, "fsType": os2.fsType, "italic": os2.fsSelection & 1,
|
||||
"ranges": [os2.ulUnicodeRange1, os2.ulUnicodeRange2, os2.ulUnicodeRange3, os2.ulUnicodeRange4],
|
||||
"codepages": [getattr(os2, "ulCodePageRange1", 0), getattr(os2, "ulCodePageRange2", 0)],
|
||||
"checksum": head.checkSumAdjustment, "upem": head.unitsPerEm, "numGlyphs": len(order),
|
||||
"family": name.getDebugName(1) or "", "style": name.getDebugName(2) or "", "version": name.getDebugName(5) or "",
|
||||
"full": name.getDebugName(4) or "", "glyphs": glyphs})
|
||||
print(json.dumps(out))
|
||||
'''
|
||||
|
||||
|
||||
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 utf16(s):
|
||||
return s.encode("utf-16-le")
|
||||
|
||||
|
||||
def eot(data, facts, version, xor=False, flags=0):
|
||||
hdr = struct.pack("<IIII", 0, len(data), version, flags | (0x10000000 if xor else 0))
|
||||
hdr += bytes.fromhex(facts["panose"]) + struct.pack("<BBIHH", 1, facts["italic"], facts["weight"], facts["fsType"], 0x504C)
|
||||
hdr += struct.pack("<4I", *facts["ranges"]) + struct.pack("<2I", *facts["codepages"]) + struct.pack("<I", facts["checksum"]) + b"\0" * 16
|
||||
for s in (facts["family"], facts["style"], facts["version"], facts["full"]):
|
||||
u = utf16(s)
|
||||
hdr += struct.pack("<HH", 0, len(u)) + u
|
||||
if version >= 0x00020001:
|
||||
u = utf16("https://example.com/")
|
||||
hdr += struct.pack("<HH", 0, len(u)) + u
|
||||
if version == 0x00020002:
|
||||
hdr += struct.pack("<IIHH", 0x12345678, 0, 0, 0) + struct.pack("<II", 0, 4) + b"EUDC"
|
||||
body = bytes(b ^ 0x50 for b in data) if xor else data
|
||||
out = hdr + body
|
||||
return struct.pack("<I", len(out)) + out[4:]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dejavu = os.path.join(store("dejavu_fonts"), "share", "fonts", "truetype", "DejaVuSansMono.ttf")
|
||||
otf = os.path.join(store("source-sans"), "share", "fonts", "opentype", "SourceSans3-Regular.otf")
|
||||
facts = json.loads(ctx.python(["fonttools"], CODE, input=json.dumps([dejavu, otf]).encode()))
|
||||
cases = []
|
||||
for path, f in zip((dejavu, otf), facts):
|
||||
data = open(path, "rb").read()
|
||||
base = os.path.basename(path)
|
||||
for label, ver, xor in (("1.0", 0x00010000, False), ("2.1", 0x00020001, False), ("2.1 xor", 0x00020001, True), ("2.2", 0x00020002, False)):
|
||||
if base.endswith(".otf") and label != "2.1":
|
||||
continue
|
||||
cases.append({"name": "%s %s" % (base, label), "data": eot(data, f, ver, xor), "version": ver, "xor": xor,
|
||||
"family": f["family"], "style": f["style"], "fullName": f["full"], "weight": f["weight"],
|
||||
"fsType": f["fsType"], "upem": f["upem"], "numGlyphs": f["numGlyphs"], "glyphs": f["glyphs"],
|
||||
"fontCrc": __import__("zlib").crc32(data)})
|
||||
mtx = eot(open(dejavu, "rb").read()[:1000], facts[0], 0x00020001, flags=0x4)
|
||||
ctx.emit("eot", {"cases": cases, "mtx": mtx})
|
||||
Reference in new issue
Block a user