mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 10:44:25 +00:00
EPS import: composite fonts' Type 42 review fixes
widthshow matches a composite character by font number times 256 plus its code; measuring Type 42 glyphs counts against the operation budget; the Type 42 data cache keeps the least recently used order, remembers fonts whose data can't be read and counts each font's data against the memory budget once; composite font arrays are borrowed, not copied.
This commit is contained in:
@@ -74,8 +74,11 @@ pub(crate) struct Interp<'a> {
|
||||
/// The width a Type 3 glyph procedure gave (`setcachedevice`, `setcharwidth`).
|
||||
pub glyph_width: Option<[f64; 2]>,
|
||||
/// The TrueType data of the Type 42 fonts drawn so far, by their `sfnts` array (see
|
||||
/// `type42`), the most recent last.
|
||||
pub type42: Vec<(Shared<Obj>, Rc<Vec<u8>>)>,
|
||||
/// `type42`; `None` when it can't be read), the most recently used last.
|
||||
pub type42: Type42Cache,
|
||||
/// The `sfnts` arrays whose TrueType data has been counted against [`MAX_MEMORY`]: a font
|
||||
/// read again after it left `type42` doesn't count again.
|
||||
pub type42_counted: HashSet<Shared<Obj>>,
|
||||
pub g: GState,
|
||||
pub saved: Vec<GState>,
|
||||
pub out: Out,
|
||||
@@ -97,6 +100,9 @@ pub(crate) struct Fault {
|
||||
pub procs: Vec<Rc<str>>,
|
||||
}
|
||||
|
||||
/// The TrueType data of Type 42 fonts by their `sfnts` array (see [`Interp::type42`]).
|
||||
pub(crate) type Type42Cache = Vec<(Shared<Obj>, Option<Rc<Vec<u8>>>)>;
|
||||
|
||||
/// Most procedure names a [`Fault`] keeps.
|
||||
const FAULT_PROCS: usize = 3;
|
||||
|
||||
@@ -193,6 +199,7 @@ impl<'a> Interp<'a> {
|
||||
fault: None,
|
||||
glyph_width: None,
|
||||
type42: vec![],
|
||||
type42_counted: HashSet::new(),
|
||||
g,
|
||||
saved: vec![],
|
||||
out,
|
||||
|
||||
@@ -1125,7 +1125,7 @@ fn read_within(body: &str, secs: u64) -> crate::Imported {
|
||||
/// budget. Running to the end of the budget can take over 20 s on a slow CI runner
|
||||
/// (`search_in_a_loop_runs_out_of_the_budget` searches about 3 GB, 14 s on a fast desktop), so the
|
||||
/// limit here only catches a program that never stops.
|
||||
fn runs_out_of_budget(body: &str) {
|
||||
pub(super) fn runs_out_of_budget(body: &str) {
|
||||
let r = read_within(&format!("0 0 10 10 rectfill {body}"), 120);
|
||||
assert_eq!(objects(&r.document).len(), 1, "{body}: {:?}", r.warnings);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("the program runs too long")), "{body}: {:?}", r.warnings);
|
||||
|
||||
@@ -102,3 +102,88 @@ fn named_descendants_set_type_at_the_composite_fonts_size() {
|
||||
let bounds_all = all(&r.document).iter().map(|n| bounds(n)).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(bounds_all.width() < 60.0, "{bounds_all:?}");
|
||||
}
|
||||
|
||||
/// `widthshow` adds its spacing to the composite character whose font number times 256 plus code
|
||||
/// is its `char` (PLRM 3rd ed., `widthshow` in chapter 8), not to every character with that code.
|
||||
#[test]
|
||||
fn widthshow_matches_a_composite_character_by_font_number_and_code() {
|
||||
let (_, wh) = glyph('H');
|
||||
let fonts = fonts().replace("/Encoding [0] def", "/Encoding [0 0] def");
|
||||
let check = |cond: String| super::tests::check(&format!("{fonts} /Comp findfont 50 scalefont setfont {cond}"));
|
||||
let end = |ch: u32| format!("gsave nulldevice 10 20 moveto 20 0 {ch} (\\000\\001\\001\\001) widthshow currentpoint grestore pop");
|
||||
// 257 is font 1's code 1: the second H only.
|
||||
check(format!("{} {} sub abs 0.01 lt", end(257), 10.0 + 100.0 * wh + 20.0));
|
||||
// 1 is font 0's code 1: the first H only.
|
||||
check(format!("{} {} sub abs 0.01 lt", end(1), 10.0 + 100.0 * wh + 20.0));
|
||||
// 2 is neither.
|
||||
check(format!("{} {} sub abs 0.01 lt", end(2), 10.0 + 100.0 * wh));
|
||||
}
|
||||
|
||||
/// Measuring a composite font's Type 42 glyphs (`stringwidth` on a long string in a `loop`)
|
||||
/// counts against the operation budget, as drawing them does.
|
||||
#[test]
|
||||
fn measuring_type42_descendants_in_a_loop_runs_out_of_the_budget() {
|
||||
super::tests::runs_out_of_budget(&format!(
|
||||
"{} /Comp findfont 50 scalefont setfont /s 100000 string def {{ s stringwidth pop pop }} loop",
|
||||
fonts()
|
||||
));
|
||||
}
|
||||
|
||||
/// A descendant whose TrueType data can't be read (an `sfnts` element that isn't a string, after
|
||||
/// 32 MB of strings) is read once, not again for every character a loop measures.
|
||||
#[test]
|
||||
fn unreadable_type42_data_is_read_once() {
|
||||
super::tests::runs_out_of_budget(
|
||||
"10 dict begin /FontName /Bad def /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /FontBBox [0 0 1 1] def /PaintType 0 def\n\
|
||||
/Encoding 256 array def 0 1 255 { Encoding exch /.notdef put } for\n\
|
||||
/CharStrings 1 dict def CharStrings /.notdef 0 put /sfnts [ 0 1 7 { pop 4000000 string } for 0 ] def FontName currentdict end definefont pop\n\
|
||||
16 dict begin /FontName /Comp def /FontType 0 def /FontMatrix [1 0 0 1 0 0] def /FMapType 2 def\n\
|
||||
/Encoding [0] def /FDepVector [/Bad findfont] def FontName currentdict end definefont pop\n\
|
||||
/Comp findfont 50 scalefont setfont { (\\000\\001) stringwidth pop pop } loop",
|
||||
);
|
||||
}
|
||||
|
||||
/// A composite font's TrueType data stays read while it is in use: the font a string uses for
|
||||
/// every other character isn't dropped (and read again, counting its size against the memory
|
||||
/// budget each time) while 16 other fonts are read between its uses.
|
||||
#[test]
|
||||
fn type42_data_in_use_stays_read() {
|
||||
let mut others = String::new();
|
||||
for k in 1..=16 {
|
||||
others.push_str(&format!(
|
||||
"10 dict begin /FontName /B{k} def /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /FontBBox [0 0 1 1] def /PaintType 0 def\n\
|
||||
/Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for\n\
|
||||
/CharStrings 1 dict def CharStrings /.notdef 0 put /sfnts [<00>] def FontName currentdict end definefont pop\n"
|
||||
));
|
||||
}
|
||||
let deps: String = (1..=16).map(|k| format!(" /B{k} findfont")).collect();
|
||||
let fonts = fonts().replace(
|
||||
"/Encoding [0] def /FDepVector [/T42 findfont] def",
|
||||
&format!("/Encoding [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] def /FDepVector [/T42 findfont{deps}] def"),
|
||||
);
|
||||
let s: String = (1..=16).map(|k| format!("\\000\\001\\{k:03o}\\001")).collect();
|
||||
super::tests::check(&format!("{others}{fonts} /Comp findfont 50 scalefont setfont 3000 {{ ({s}) stringwidth pop pop }} repeat true"));
|
||||
}
|
||||
|
||||
/// A page that cycles through more Type 42 fonts than are kept read reads each again when it
|
||||
/// comes back, but counts its data against the memory budget once.
|
||||
#[test]
|
||||
fn type42_data_read_again_counts_once() {
|
||||
let mut fonts = format!("/S [\n{}] def\n", sfnts());
|
||||
for k in 0..17 {
|
||||
fonts.push_str(&format!(
|
||||
"10 dict begin /FontName /F{k} def /FontType 42 def /FontMatrix [1 0 0 1 0 0] def /FontBBox [0 0 1 1] def /PaintType 0 def\n\
|
||||
/Encoding 256 array def 0 1 255 {{ Encoding exch /.notdef put }} for\n\
|
||||
/CharStrings 1 dict def CharStrings /.notdef 0 put /sfnts [ S aload pop ] def FontName currentdict end definefont pop\n"
|
||||
));
|
||||
}
|
||||
let deps: String = (0..17).map(|k| format!(" /F{k} findfont")).collect();
|
||||
let picks: String = (0..17).map(|k| format!(" {k}")).collect();
|
||||
fonts.push_str(&format!(
|
||||
"16 dict begin /FontName /Comp def /FontType 0 def /FontMatrix [1 0 0 1 0 0] def /FMapType 2 def\n\
|
||||
/Encoding [{picks}] def /FDepVector [{deps}] def FontName currentdict end definefont pop\n"
|
||||
));
|
||||
let s: String = (0..17).map(|k| format!("\\{k:03o}\\001")).collect();
|
||||
// 17 fonts of 431 kB, each read 200 times: 1.4 GB if each read counted.
|
||||
super::tests::check(&format!("{fonts} /Comp findfont 50 scalefont setfont 200 {{ ({s}) stringwidth pop pop }} repeat true"));
|
||||
}
|
||||
|
||||
@@ -524,6 +524,8 @@ impl Spacing {
|
||||
/// composite font's matrix (over the descendant's own).
|
||||
struct Mapped {
|
||||
font: DictRef,
|
||||
/// The byte that picked the descendant (the font number).
|
||||
pick: u8,
|
||||
code: u8,
|
||||
outer: Affine,
|
||||
}
|
||||
@@ -567,8 +569,8 @@ impl Interp<'_> {
|
||||
if font_type(&f) != Some(0.0) || f.get(&Key::name("FMapType")).and_then(Obj::as_num) != Some(2.0) {
|
||||
return None;
|
||||
}
|
||||
let encoding = f.get(&Key::name("Encoding"))?.items()?.to_vec();
|
||||
let fonts = f.get(&Key::name("FDepVector"))?.items()?.to_vec();
|
||||
let (encoding, fonts) = (f.get(&Key::name("Encoding"))?.items()?.clone(), f.get(&Key::name("FDepVector"))?.items()?.clone());
|
||||
let (encoding, fonts) = (encoding.borrow(), fonts.borrow());
|
||||
let outer = font_matrix(&f, 1.0);
|
||||
let mut out = Vec::with_capacity(s.len() / 2);
|
||||
for &[pick, code] in s.as_chunks::<2>().0 {
|
||||
@@ -577,7 +579,7 @@ impl Interp<'_> {
|
||||
if let Some(Obj::Dict(d)) = index.and_then(|i| fonts.get(i as usize))
|
||||
&& font_type(&d.borrow()) != Some(0.0)
|
||||
{
|
||||
out.push(Mapped { font: d.clone(), code, outer });
|
||||
out.push(Mapped { font: d.clone(), pick, code, outer });
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
@@ -590,7 +592,9 @@ impl Interp<'_> {
|
||||
for (i, g) in glyphs.iter().enumerate() {
|
||||
let at = self.user_point()?;
|
||||
let w = self.composite_glyph(g, at, Draw::Fill)?;
|
||||
let d = spacing.advance(i, i64::from(g.code), w);
|
||||
// `widthshow` and `awidthshow` match a composite font's character by its font number
|
||||
// times 256 plus its code (PLRM 3rd ed., `widthshow` in chapter 8).
|
||||
let d = spacing.advance(i, i64::from(g.pick) * 256 + i64::from(g.code), w);
|
||||
self.g.cur = Some(self.xf() * (at + d));
|
||||
let c = code_char(&g.font.borrow(), g.code);
|
||||
if c != '\u{2022}' {
|
||||
@@ -619,8 +623,9 @@ impl Interp<'_> {
|
||||
}
|
||||
let fm = g.outer * font_matrix(&g.font.borrow(), 1.0);
|
||||
if let Some((outline, advance)) = self.type42_glyph(&g.font, g.code)? {
|
||||
// Measuring a glyph reads its outline too, so `stringwidth` in a loop pays for it.
|
||||
self.spend((outline.elements().len() as u64).saturating_add(16))?;
|
||||
if paint != Draw::No {
|
||||
self.spend((outline.elements().len() as u64).saturating_add(16))?;
|
||||
let mut p = outline;
|
||||
p.apply_affine(self.xf() * Affine::translate(at.to_vec2()) * fm);
|
||||
if paint == Draw::Fill {
|
||||
@@ -676,13 +681,23 @@ impl Interp<'_> {
|
||||
.map_or(0, |g| g as u32);
|
||||
(sfnts, gid)
|
||||
};
|
||||
let data = match self.type42.iter().find(|(k, _)| k.same(&sfnts)) {
|
||||
Some((_, d)) => d.clone(),
|
||||
// The least recently used font goes first: a hit moves to the end.
|
||||
let data = match self.type42.iter().position(|(k, _)| k.same(&sfnts)) {
|
||||
Some(i) => {
|
||||
let hit = self.type42.remove(i);
|
||||
let data = hit.1.clone();
|
||||
self.type42.push(hit);
|
||||
data
|
||||
}
|
||||
None => {
|
||||
let Some(data) = super::type42::font_data(&sfnts.borrow()) else { return Ok(None) };
|
||||
self.alloc(data.len())?;
|
||||
self.spend((data.len() / 4096) as u64)?;
|
||||
let data = Rc::new(data);
|
||||
// Fonts whose data can't be read are kept too, so they are copied only once.
|
||||
let data = super::type42::font_data(&sfnts.borrow()).map(Rc::new);
|
||||
if let Some(d) = &data {
|
||||
if self.type42_counted.insert(sfnts.clone()) {
|
||||
self.alloc(d.len())?;
|
||||
}
|
||||
self.spend((d.len() / 4096) as u64)?;
|
||||
}
|
||||
if self.type42.len() >= MAX_TYPE42 {
|
||||
self.type42.remove(0);
|
||||
}
|
||||
@@ -690,6 +705,7 @@ impl Interp<'_> {
|
||||
data
|
||||
}
|
||||
};
|
||||
let Some(data) = data else { return Ok(None) };
|
||||
Ok(super::type42::glyph(&data, gid))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user