ws-arch2: wip type1 (charstring interpreter, PFB / PFA parsing) and codecs/font/GlyphNames (AGLFN + StandardEncoding)

This commit is contained in:
4DBug committed 2026-10-31 15:21:08 -05:00
1 parent b6b7999a63
commit e3c2ceaa5e
5 files changed
+836

No files matched your search

+154
View File
@@ -0,0 +1,154 @@
--!strict
-- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a
-- cmap, PCF / BDF glyph names): the Adobe Glyph List For New Fonts (AGLFN 1.7, Adobe, BSD-3-Clause:
-- licenses/agl-LICENSE.txt; the f-ligatures and dotlessj added), the uniXXXX / uXXXX[XX] conventions and
-- name.suffix variants ("a.sc" -> a) per the AGL specification; and Adobe StandardEncoding (code -> glyph name).
-- Generated once from fontTools.agl / fontTools.encodings.StandardEncoding.
--
-- GlyphNames.unicode("Aacute") -> 0xC1 GlyphNames.unicode("uni20AC") -> 0x20AC (nil when unknown)
-- GlyphNames.STANDARD[65] -> "A" (StandardEncoding, codes 0..255; nil for .notdef)
local GlyphNames = {}
-- AGLFN: "name hex" pairs
local AGL = "" ..
"A 41 AE C6 AEacute 1FC Aacute C1 Abreve 102 Acircumflex C2 Adieresis C4 Agrave C0 Alpha 391 " ..
"Alphatonos 386 Amacron 100 Aogonek 104 Aring C5 Aringacute 1FA Atilde C3 B 42 Beta 392 C 43 Cacute " ..
"106 Ccaron 10C Ccedilla C7 Ccircumflex 108 Cdotaccent 10A Chi 3A7 D 44 Dcaron 10E Dcroat 110 Delta " ..
"2206 E 45 Eacute C9 Ebreve 114 Ecaron 11A Ecircumflex CA Edieresis CB Edotaccent 116 Egrave C8 " ..
"Emacron 112 Eng 14A Eogonek 118 Epsilon 395 Epsilontonos 388 Eta 397 Etatonos 389 Eth D0 Euro 20AC " ..
"F 46 G 47 Gamma 393 Gbreve 11E Gcaron 1E6 Gcircumflex 11C Gdotaccent 120 H 48 H18533 25CF H18543 " ..
"25AA H18551 25AB H22073 25A1 Hbar 126 Hcircumflex 124 I 49 IJ 132 Iacute CD Ibreve 12C Icircumflex " ..
"CE Idieresis CF Idotaccent 130 Ifraktur 2111 Igrave CC Imacron 12A Iogonek 12E Iota 399 " ..
"Iotadieresis 3AA Iotatonos 38A Itilde 128 J 4A Jcircumflex 134 K 4B Kappa 39A L 4C Lacute 139 " ..
"Lambda 39B Lcaron 13D Ldot 13F Lslash 141 M 4D Mu 39C N 4E Nacute 143 Ncaron 147 Ntilde D1 Nu 39D O " ..
"4F OE 152 Oacute D3 Obreve 14E Ocircumflex D4 Odieresis D6 Ograve D2 Ohorn 1A0 Ohungarumlaut 150 " ..
"Omacron 14C Omega 2126 Omegatonos 38F Omicron 39F Omicrontonos 38C Oslash D8 Oslashacute 1FE Otilde " ..
"D5 P 50 Phi 3A6 Pi 3A0 Psi 3A8 Q 51 R 52 Racute 154 Rcaron 158 Rfraktur 211C Rho 3A1 S 53 SF010000 " ..
"250C SF020000 2514 SF030000 2510 SF040000 2518 SF050000 253C SF060000 252C SF070000 2534 SF080000 " ..
"251C SF090000 2524 SF100000 2500 SF110000 2502 SF190000 2561 SF200000 2562 SF210000 2556 SF220000 " ..
"2555 SF230000 2563 SF240000 2551 SF250000 2557 SF260000 255D SF270000 255C SF280000 255B SF360000 " ..
"255E SF370000 255F SF380000 255A SF390000 2554 SF400000 2569 SF410000 2566 SF420000 2560 SF430000 " ..
"2550 SF440000 256C SF450000 2567 SF460000 2568 SF470000 2564 SF480000 2565 SF490000 2559 SF500000 " ..
"2558 SF510000 2552 SF520000 2553 SF530000 256B SF540000 256A Sacute 15A Scaron 160 Scedilla 15E " ..
"Scircumflex 15C Sigma 3A3 T 54 Tau 3A4 Tbar 166 Tcaron 164 Theta 398 Thorn DE U 55 Uacute DA Ubreve " ..
"16C Ucircumflex DB Udieresis DC Ugrave D9 Uhorn 1AF Uhungarumlaut 170 Umacron 16A Uogonek 172 " ..
"Upsilon 3A5 Upsilon1 3D2 Upsilondieresis 3AB Upsilontonos 38E Uring 16E Utilde 168 V 56 W 57 Wacute " ..
"1E82 Wcircumflex 174 Wdieresis 1E84 Wgrave 1E80 X 58 Xi 39E Y 59 Yacute DD Ycircumflex 176 " ..
"Ydieresis 178 Ygrave 1EF2 Z 5A Zacute 179 Zcaron 17D Zdotaccent 17B Zeta 396 a 61 aacute E1 abreve " ..
"103 acircumflex E2 acute B4 acutecomb 301 adieresis E4 ae E6 aeacute 1FD agrave E0 aleph 2135 alpha " ..
"3B1 alphatonos 3AC amacron 101 ampersand 26 angle 2220 angleleft 2329 angleright 232A anoteleia 387 " ..
"aogonek 105 approxequal 2248 aring E5 aringacute 1FB arrowboth 2194 arrowdblboth 21D4 arrowdbldown " ..
"21D3 arrowdblleft 21D0 arrowdblright 21D2 arrowdblup 21D1 arrowdown 2193 arrowleft 2190 arrowright " ..
"2192 arrowup 2191 arrowupdn 2195 arrowupdnbse 21A8 asciicircum 5E asciitilde 7E asterisk 2A " ..
"asteriskmath 2217 at 40 atilde E3 b 62 backslash 5C bar 7C beta 3B2 block 2588 braceleft 7B " ..
"braceright 7D bracketleft 5B bracketright 5D breve 2D8 brokenbar A6 bullet 2022 c 63 cacute 107 " ..
"caron 2C7 carriagereturn 21B5 ccaron 10D ccedilla E7 ccircumflex 109 cdotaccent 10B cedilla B8 cent " ..
"A2 chi 3C7 circle 25CB circlemultiply 2297 circleplus 2295 circumflex 2C6 club 2663 colon 3A " ..
"colonmonetary 20A1 comma 2C congruent 2245 copyright A9 currency A4 d 64 dagger 2020 daggerdbl 2021 " ..
"dcaron 10F dcroat 111 degree B0 delta 3B4 diamond 2666 dieresis A8 dieresistonos 385 divide F7 " ..
"dkshade 2593 dnblock 2584 dollar 24 dong 20AB dotaccent 2D9 dotbelowcomb 323 dotlessi 131 dotlessj " ..
"237 dotmath 22C5 e 65 eacute E9 ebreve 115 ecaron 11B ecircumflex EA edieresis EB edotaccent 117 " ..
"egrave E8 eight 38 element 2208 ellipsis 2026 emacron 113 emdash 2014 emptyset 2205 endash 2013 eng " ..
"14B eogonek 119 epsilon 3B5 epsilontonos 3AD equal 3D equivalence 2261 estimated 212E eta 3B7 " ..
"etatonos 3AE eth F0 exclam 21 exclamdbl 203C exclamdown A1 existential 2203 f 66 female 2640 ff " ..
"FB00 ffi FB03 ffl FB04 fi FB01 figuredash 2012 filledbox 25A0 filledrect 25AC five 35 fiveeighths " ..
"215D fl FB02 florin 192 four 34 fraction 2044 franc 20A3 g 67 gamma 3B3 gbreve 11F gcaron 1E7 " ..
"gcircumflex 11D gdotaccent 121 germandbls DF gradient 2207 grave 60 gravecomb 300 greater 3E " ..
"greaterequal 2265 guillemotleft AB guillemotright BB guilsinglleft 2039 guilsinglright 203A h 68 " ..
"hbar 127 hcircumflex 125 heart 2665 hookabovecomb 309 house 2302 hungarumlaut 2DD hyphen 2D i 69 " ..
"iacute ED ibreve 12D icircumflex EE idieresis EF igrave EC ij 133 imacron 12B infinity 221E " ..
"integral 222B integralbt 2321 integraltp 2320 intersection 2229 invbullet 25D8 invcircle 25D9 " ..
"invsmileface 263B iogonek 12F iota 3B9 iotadieresis 3CA iotadieresistonos 390 iotatonos 3AF itilde " ..
"129 j 6A jcircumflex 135 k 6B kappa 3BA kgreenlandic 138 l 6C lacute 13A lambda 3BB lcaron 13E ldot " ..
"140 less 3C lessequal 2264 lfblock 258C lira 20A4 logicaland 2227 logicalnot AC logicalor 2228 " ..
"longs 17F lozenge 25CA lslash 142 ltshade 2591 m 6D macron AF male 2642 minus 2212 minute 2032 mu " ..
"B5 multiply D7 musicalnote 266A musicalnotedbl 266B n 6E nacute 144 napostrophe 149 ncaron 148 nine " ..
"39 notelement 2209 notequal 2260 notsubset 2284 ntilde F1 nu 3BD numbersign 23 o 6F oacute F3 " ..
"obreve 14F ocircumflex F4 odieresis F6 oe 153 ogonek 2DB ograve F2 ohorn 1A1 ohungarumlaut 151 " ..
"omacron 14D omega 3C9 omega1 3D6 omegatonos 3CE omicron 3BF omicrontonos 3CC one 31 onedotenleader " ..
"2024 oneeighth 215B onehalf BD onequarter BC onethird 2153 openbullet 25E6 ordfeminine AA " ..
"ordmasculine BA orthogonal 221F oslash F8 oslashacute 1FF otilde F5 p 70 paragraph B6 parenleft 28 " ..
"parenright 29 partialdiff 2202 percent 25 period 2E periodcentered B7 perpendicular 22A5 " ..
"perthousand 2030 peseta 20A7 phi 3C6 phi1 3D5 pi 3C0 plus 2B plusminus B1 prescription 211E product " ..
"220F propersubset 2282 propersuperset 2283 proportional 221D psi 3C8 q 71 question 3F questiondown " ..
"BF quotedbl 22 quotedblbase 201E quotedblleft 201C quotedblright 201D quoteleft 2018 quotereversed " ..
"201B quoteright 2019 quotesinglbase 201A quotesingle 27 r 72 racute 155 radical 221A rcaron 159 " ..
"reflexsubset 2286 reflexsuperset 2287 registered AE revlogicalnot 2310 rho 3C1 ring 2DA rtblock " ..
"2590 s 73 sacute 15B scaron 161 scedilla 15F scircumflex 15D second 2033 section A7 semicolon 3B " ..
"seven 37 seveneighths 215E shade 2592 sigma 3C3 sigma1 3C2 similar 223C six 36 slash 2F smileface " ..
"263A space 20 spade 2660 sterling A3 suchthat 220B summation 2211 sun 263C t 74 tau 3C4 tbar 167 " ..
"tcaron 165 therefore 2234 theta 3B8 theta1 3D1 thorn FE three 33 threeeighths 215C threequarters BE " ..
"tilde 2DC tildecomb 303 tonos 384 trademark 2122 triagdn 25BC triaglf 25C4 triagrt 25BA triagup " ..
"25B2 two 32 twodotenleader 2025 twothirds 2154 u 75 uacute FA ubreve 16D ucircumflex FB udieresis " ..
"FC ugrave F9 uhorn 1B0 uhungarumlaut 171 umacron 16B underscore 5F underscoredbl 2017 union 222A " ..
"universal 2200 uogonek 173 upblock 2580 upsilon 3C5 upsilondieresis 3CB upsilondieresistonos 3B0 " ..
"upsilontonos 3CD uring 16F utilde 169 v 76 w 77 wacute 1E83 wcircumflex 175 wdieresis 1E85 " ..
"weierstrass 2118 wgrave 1E81 x 78 xi 3BE y 79 yacute FD ycircumflex 177 ydieresis FF yen A5 ygrave " ..
"1EF3 z 7A zacute 17A zcaron 17E zdotaccent 17C zero 30 zeta 3B6 " ..
""
-- StandardEncoding: 256 names, "-" = .notdef
local STD = "" ..
"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - space exclam quotedbl numbersign " ..
"dollar percent ampersand quoteright parenleft parenright asterisk plus comma hyphen period slash " ..
"zero one two three four five six seven eight nine colon semicolon less equal greater question at A " ..
"B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft backslash bracketright asciicircum " ..
"underscore quoteleft a b c d e f g h i j k l m n o p q r s t u v w x y z braceleft bar braceright " ..
"asciitilde - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - exclamdown cent " ..
"sterling fraction yen florin section currency quotesingle quotedblleft guillemotleft guilsinglleft " ..
"guilsinglright fi fl - endash dagger daggerdbl periodcentered - paragraph bullet quotesinglbase " ..
"quotedblbase quotedblright guillemotright ellipsis perthousand - questiondown - grave acute " ..
"circumflex tilde macron breve dotaccent dieresis - ring cedilla - hungarumlaut ogonek caron emdash " ..
"- - - - - - - - - - - - - - - - AE - ordfeminine - - - - Lslash Oslash OE ordmasculine - - - - - ae " ..
"- - - dotlessi - - lslash oslash oe germandbls - - - - " ..
""
local byName: { [string]: number }? = nil
local function load(): { [string]: number }
local t: { [string]: number } = {}
for name, hex in string.gmatch(AGL, "(%S+) (%x+)") do
t[name] = tonumber(hex, 16) :: number
end
byName = t
return t
end
local STANDARD: { [number]: string } = {}
do
local i = 0
for name in string.gmatch(STD, "%S+") do
if name ~= "-" then
STANDARD[i] = name
end
i += 1
end
end
GlyphNames.STANDARD = STANDARD
-- unicode(name) -> the code point of a glyph name (the first one for ligature names like "f_i"), or nil
function GlyphNames.unicode(name: string): number?
local base = string.match(name, "^([^%.]+)") or name
local t = byName or load()
local v = t[base]
if v then
return v
end
local hex = string.match(base, "^uni(%x%x%x%x)")
if hex then
local c = tonumber(hex, 16) :: number
return if c >= 0xD800 and c < 0xE000 then nil else c
end
hex = string.match(base, "^u(%x%x%x%x%x?%x?)$")
if hex then
local c = tonumber(hex, 16) :: number
return if c > 0x10FFFF or (c >= 0xD800 and c < 0xE000) then nil else c
end
local first = string.match(base, "^([^_]+)_")
if first then
return GlyphNames.unicode(first)
end
return nil
end
return GlyphNames
+284
View File
@@ -0,0 +1,284 @@
--!strict
-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted
-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side
-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div,
-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement;
-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes,
-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the
-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops).
local Charstring = {}
export type Result = { cmds: { any }, advance: number, sbx: number }
-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result
export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? }
local readu8 = buffer.readu8
function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
local cmds: { any } = {}
local stack: { number } = {}
local sp = 0
local ps: { number } = {} -- the PostScript stack callothersubr / pop use
local x, y = 0, 0
local advance, sbx = 0, 0
local open = false
local flex = false
local flexPts: { number } = {}
local budget = 200000
local finished = false
local function push(v: number)
if sp < 48 then
sp += 1
stack[sp] = v
end
end
local function arg(i: number): number
return stack[i] or 0
end
local function close()
if open then
table.insert(cmds, { op = "close" })
open = false
end
end
local function moveTo(dx: number, dy: number)
x += dx
y += dy
if flex then
table.insert(flexPts, x)
table.insert(flexPts, y)
return
end
close()
local c: any = { op = "moveTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
end
local function ensureOpen()
if not open then
-- a drawing operator without a moveto starts at the current point
local c: any = { op = "moveTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
open = true
end
end
local function lineTo(dx: number, dy: number)
local first = not open
ensureOpen()
local _ = first
x += dx
y += dy
local c: any = { op = "lineTo" }
c[1], c[2] = x, y
table.insert(cmds, c)
end
local function curveTo(a: number, b: number, c: number, d: number, e: number, f: number)
ensureOpen()
local x1, y1 = x + a, y + b
local x2, y2 = x1 + c, y1 + d
x, y = x2 + e, y2 + f
local cmd: any = { op = "cubicTo" }
cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = x1, y1, x2, y2, x, y
table.insert(cmds, cmd)
end
local function exec(b: buffer, depth: number): string?
if depth > 10 then
return "subroutines nested too deep"
end
local n = buffer.len(b)
local p = 0
while p < n do
budget -= 1
if budget <= 0 then
return "operation budget exceeded"
end
local v = readu8(b, p)
p += 1
if v >= 32 then
if v <= 246 then
push(v - 139)
elseif v <= 250 then
if p >= n then
return "truncated number"
end
push((v - 247) * 256 + readu8(b, p) + 108)
p += 1
elseif v <= 254 then
if p >= n then
return "truncated number"
end
push(-(v - 251) * 256 - readu8(b, p) - 108)
p += 1
else
if p + 4 > n then
return "truncated number"
end
local u = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3)
push(if u >= 0x80000000 then u - 0x100000000 else u)
p += 4
end
continue
end
local op = v
if op == 12 then
if p >= n then
return "truncated escape"
end
op = 1200 + readu8(b, p)
p += 1
end
if op == 13 then -- hsbw
sbx, advance = arg(1), arg(2)
x, y = sbx, 0
sp = 0
elseif op == 1207 then -- sbw
sbx, advance = arg(1), arg(3)
x, y = arg(1), arg(2)
sp = 0
elseif op == 21 then
moveTo(arg(1), arg(2))
sp = 0
elseif op == 22 then
moveTo(arg(1), 0)
sp = 0
elseif op == 4 then
moveTo(0, arg(1))
sp = 0
elseif op == 5 then
lineTo(arg(1), arg(2))
sp = 0
elseif op == 6 then
lineTo(arg(1), 0)
sp = 0
elseif op == 7 then
lineTo(0, arg(1))
sp = 0
elseif op == 8 then
curveTo(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6))
sp = 0
elseif op == 30 then -- vhcurveto
curveTo(0, arg(1), arg(2), arg(3), arg(4), 0)
sp = 0
elseif op == 31 then -- hvcurveto
curveTo(arg(1), 0, arg(2), arg(3), 0, arg(4))
sp = 0
elseif op == 9 then
close()
sp = 0
elseif op == 10 then -- callsubr
local idx = arg(sp)
sp = math.max(0, sp - 1)
local sub = ctx.subrs[idx + 1]
if not sub then
return "call of a missing subroutine " .. idx
end
local err = exec(sub, depth + 1)
if err or finished then
return err
end
elseif op == 11 then -- return
return nil
elseif op == 14 then -- endchar
close()
finished = true
return nil
elseif op == 1212 then -- div
if sp >= 2 then
local d = stack[sp]
stack[sp - 1] = if d ~= 0 then stack[sp - 1] / d else 0
sp -= 1
end
elseif op == 1216 then -- callothersubr: args... n othersubr#
local num = arg(sp)
local count = arg(sp - 1)
sp = math.max(0, sp - 2)
count = math.clamp(count, 0, sp)
local args = {}
for i = 1, count do
args[i] = stack[sp - count + i]
end
sp -= count
if num == 1 then
flex = true
table.clear(flexPts)
elseif num == 2 then
-- a flex point: the rmoveto before it already recorded the point
elseif num == 0 and flex then
flex = false
-- flexPts: the reference point, then 6 control / end points
local f = flexPts
if #f >= 14 then
-- restore the current point to before the flex sequence's moves
local function curve(i: number)
ensureOpen()
local cmd: any = { op = "cubicTo" }
cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6] = f[i], f[i + 1], f[i + 2], f[i + 3], f[i + 4], f[i + 5]
table.insert(cmds, cmd)
end
curve(3)
curve(9)
x, y = f[13], f[14]
end
table.clear(ps)
table.insert(ps, args[3] or y)
table.insert(ps, args[2] or x)
elseif num == 3 then
table.clear(ps)
table.insert(ps, 3)
else
table.clear(ps)
for i = #args, 1, -1 do
table.insert(ps, args[i])
end
end
elseif op == 1217 then -- pop
push(table.remove(ps) or 0)
elseif op == 1233 then -- setcurrentpoint
x, y = arg(1), arg(2)
sp = 0
elseif op == 1206 then -- seac: asb adx ady bchar achar
local asb, adx, ady, bchar, achar = arg(1), arg(2), arg(3), arg(4), arg(5)
sp = 0
if not ctx.seac then
return "seac without base glyphs"
end
local base = ctx.seac(bchar)
local accent = ctx.seac(achar)
if not base or not accent then
return "seac of a missing glyph"
end
close()
for _, c in base.cmds do
table.insert(cmds, c)
end
local ox, oy = adx - asb, ady
for _, c in accent.cmds do
local t: any = { op = c.op }
for i = 1, #c, 2 do
t[i], t[i + 1] = c[i] + ox, c[i + 1] + oy
end
table.insert(cmds, t)
end
finished = true
return nil
elseif op == 1 or op == 3 or op == 1200 or op == 1201 or op == 1202 then
sp = 0 -- hints
else
sp = 0 -- unknown operators clear the stack
end
end
return nil
end
local err = exec(cs, 0)
if err then
return nil, err
end
close()
return { cmds = cmds, advance = advance, sbx = sbx }, nil
end
return Charstring
+365
View File
@@ -0,0 +1,365 @@
--!strict
-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the
-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox,
-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV,
-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring
-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph
-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through
-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple
-- Master and CID-keyed (Type 9 / 11) fonts, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Raster = require("@formats/codecs/image/Raster")
local GlyphNames = require("@formats/codecs/font/GlyphNames")
local Charstring = require("@formats/font/type1/Charstring")
-- ------------------------------------------------------------------------------------------------ contract
local Type1 = {
name = "type1",
category = "font",
extensions = { "pfb", "pfa", "t1" },
mime = { "application/x-font-type1" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" },
caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } },
}
export type DecodeOptions = { maxGlyphs: number? } -- default 65536
-- ------------------------------------------------------------------------------------------------ sniff
function Type1.sniff(r: Bytes.Reader): number
local h = r:peek(64)
if string.sub(h, 1, 2) == "\128\1" then
h = string.sub(h, 7)
end
if string.sub(h, 1, 14) == "%!PS-AdobeFont" or string.sub(h, 1, 10) == "%!FontType" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA
local function sections(r: Bytes.Reader): (string?, buffer?, string?)
local b = r.buf
local n = r:size()
if r:peek(2) == "\128\1" then
local clear, bin = {}, Bytes.writer()
local p = 0
while p + 2 <= n do
local h = r:sub(p, 6)
local m, ty, len = h:u8(), h:u8(), h:u32le()
if m ~= 128 then
return nil, nil, "bad PFB segment marker"
end
if ty == 3 then
break
end
if h.err or p + 6 + len > n then
return nil, nil, "truncated PFB segment"
end
if ty == 1 then
if #clear == 0 or bin:tell() == 0 then
table.insert(clear, buffer.readstring(b, r.base + p + 6, len))
end
elseif ty == 2 then
bin:bytes(r:sub(p + 6, len):bytes(len))
else
return nil, nil, "bad PFB segment type " .. ty
end
p += 6 + len
end
return table.concat(clear), bin:finish(), nil
end
local text = buffer.readstring(b, r.base, n)
local e = string.find(text, "eexec", 1, true)
if not e then
return nil, nil, "no eexec section"
end
local clear = string.sub(text, 1, e + 4)
-- PFA: hex digits after eexec, up to the zeros trailer (or binary if not hex)
local rest = string.sub(text, e + 5)
local hexPart = string.match(rest, "^%s*([%x%s]+)")
if hexPart and #hexPart > 8 then
local digits = string.gsub(hexPart, "%s", "")
local out = buffer.create(#digits // 2)
for i = 0, #digits // 2 - 1 do
buffer.writeu8(out, i, tonumber(string.sub(digits, i * 2 + 1, i * 2 + 2), 16) or 0)
end
return clear, out, nil
end
local s = string.match(rest, "^[\r\n]*(.*)$") or rest
return clear, buffer.fromstring(s), nil
end
local function decrypt(src: buffer, off: number, n: number, key: number, skip: number): buffer
local r = key
local out = buffer.create(math.max(0, n - skip))
for i = 0, n - 1 do
local c = buffer.readu8(src, off + i)
local p = bit32.bxor(c, bit32.rshift(r, 8))
r = ((c + r) * 52845 + 22719) % 65536
if i >= skip then
buffer.writeu8(out, i - skip, p)
end
end
return out
end
-- binary strings of the private dictionary: "<len> RD <bytes>" / "<len> -| <bytes>"
local function binaryAt(priv: buffer, p: number, len: number): buffer?
if p < 0 or len < 0 or p + len > buffer.len(priv) then
return nil
end
local out = buffer.create(len)
buffer.copy(out, 0, priv, p, len)
return out
end
local function psString(clear: string, key: string): string?
return string.match(clear, "/" .. key .. "%s*%((.-)%)%s*[rd]") or string.match(clear, "/" .. key .. "%s*%((.-)%)")
end
local Face = {}
Face.__index = Face
function Face.glyphIndex(self: any, cp: number): number
return self._cmap[cp] or 0
end
function Face.advance(self: any, g: number): number
local res = self:_run(g)
return if res then res.advance else 0
end
function Face.kern(_self: any, _a: number, _b: number): number
return 0
end
function Face._run(self: any, g: number): Charstring.Result?
local cached = self._cache[g]
if cached ~= nil then
return if cached == false then nil else cached
end
local cs = self._charstrings[g + 1]
if not cs then
return nil
end
local res = Charstring.run(cs, self._ctx)
self._cache[g] = res or false
return res
end
function Face.outline(self: any, g: number): { any }?
local res = self:_run(g)
if not res then
return nil
end
local out = table.create(#res.cmds)
for i, c in res.cmds do
out[i] = table.clone(c)
end
return out
end
function Face.rasterize(self: any, g: number, px: number): Types.Image?
if type(px) ~= "number" or not (px > 0) or px > 4096 then
return nil
end
local res = self:_run(g)
if not res then
return nil
end
local s = px / self.unitsPerEm
local m = Raster.mask(res.cmds, { transform = { s, 0, 0, -s, 0, 0 }, maxPixels = 2 ^ 24 })
local img
if m then
img = Types.Image.new(m.width, m.height, "alpha8")
buffer.copy(img.pixels, 0, m.coverage)
img.meta.left, img.meta.top = m.x, -m.y
else
img = Types.Image.new(0, 0, "alpha8")
img.meta.left, img.meta.top = 0, 0
end
img.meta.advance = res.advance * s
img.meta.glyph = g
return img
end
function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxGlyphs = o.maxGlyphs or 65536
local clear, enc, serr = sections(r)
if not clear or not enc then
return nil, Err.from(serr)
end
if not string.find(clear, "eexec", 1, true) and buffer.len(enc) == 0 then
return nil, Err.new(Err.CORRUPT, "no eexec section")
end
if buffer.len(enc) < 4 then
return nil, Err.new(Err.TRUNCATED, "eexec section too short")
end
local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4)
local ptext = buffer.tostring(priv)
local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4
-- Subrs
local subrs: { buffer } = {}
local function charstring(p: number, len: number): buffer?
local raw = binaryAt(priv, p, len)
if not raw then
return nil
end
if lenIV < 0 then
return raw
end
return decrypt(raw, 0, len, 4330, lenIV)
end
local sAt = string.find(ptext, "/Subrs", 1, true)
local csAt = string.find(ptext, "/CharStrings", 1, true)
if not csAt then
return nil, Err.new(Err.CORRUPT, "no CharStrings")
end
if sAt and sAt < csAt then
local p = sAt
while true do
local s, e, idx, len = string.find(ptext, "dup%s+(%d+)%s+(%d+)%s+%S+ ", p)
if not s or s > csAt then
break
end
local i, n = tonumber(idx) :: number, tonumber(len) :: number
if i > 65535 then
return nil, Err.new(Err.LIMIT, "too many subroutines")
end
local cs = charstring(e, n)
if not cs then
return nil, Err.new(Err.TRUNCATED, "subroutine " .. i .. " past the end")
end
subrs[i + 1] = cs
p = e + n
end
end
-- CharStrings
local names: { string } = {}
local charstrings: { buffer } = {}
local byName: { [string]: number } = {}
local p = csAt + 12
while true do
local s, e, name, len = string.find(ptext, "/([^%s/%[%]{}()<>]+)%s+(%d+)%s+%S+ ", p)
if not s then
break
end
-- stop at the end of the dictionary
if string.find(string.sub(ptext, p, s), "%send%s") then
break
end
local n = tonumber(len) :: number
local cs = charstring(e, n)
if not cs then
return nil, Err.new(Err.TRUNCATED, "charstring " .. tostring(name) .. " past the end")
end
if #names >= maxGlyphs then
return nil, Err.new(Err.LIMIT, "more than maxGlyphs glyphs")
end
table.insert(names, name :: string)
table.insert(charstrings, cs)
if byName[name :: string] == nil then
byName[name :: string] = #names - 1
end
p = e + n
end
if #names == 0 then
return nil, Err.new(Err.CORRUPT, "no glyphs")
end
-- .notdef first: glyph 0
local nd = byName[".notdef"]
if nd and nd ~= 0 then
names[1], names[nd + 1] = names[nd + 1], names[1]
charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1]
byName[names[1]], byName[names[nd + 1]] = 0, nd
end
-- the encoding
local encoding: { [number]: string } = {}
if string.find(clear, "/Encoding%s+StandardEncoding") then
for code, gname in GlyphNames.STANDARD do
encoding[code] = gname
end
else
for code, gname in string.gmatch(clear, "dup%s+(%d+)%s*/([^%s/]+)%s+put") do
encoding[tonumber(code) :: number] = gname
end
end
local cmap: { [number]: number } = {}
for _, gname in encoding do
local g = byName[gname]
local cp = GlyphNames.unicode(gname)
if g and cp and cmap[cp] == nil then
cmap[cp] = g
end
end
for k, gname in names do
local cp = GlyphNames.unicode(gname)
if cp and cmap[cp] == nil then
cmap[cp] = k - 1
end
end
-- font matrix / bbox
local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]")
local scale = 0.001
if fm then
local a = tonumber(string.match(fm, "^%s*(%S+)"))
if a and a > 0 then
scale = a
end
end
local bb = string.match(clear, "/FontBBox%s*[{%[]([^}%]]*)[}%]]")
local bbox = { 0, 0, 0, 0 }
if bb then
local k = 1
for v in string.gmatch(bb, "%S+") do
bbox[k] = tonumber(v) or 0
k += 1
end
end
local upm = math.floor(1 / scale + 0.5)
local font = setmetatable({
kind = "font",
info = {
family = psString(clear, "FamilyName") or string.match(clear, "/FontName%s*/(%S+)"),
style = psString(clear, "Weight") or "Regular",
fullName = psString(clear, "FullName"),
postscriptName = string.match(clear, "/FontName%s*/(%S+)"),
},
unitsPerEm = upm,
ascent = bbox[4],
descent = bbox[2],
lineGap = 0,
numGlyphs = #names,
meta = {
glyphNames = names,
encoding = encoding,
bbox = bbox,
italicAngle = tonumber(string.match(clear, "/ItalicAngle%s+(%-?[%d%.]+)") or "0"),
lenIV = lenIV,
source = { format = "type1", variant = if r:peek(2) == "\128\1" then "pfb" else "pfa" },
},
_cmap = cmap,
_charstrings = charstrings,
_cache = {},
}, Face)
font._ctx = {
subrs = subrs,
seac = function(code: number): Charstring.Result?
local gname = GlyphNames.STANDARD[code]
local g = if gname then byName[gname] else nil
if not g then
return nil
end
return Charstring.run(charstrings[g + 1], { subrs = subrs })
end,
}
return font, nil
end
return Type1