EPS import: test embedded Type 1 lexing and CIDFont metrics, glyph directories and data limit

Four tests cover embedded-font code paths that no test reached:

- The Type 1 encrypted-part lexer steps over strings with escaped and
  nested parentheses, nested procedures holding comments and strings,
  comments, hexadecimal strings and dictionaries, and does not take
  CharStrings written inside a string, a procedure or a comment for the
  font's.
- A CIDFont's Metrics entries (a number, [sbx wx] and [sbx sby wx wy])
  replace the glyph widths; an entry of another length keeps them.
- A GlyphDirectory array or dictionary draws the same glyphs as the
  binary data section.
- A StartData count over 64 MiB is refused before it is read.
This commit is contained in:
dotCooCoo committed 2026-12-02 21:45:17 -08:00
1 parent 15cc3b048f
commit 5292a3630c
2 files changed
+132 -17

No files matched your search

+99 -14
View File
@@ -50,10 +50,7 @@ fn hex(b: &[u8]) -> String {
/// triangle (500 across, 400 high) 500 wide drawn by a subroutine, encrypted (dictionary 1,
/// `lenIV` 4). The binary data section, written in hexadecimal when `hex_data`.
fn cid_font(hex_data: bool) -> Vec<u8> {
let empty = cs(&[(&[0, 500], 13), (&[], 14)]);
let square = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]);
let triangle = encrypt(&cs(&[(&[0, 500], 13), (&[0], 10), (&[], 14)]));
let subr = encrypt(&cs(&[(&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)]));
let [empty, square, triangle] = cid_glyphs();
// The offset table: FDArray index (1 byte) and offset (2 bytes) of CIDs 0 to 2 and the end.
let table = 4 * 3;
let offsets = [table, table + empty.len(), table + empty.len() + square.len(), table + empty.len() + square.len() + triangle.len()];
@@ -65,16 +62,7 @@ fn cid_font(hex_data: bool) -> Vec<u8> {
data.extend(empty);
data.extend(square);
data.extend(triangle);
let mut out = format!(
"/CIDInit /ProcSet findresource begin\n20 dict begin\n/CIDFontName /TestCID def /CIDFontType 0 def\n\
/CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Shapes) def /Supplement 0 def end def\n\
/FontBBox [0 0 1000 1000] def\n/FDArray [\n\
4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end\n\
4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV 4 def /Subrs [<{}>] def end def currentdict end\n\
] def\n/CIDMapOffset 0 def /FDBytes 1 def /GDBytes 2 def /CIDCount 3 def\n",
hex(&subr)
)
.into_bytes();
let mut out = cid_font_head().into_bytes();
if hex_data {
out.extend(format!("(Hex) {} StartData\n{}>\n", data.len(), hex(&data)).into_bytes());
} else {
@@ -85,6 +73,46 @@ fn cid_font(hex_data: bool) -> Vec<u8> {
out
}
/// The charstrings of [`cid_font`]'s CIDs 0 to 2, as its data holds them.
fn cid_glyphs() -> [Vec<u8>; 3] {
let empty = cs(&[(&[0, 500], 13), (&[], 14)]);
let square = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]);
let triangle = encrypt(&cs(&[(&[0, 500], 13), (&[0], 10), (&[], 14)]));
[empty, square, triangle]
}
/// [`cid_font`] up to its glyph data: the CIDFont dictionary, its FDArray and its offset table's
/// layout.
fn cid_font_head() -> String {
let subr = encrypt(&cs(&[(&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)]));
format!(
"/CIDInit /ProcSet findresource begin\n20 dict begin\n/CIDFontName /TestCID def /CIDFontType 0 def\n\
/CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Shapes) def /Supplement 0 def end def\n\
/FontBBox [0 0 1000 1000] def\n/FDArray [\n\
4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end\n\
4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV 4 def /Subrs [<{}>] def end def currentdict end\n\
] def\n/CIDMapOffset 0 def /FDBytes 1 def /GDBytes 2 def /CIDCount 3 def\n",
hex(&subr)
)
}
/// [`cid_font`] with its glyphs in a `GlyphDirectory` (each entry the FDArray index byte and the
/// charstring: PLRM 3rd ed., §5.11.3) instead of a binary data section, as an array
/// indexed by CID or as a dictionary keyed by CID, defined with `defineresource`. Its own matrix
/// is the identity, as its FDArray matrices give glyph space.
fn cid_font_in_a_directory(dict: bool) -> String {
let entries: Vec<String> = cid_glyphs().iter().zip([0u8, 0, 1]).map(|(g, fd)| format!("<{:02x}{}>", fd, hex(g))).collect();
let directory = if dict {
format!("<< {} >>", entries.iter().enumerate().map(|(cid, e)| format!("{cid} {e}")).collect::<Vec<_>>().join(" "))
} else {
format!("[ {} ]", entries.join(" "))
};
format!(
"{}/FontMatrix [1 0 0 1 0 0] def /GlyphDirectory {directory} def\nCIDFontName currentdict end /CIDFont defineresource pop end\n",
cid_font_head()
)
}
/// CMap `/Test-H`: one-byte codes 00–7F and two-byte codes 8000–FFFF; A and B are CIDs 1 and 2,
/// <8001> CID 2, and codes 00–1F without a character take CID 1 as their notdef.
const CMAP: &str = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\
@@ -121,6 +149,63 @@ fn type0_cidfonts_draw_their_charstrings_through_the_cmap() {
}
}
/// `font` and the CMap, then `body`, as an EPS file.
fn program_with(font: &str, body: &str) -> Vec<u8> {
format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n{font}{CMAP}{body}\nshowpage\n%%EOF\n").into_bytes()
}
/// Widths in a CIDFont's `Metrics` dictionary replace its glyphs' own (PLRM 3rd ed., §5.9.2): a
/// number is the width, a 2-element entry `[sbx wx]` gives its second element and a 4-element
/// entry `[sbx sby wx wy]` its third. An entry of another length keeps the glyph's width.
#[test]
fn cidfont_metrics_replace_the_glyph_widths() {
let with = |metrics: &str| {
String::from_utf8(cid_font(true)).unwrap().replace("/CIDCount 3 def", &format!("/CIDCount 3 def /Metrics << {metrics} >> def"))
};
let width = |font: &str, s: &str, w: f64| check(&format!("{font}{CMAP} /TestFont 50 selectfont {s} stringwidth pop {w} sub abs 0.01 lt"));
let font = with("0 250 1 [0 700] 2 [0 0 800 0]");
// At 50 points an em: 700 units for A (CID 1), 800 for B (CID 2), 250 for CID 0.
width(&font, "(A)", 35.0);
width(&font, "(B)", 40.0);
width(&font, "<9041>", 12.5);
// A 3-element entry keeps the square's 600 units.
width(&with("1 [0 700 0]"), "(A)", 30.0);
// The triangle is drawn where the square's new width ends, 700 units on, not 600.
let r = import(&program_with(&font, "/TestFont 50 selectfont 10 20 moveto (AB) show")).unwrap();
let p = paths(&r);
assert_eq!(p.len(), 2, "{p:?} {:?}", r.warnings);
assert!((p[1].x0 - 45.0).abs() < 0.01 && (p[1].width() - 25.0).abs() < 0.01, "{p:?}");
}
/// A Type 0 CIDFont whose glyphs are in a `GlyphDirectory`, an array or a dictionary, draws the
/// same glyphs as the same font with its glyphs in a binary data section.
#[test]
fn glyph_directories_draw_the_glyphs_a_data_section_does() {
let show = "/TestFont 50 selectfont 10 20 moveto (AB) show";
let want = paths(&import(&program(false, show)).unwrap());
assert_eq!(want.len(), 2, "{want:?}");
for dict in [false, true] {
let r = import(&program_with(&cid_font_in_a_directory(dict), show)).unwrap();
assert!(r.warnings.is_empty(), "{dict}: {:?}", r.warnings);
let p = paths(&r);
assert_eq!(p.len(), 2, "{dict}: {p:?}");
assert!(p.iter().zip(&want).all(|(a, b)| super::tests::near(*a, *b)), "{dict}: {p:?} {want:?}");
}
}
/// A binary data section longer than a font's data may be (64 MiB) is refused before it is read.
#[test]
fn start_data_over_the_glyph_data_limit_is_refused() {
let font = String::from_utf8(cid_font(true)).unwrap();
let font = format!("{}(Binary) 70000000 StartData abc\n", &font[..font.find("(Hex)").unwrap()]);
let r = import(&program_with(&font, "/TestFont 50 selectfont 10 20 moveto (AB) show"));
let said = match &r {
Ok(r) => r.warnings.join("\n"),
Err(e) => e.clone(),
};
assert!(said.contains("a font's data is too large"), "{said}");
}
/// Codes take as many bytes as their codespace range says; codes without a character take their
/// notdef mapping's CID, else CID 0 (PLRM 3rd ed., §5.11.5).
#[test]
+33 -3
View File
@@ -47,6 +47,11 @@ fn font(encoding: &str, hex: bool) -> Vec<u8> {
/// [`font`] with subroutines `subrs` and, when given, charstring `a` for A.
fn font_with(encoding: &str, hex: bool, subrs: &[Vec<u8>], a: Option<Vec<u8>>) -> Vec<u8> {
font_private(encoding, hex, subrs, a, b"")
}
/// [`font_with`] with `extra` in the encrypted part, after `Subrs` and before `CharStrings`.
fn font_private(encoding: &str, hex: bool, subrs: &[Vec<u8>], a: Option<Vec<u8>>, extra: &[u8]) -> Vec<u8> {
let square = a.unwrap_or_else(|| cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]));
let triangle = cs(&[(&[0, 500], 13), (&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 14)]);
let notdef = cs(&[(&[0, 250], 13), (&[], 14)]);
@@ -61,7 +66,9 @@ fn font_with(encoding: &str, hex: bool, subrs: &[Vec<u8>], a: Option<Vec<u8>>) -
private.extend(e);
private.extend(b" NP\n");
}
private.extend(b"readonly def\n2 index /CharStrings 4 dict dup begin\n");
private.extend(b"readonly def\n");
private.extend(extra);
private.extend(b"2 index /CharStrings 4 dict dup begin\n");
for (name, glyph) in [(".notdef", &notdef), ("A", &square), ("B", &triangle), ("g1", &triangle)] {
let e = encrypt(glyph, 4330);
private.extend(format!("/{name} {} RD ", e.len()).into_bytes());
@@ -163,8 +170,13 @@ fn laid_out(t: &TextObject) -> Vec<(vectorcraft_geom::Rect, f64, bool)> {
/// font's own advances (no tracking makes up for a stand-in's), not in the fallback font.
#[test]
fn embedded_type1_type_draws_with_the_files_glyphs() {
let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show");
let t = &texts(&r)[0];
draws_the_files_glyphs(&program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show"));
}
/// "AB" in `/TestOne` drawn with the file's glyphs: the square and the triangle, B starting where
/// A's 600 units end.
fn draws_the_files_glyphs(r: &crate::Imported) {
let t = &texts(r)[0];
assert!(t.file_fonts.is_some(), "{:?}", r.warnings);
let glyphs = laid_out(t);
assert_eq!(glyphs.len(), 2);
@@ -178,6 +190,24 @@ fn embedded_type1_type_draws_with_the_files_glyphs() {
assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs);
}
/// The encrypted part's other definitions are stepped over whole when looking for its
/// `CharStrings`: strings with escaped and nested parentheses, nested procedures holding comments
/// and strings, comments, hexadecimal strings and dictionaries. `CharStrings` written inside a
/// string or a comment, with a charstring of its own, isn't taken for the font's.
#[test]
fn the_encrypted_parts_other_definitions_are_stepped_over() {
let extra: &[u8] = b"/OtherSubrs [ { (a\\) } (b) {c) { % } ( {\n} } ] ND\n\
/p { {} (}) /CharStrings 2 dict dup begin /A 1 RD x ND end } def\n\
/x <0A 0b\n 1F> def\n\
/d << /k (() /CharStrings 2 dict) /m << >> >> def\n\
% /CharStrings 2 dict dup begin /A 1 RD x ND end\n\
(/CharStrings 2 \\( dict dup begin /A 1 RD x ND end) pop\n";
let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
let body = b"/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show\nshowpage\n%%EOF\n".to_vec();
let r = import(&[head, font_private(OWN, false, &[], None, extra), body].concat()).unwrap();
draws_the_files_glyphs(&r);
}
/// A family whose regular style the file carries but whose bold it only names: the regular is
/// drawn in the kept font and the bold in the fallback font, and the warning says both.
#[test]