From e377bbd24d2132a02f7453a852b999d747fe56c2 Mon Sep 17 00:00:00 2001 From: JonRC Date: Sun, 22 Nov 2026 23:38:19 -0300 Subject: [PATCH 1/5] Fix #9152: EPS import keeps the fonts a file carries for type whose family isn't installed Type in a Type 1 or Type 42 font an EPS embeds came in as live type in the fallback font when its family isn't installed. As PDF import has done since #4569, the glyphs that type is shown in (outline and advance from the font program, for each character) now become a font kept with the document, which draws that type as the file does until its text is edited, and spaces it by the glyphs' own advances. A string that draws a character with a different glyph from the one kept for it comes in as outlines. The warning names those families with PDF import's sentence for fonts a file carries. Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. --- crates/eps/src/import.rs | 38 +++++-- crates/eps/src/import/file_fonts.rs | 133 ++++++++++++++++++++++++ crates/eps/src/import/graphics/state.rs | 4 + crates/eps/src/import/tests.rs | 2 +- crates/eps/src/import/tests_type1.rs | 96 ++++++++++++++++- crates/eps/src/import/tests_type42.rs | 16 +++ crates/eps/src/import/text.rs | 83 ++++++++++++++- crates/eps/src/import/type1.rs | 15 +++ docs/file-format-parity.md | 1 + 9 files changed, 375 insertions(+), 13 deletions(-) create mode 100644 crates/eps/src/import/file_fonts.rs diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 8182553b00..f85ed7df3e 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -39,6 +39,7 @@ mod ai; mod ate; mod cid; mod data; +mod file_fonts; mod graphics; mod interp; mod lex; @@ -113,6 +114,10 @@ const MAX_SIDE: f64 = 1e5; /// The start of the warning that type was set in fonts that aren't available, before ": " and /// their families: PDF import's words, as type in those fonts comes in the same way. pub(crate) const MISSING_FONTS_NOTE: &str = "fonts that aren't available show in the fallback font until they are"; +/// The start of the warning that type in fonts that aren't available is drawn in the fonts the +/// file carries (see `file_fonts`), before ": " and their families: PDF import's words. +pub(crate) const CARRIED_FONTS_NOTE: &str = + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font)"; /// Most families named in that warning. const MAX_MISSING_FONTS: usize = 64; @@ -304,18 +309,36 @@ pub fn import_ai(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncod /// [`import_names`] (a `.ai` when `ai_file`, see [`import_ai`]). fn read_checked(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncoding, ai_file: bool) -> Result { let mut r = read_names(bytes, editing_data, trust, names, ai_file)?; - let missing = missing_fonts(&r.document); - if !missing.is_empty() { - r.warnings.push(format!("{MISSING_FONTS_NOTE}: {}", missing.join(", "))); + r.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut r.document)); + let (carried, missing) = missing_fonts(&r.document); + for (note, families) in [(CARRIED_FONTS_NOTE, carried), (MISSING_FONTS_NOTE, missing)] { + if !families.is_empty() { + r.warnings.push(format!("{note}: {}", families.join(", "))); + } } Ok(r) } /// The families of the type in `d` (its layers and its symbols) that aren't available, each once /// in the order the type comes, at most [`MAX_MISSING_FONTS`]: the document's, whether its type -/// came from the page or from an editing copy, and none for type only measured or outlined. -fn missing_fonts(d: &Document) -> Vec { +/// came from the page or from an editing copy, and none for type only measured or outlined. Those +/// drawn in fonts the file carries (bound to the document's type) come first, the rest second. +fn missing_fonts(d: &Document) -> (Vec, Vec) { let db = vectorcraft_text::FontDb::global(); + let mut bound: HashSet = HashSet::new(); + let mut find_bound = |n: &Node| { + if let NodeKind::Text(t) = &n.kind { + for font in t.file_fonts_in_use() { + if t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some() { + bound.insert(font.family.clone()); + } + } + } + }; + d.walk(&mut find_bound); + for s in &d.symbols { + s.art.walk(&mut find_bound); + } let mut checked: HashSet = HashSet::new(); let mut missing: Vec = Vec::new(); let mut add = |n: &Node| { @@ -335,7 +358,7 @@ fn missing_fonts(d: &Document) -> Vec { for s in &d.symbols { s.art.walk(&mut add); } - missing + missing.into_iter().partition(|family| bound.contains(family)) } /// [`import_names`] before the type's fonts are checked (a `.ai` when `ai_file`, see [`import_ai`]). @@ -406,6 +429,9 @@ fn finish(mut out: Out) -> Imported { if !out.shadings.is_empty() { graphics::collapse(&mut children, &out.shadings); } + // The fonts made of the glyphs of fonts the file carries, for their type. + let kept = std::mem::take(&mut out.file_glyphs).keep(&mut out.doc.images); + file_fonts::keep_file_fonts(&mut children, &kept, &out.doc.images); let mut layer = Node::layer(out.doc.alloc_id(), "Layer 1", LayerColor::Preset(0)); if let Some(c) = layer.children_mut() { *c = children; diff --git a/crates/eps/src/import/file_fonts.rs b/crates/eps/src/import/file_fonts.rs new file mode 100644 index 0000000000..0ce2046aea --- /dev/null +++ b/crates/eps/src/import/file_fonts.rs @@ -0,0 +1,133 @@ +//! The fonts an EPS carries (embeds) for type whose fonts aren't available here, kept with the +//! document as PDF import keeps a PDF's (#4568): the glyphs its type is shown in, gathered as the +//! program runs, become one font per family and style ([`vectorcraft_text::build_file_font`]), +//! which draws that type as the file draws it until its text is edited +//! ([`vectorcraft_doc::FileFonts`]). +//! +//! Each glyph comes from the font program the file carries (a Type 1 font's charstrings, a Type 42 +//! font's TrueType glyph): its outline and advance, for the character its code shows. The first +//! glyph of each character is kept; a string that uses a different glyph for a character is drawn +//! as outlines instead. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; + +use vectorcraft_doc::{FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind}; +use vectorcraft_text::{FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; + +/// The most glyphs gathered from one file, in all its fonts (an outline is some hundreds of bytes). +const MAX_GLYPHS: usize = 200_000; + +/// The glyphs gathered so far. +#[derive(Default)] +pub(crate) struct FileFontGlyphs { + fonts: Vec, + /// Each font (family and style) by its index in `fonts`. + index: HashMap<(String, String), usize>, + /// Glyphs gathered, in all. + count: usize, +} + +/// The glyphs of one family and style. +struct Gathered { + family: String, + style: String, + info: FileFontInfo, + glyphs: Vec, + /// Each character's glyph, by its index in `glyphs`. + chars: HashMap, +} + +impl FileFontGlyphs { + /// The font of `family` and `style` (made with `info` the first time): its index. + pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize { + if let Some(&i) = self.index.get(&(family.to_string(), style.to_string())) { + return i; + } + let i = self.fonts.len(); + self.fonts.push(Gathered { family: family.to_string(), style: style.to_string(), info: info(), glyphs: vec![], chars: HashMap::new() }); + self.index.insert((family.to_string(), style.to_string()), i); + i + } + + /// Can `glyphs` all be drawn in font `font`: no character among them has a glyph there, or in + /// `glyphs` itself, that differs in outline or advance? A font keeps one glyph per character. + pub fn fits(&self, font: usize, glyphs: &[FileGlyph]) -> bool { + let Some(f) = self.fonts.get(font) else { return false }; + let same = |a: &FileGlyph, b: &FileGlyph| a.outline == b.outline && a.advance == b.advance; + glyphs.iter().enumerate().all(|(i, g)| { + f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).is_none_or(|kept| same(kept, g)) + && glyphs.iter().take(i).filter(|e| e.ch == g.ch).all(|e| same(e, g)) + }) + } + + /// Gather `glyph` for font `font`, unless it already has one for its character or is full. + pub fn add(&mut self, font: usize, glyph: FileGlyph) { + if self.count >= MAX_GLYPHS { + return; + } + if let Some(f) = self.fonts.get_mut(font) + && f.glyphs.len() < MAX_FILE_GLYPHS + && !f.chars.contains_key(&glyph.ch) + { + f.chars.insert(glyph.ch, f.glyphs.len()); + f.glyphs.push(glyph); + self.count += 1; + } + } + + /// The fonts built from the glyphs gathered, stored in `images` under their content keys: + /// family and style → the font's key. + pub fn keep(self, images: &mut BTreeMap) -> HashMap<(String, String), String> { + let mut kept = HashMap::new(); + for f in self.fonts { + let Some(bytes) = build_file_font(&f.info, &f.glyphs) else { continue }; + let blob = ImageBlob::new(FILE_FONT_MIME, bytes); + let base = blob.content_key(); + let mut key = base.clone(); + let mut suffix = 1; + while images.get(&key).is_some_and(|held| held != &blob) { + key = format!("{base}-{suffix}"); + suffix += 1; + } + images.entry(key.clone()).or_insert(blob); + kept.insert((f.family, f.style), key); + } + kept + } +} + +/// The type among `nodes` (and in their groups) set in the families and styles `kept` holds fonts +/// for (family and style → the font's blob in `images`): drawn in them while its text is the +/// file's, and laid out again for its bounds. +pub(crate) fn keep_file_fonts(nodes: &mut [Arc], kept: &HashMap<(String, String), String>, images: &BTreeMap) { + if kept.is_empty() { + return; + } + let db = vectorcraft_text::FontDb::global(); + for n in nodes.iter_mut() { + if n.children().is_some_and(|c| !c.is_empty()) + && let Some(children) = Arc::make_mut(n).children_mut() + { + keep_file_fonts(children, kept, images); + } + let NodeKind::Text(t) = &n.kind else { continue }; + let mut fonts: Vec = vec![]; + for r in &t.runs { + let (family, style) = (&r.style.font_family, &r.style.font_style); + if let Some(key) = kept.get(&(family.clone(), style.clone())) + && !fonts.iter().any(|f| f.family == *family && f.style == *style) + { + fonts.push(FileFont { family: family.clone(), style: style.clone(), key: key.clone() }); + } + } + if fonts.is_empty() { + continue; + } + if let NodeKind::Text(t) = &mut Arc::make_mut(n).kind { + t.file_fonts = Some(Box::new(FileFonts::new(fonts, &t.plain_text()))); + db.bind_file_fonts(t, |key| images.get(key)); + t.cached_bounds = Some(vectorcraft_text::layout(db, t).bounds); + } + } +} diff --git a/crates/eps/src/import/graphics/state.rs b/crates/eps/src/import/graphics/state.rs index 489f675bf4..be6a74392e 100644 --- a/crates/eps/src/import/graphics/state.rs +++ b/crates/eps/src/import/graphics/state.rs @@ -152,6 +152,9 @@ pub(crate) struct Out { pub(super) tilings: HashMap>, /// How deep art drawn apart (a pattern's cell, a Type 3 glyph) is nested. pub apart: u32, + /// The glyphs of fonts the file carries for families that aren't available, gathered for the + /// fonts kept with the document (see `file_fonts`). + pub file_glyphs: super::super::file_fonts::FileFontGlyphs, } fn sane(r: Rect) -> bool { @@ -201,6 +204,7 @@ impl Out { shadings: HashSet::new(), tilings: HashMap::new(), apart: 0, + file_glyphs: Default::default(), } } diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index cf0e890f38..0ba6c600d5 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -936,7 +936,7 @@ fn device_settings_are_accepted_and_change_nothing() { /// `warnings` without the note naming fonts that aren't available: which those are depends on the /// fonts installed where the tests run, not on the program. pub(super) fn program_warnings(warnings: &[String]) -> Vec<&String> { - warnings.iter().filter(|w| !w.starts_with(super::MISSING_FONTS_NOTE)).collect() + warnings.iter().filter(|w| !w.starts_with(super::MISSING_FONTS_NOTE) && !w.starts_with(super::CARRIED_FONTS_NOTE)).collect() } fn blue(body: &str) { diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs index 5399042908..d94be757ac 100644 --- a/crates/eps/src/import/tests_type1.rs +++ b/crates/eps/src/import/tests_type1.rs @@ -138,8 +138,100 @@ fn type_in_fonts_that_arent_available_is_named_in_a_warning() { /Nowhere-Bold 12 selectfont 10 80 moveto (x) show /Inter-Regular 12 selectfont 10 90 moveto (y) show", ); assert_eq!(texts(&r).iter().map(|t| t.runs[0].style.font_family.as_str()).collect::>(), ["Test One", "Test One", "Nowhere", "Inter"]); - // PDF import's words. - assert_eq!(r.warnings, ["fonts that aren't available show in the fallback font until they are: Test One, Nowhere"]); + // PDF import's words: the font the file carries draws its type, the one it only names doesn't. + assert_eq!( + r.warnings, + [ + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One", + "fonts that aren't available show in the fallback font until they are: Nowhere", + ] + ); + // A font found by name keeps no glyphs of the file's: it shows in the fallback font, as before. + assert!(texts(&r).iter().filter(|t| t.runs[0].style.font_family != "Test One").all(|t| t.file_fonts.is_none())); +} + +/// The glyphs of type laid out in the document's fonts: each one's outline (text space) and origin, +/// and whether a font the file carries draws it. +fn laid_out(t: &TextObject) -> Vec<(vectorcraft_geom::Rect, f64, bool)> { + use kurbo::Shape; + let db = vectorcraft_text::FontDb::global(); + vectorcraft_text::layout(db, t).glyphs.iter().map(|g| (g.outline.bounding_box(), g.origin.x, db.is_file_font(g.font_id))).collect() +} + +/// Type in a Type 1 font the file carries, whose family isn't available, is drawn with the file's +/// glyphs, as PDF import keeps a PDF's fonts (#4568): A the square and B the triangle, at the +/// 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]; + assert!(t.file_fonts.is_some(), "{:?}", r.warnings); + let glyphs = laid_out(t); + assert_eq!(glyphs.len(), 2); + assert!(glyphs.iter().all(|g| g.2), "every glyph the file's: {glyphs:?}"); + // The square is 400 by 500 units, the triangle 500 by 400, at 50 points an em. + let (a, b) = (glyphs[0].0, glyphs[1].0); + assert!((a.width() - 20.0).abs() < 0.05 && (a.height() - 25.0).abs() < 0.05, "{a:?}"); + assert!((b.width() - 25.0).abs() < 0.05 && (b.height() - 20.0).abs() < 0.05, "{b:?}"); + // B starts where A's 600 units end, with no tracking. + assert!((glyphs[1].1 - glyphs[0].1 - 30.0).abs() < 0.05, "{glyphs:?}"); + assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs); +} + +/// A character the file draws with a different glyph from the one the kept font already has for +/// it (here a second font of the same name whose A is a narrower square) can't go in that font: +/// that string comes in as outlines, the first stays type in the file's glyphs. +#[test] +fn a_second_glyph_for_a_character_keeps_its_type_as_outlines() { + let narrow = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[200, 0], 5), (&[0, 500], 5), (&[-200, 0], 5), (&[], 9), (&[], 14)]); + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let file = [ + head, + font(OWN, false), + b"/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show\n".to_vec(), + font_with(OWN, false, &[], Some(narrow)), + b"/TestOne findfont 50 scalefont setfont 10 60 moveto (A) show\nshowpage\n%%EOF\n".to_vec(), + ] + .concat(); + let r = import(&file).unwrap(); + let t = texts(&r); + assert_eq!(t.len(), 1, "{:?}", all(&r.document)); + assert!(laid_out(&t[0]).iter().all(|g| g.2)); + let paths: Vec<_> = all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| bounds(n)).collect(); + assert!(paths.iter().any(|b| (b.width() - 10.0).abs() < 0.05 && (b.height() - 25.0).abs() < 0.05), "the narrow A as outlines: {paths:?}"); +} + +/// The type opened in the app keeps the file's glyphs through a save and a reopen, takes the +/// fallback font once its text is edited, and gets the file's glyphs back on undo, as PDF type in +/// a font the file carries does. +#[test] +fn kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited() { + use vectorcraft_testkit::{Session, json}; + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let file = [head, font(OWN, false), b"/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show\nshowpage\n%%EOF\n".to_vec()].concat(); + let mut s = Session::new(); + let opened = s.execute("document.open", &json!({"name": "kept.eps", "dataBase64": vectorcraft_testkit::format::base64_encode(&file)})).unwrap(); + assert!(opened["warnings"].to_string().contains("until their text is edited"), "{opened}"); + let carried = |s: &Session| { + let (mut glyphs, mut id) = (vec![], None); + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + glyphs.extend(laid_out(t).into_iter().map(|g| g.2)); + id = Some(n.id); + } + }); + (glyphs, id) + }; + let (glyphs, id) = carried(&s); + assert_eq!(glyphs, [true, true]); + let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap(); + assert_eq!(carried(&s).0, [true, true], "saved and opened again"); + let id = carried(&s).1.or(id).unwrap(); + s.execute("text.setText", &json!({"id": id, "text": "ABA"})).unwrap(); + assert!(carried(&s).0.iter().all(|g| !g), "edited: the fallback font"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(carried(&s).0, [true, true], "undone: the file's glyphs again"); } #[test] diff --git a/crates/eps/src/import/tests_type42.rs b/crates/eps/src/import/tests_type42.rs index 21399afe70..c09ae2589e 100644 --- a/crates/eps/src/import/tests_type42.rs +++ b/crates/eps/src/import/tests_type42.rs @@ -111,6 +111,22 @@ fn the_fonts_own_widths_space_its_type_and_move_the_point() { check("newpath 10 20 moveto (\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into()); } +/// Type in a Type 42 font the file carries, whose family (Plain42) isn't available, is drawn +/// with the file's glyphs kept with the document, spaced by their own widths, as a Type 1 font's +/// is (see `tests_type1`). +#[test] +fn type_in_a_carried_type42_font_draws_with_the_files_glyphs() { + let (h, wh) = glyph('H'); + let (i, _) = glyph('I'); + let r = read(&format!("{} /Plain42 findfont 50 scalefont setfont 10 20 moveto (\\001\\002) show", font(&[h, i]))); + let t = &texts(&r)[0]; + assert!(t.file_fonts.is_some(), "{:?}", r.warnings); + let db = vectorcraft_text::FontDb::global(); + assert!(vectorcraft_text::layout(db, t).glyphs.iter().all(|g| db.is_file_font(g.font_id))); + let o = origins(t); + assert!((o[1] - o[0] - 50.0 * wh).abs() < 0.05, "{o:?}"); +} + /// `xshow` and `ashow` put each character where they say: the type's tracking makes up the /// difference from its font's advances. #[test] diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 3de16d7bbf..e88c4d3bb9 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -9,7 +9,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, Point, Vec2}; -use vectorcraft_text::TextLayout; +use vectorcraft_text::{FileFontInfo, FileGlyph, TextLayout}; use super::cid::Base; use super::graphics::MAX_APART; @@ -675,6 +675,17 @@ impl Interp<'_> { { return self.show_type42_outlines(data, glyphs, s, spacing, at, f1); } + // Type in a font the file carries whose family isn't available is drawn in a font made of + // the file's glyphs (see `file_fonts`), spaced by their own advances. A character whose + // glyph differs from the one that font has for it keeps the string as outlines. + let kept = match &plain { + Some((data, glyphs)) => match self.keep_file_glyphs(data, glyphs)? { + Some(true) => true, + Some(false) => return self.show_type42_outlines(data, glyphs, s, spacing, at, f1), + None => false, + }, + None => false, + }; // Each code's character, if it has one that shows (control codes don't). let chars = match &plain { Some((_, glyphs)) => glyphs.iter().map(|g| g.ch).collect::>(), @@ -685,7 +696,49 @@ impl Interp<'_> { codes.push(u32::from(code), c.filter(|c| !c.is_control())); } let widths: Option> = plain.map(|(_, glyphs)| glyphs.iter().map(|g| g.width).collect()); - self.show_codes(&codes, widths.as_deref(), spacing, false, s, Draw::Fill) + self.show_codes(&codes, widths.as_deref().map(|of| Widths { of, kept }), spacing, false, s, Draw::Fill) + } + + /// The glyphs of codes `glyphs` in font program `data` (the current font's) gathered for the + /// font kept from the file for their family and style, when that family isn't available and + /// the type shows: `Some(true)` gathered, `Some(false)` a character's glyph differs from the + /// one that font has for it, `None` not kept (the family is available, the type draws nothing + /// or is drawn apart, or a glyph can't be read). + fn keep_file_glyphs(&mut self, data: &Embedded, glyphs: &[Plain]) -> Res> { + if self.g.paint.is_none() || self.g.null || self.out.apart > 0 { + return Ok(None); + } + let (name, _) = self.font()?; + let (family, style) = family_style(&name); + if family.is_empty() || vectorcraft_text::FontDb::global().find_family(&family).is_some() { + return Ok(None); + } + let mut file = Vec::with_capacity(glyphs.len()); + for g in glyphs { + let Some(ch) = g.ch.filter(|c| !c.is_control()) else { continue }; + let Some((outline, advance)) = data.glyph(g.gid) else { return Ok(None) }; + self.spend(data.take_work())?; + // Ems, y up, onto thousandths of an em. + file.push(FileGlyph { ch, outline: Affine::scale(1000.0) * outline, advance: advance * 1000.0 }); + } + if file.is_empty() { + return Ok(None); + } + let postscript = match name.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest.to_string(), + _ => name.clone(), + }; + let (fs_type, metrics) = data.facts(); + let (ascent, descent) = metrics.unwrap_or_default(); + let info = || FileFontInfo { family: family.clone(), style: style.clone(), postscript, ascent, descent, fs_type }; + let font = self.out.file_glyphs.font(&family, &style, info); + if !self.out.file_glyphs.fits(font, &file) { + return Ok(Some(false)); + } + for g in file { + self.out.file_glyphs.add(font, g); + } + Ok(Some(true)) } /// The codes `codes` (each standing for some of its characters, or none) shown in the current @@ -698,12 +751,14 @@ impl Interp<'_> { fn show_codes>( &mut self, codes: &Decoded, - widths: Option<&[f64]>, + widths: Option, spacing: &Spacing, vertical: bool, kern: &[C], draw: Draw, ) -> Res { + let kept = widths.is_some_and(|w| w.kept); + let widths = widths.map(|w| w.of); let at = self.user_point()?; let (_, f1) = self.font()?; let text = &codes.text; @@ -717,6 +772,17 @@ impl Interp<'_> { *n += g.advance; } } + if kept && let Some(widths) = widths { + let mut k = 0; + for (i, &(_, n)) in codes.codes.iter().enumerate() { + if n == 1 + && let Some(slot) = natural.get_mut(k) + { + *slot = widths.get(i).copied().unwrap_or(0.0) * size; + } + k += n; + } + } // Each code's move (user space) and that move in text space, along the baseline (down the // column) and across. let em = |x: f64| f1 * if vertical { Point::new(0.0, -x) } else { Point::new(x, 0.0) } - f1 * Point::ZERO; @@ -1328,7 +1394,7 @@ impl Interp<'_> { }; let saved = self.g.font.replace(named.font.clone()); let before = std::mem::replace(&mut self.kshow_font, saved.clone()); - let r = self.show_codes(&named.codes, widths.as_deref(), spacing, named.vertical, &kern, draw); + let r = self.show_codes(&named.codes, widths.as_deref().map(|of| Widths { of, kept: false }), spacing, named.vertical, &kern, draw); self.kshow_font = before; self.g.font = saved; r @@ -1675,6 +1741,15 @@ impl Interp<'_> { } } +/// The widths of the codes [`Interp::show_codes`] shows (glyph space, one unit an em). With +/// `kept`, the type is drawn in a font kept from the file whose glyphs are that wide (see +/// `file_fonts`), so they are its characters' advances, not the layout's. +#[derive(Clone, Copy)] +struct Widths<'a> { + of: &'a [f64], + kept: bool, +} + /// A character code of a font carrying its program: the character it stands for (`None` when /// neither its glyph name nor the font says), its glyph and the glyph's width (ems). struct Plain { diff --git a/crates/eps/src/import/type1.rs b/crates/eps/src/import/type1.rs index 3000077721..7e411d8707 100644 --- a/crates/eps/src/import/type1.rs +++ b/crates/eps/src/import/type1.rs @@ -51,6 +51,21 @@ impl Embedded { } } + /// What the font program says of its licence (OS/2 `fsType`) and its ascent and descent + /// (thousandths of an em, the descent negative): a TrueType font's tables. A Type 1 font + /// says neither. + pub fn facts(&self) -> (Option, Option<(f64, f64)>) { + use skrifa::MetadataProvider; + use skrifa::raw::TableProvider; + let Self::TrueType(f) = self else { return (None, None) }; + let Ok(font) = skrifa::FontRef::new(&f.data) else { return (None, None) }; + let fs_type = font.os2().ok().map(|o| o.fs_type()); + let m = font.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + let k = 1000.0 / f64::from(m.units_per_em.max(1)); + let (ascent, descent) = (f64::from(m.ascent) * k, f64::from(m.descent) * k); + (fs_type, (ascent.is_finite() && descent.is_finite() && ascent > 0.0 && descent <= 0.0).then_some((ascent, descent))) + } + /// The character glyph `gid` stands for, when the font says (a TrueType font's character /// map or `post` names; a Type 1 glyph's name). pub fn char_of(&self, gid: u32) -> Option { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 932138e226..e33d9f795a 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -422,6 +422,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-22 | minor | EPS import: type in a Type 1 or Type 42 font the file carries, whose family isn't available, is drawn in a TrueType font built from the glyphs the file shows (outlines and advances from the font program), kept with the document as PDF import keeps a PDF's (#4569), and spaced by those glyphs' own advances; once its text is edited it takes the fallback font. A string that draws a character with another glyph than the one kept for it comes in as outlines. The warning names those families with PDF import's words ("show as the file draws them, in the fonts it carries, until their text is edited"). Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. Tests `embedded_type1_type_draws_with_the_files_glyphs`, `a_second_glyph_for_a_character_keeps_its_type_as_outlines`, `kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited`, `type_in_fonts_that_arent_available_is_named_in_a_warning` in `crates/eps/src/import/tests_type1.rs`, `type_in_a_carried_type42_font_draws_with_the_files_glyphs` in `crates/eps/src/import/tests_type42.rs`; scores unchanged | | 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | | 2026-11-12 | minor | #4569: document-owned file-font bindings, exact-byte identity checks and reclaimable live-face allowance; preserve referenced fallback bindings through installed-font removal, transfer placement leases/resources, relink older-save font keys, and restore recovery blobs before binding/diagnostics. Regression sources cover native/clipboard/export, Place/Break Link/older saves/recovery and isolated text/renderer ownership. Format-only verification; compilation and runtime proof pending. Scores and estimates unchanged. | From 104197e298cb92a9bf09b784267599ff234dea2c Mon Sep 17 00:00:00 2001 From: JonRC Date: Mon, 23 Nov 2026 00:53:54 -0300 Subject: [PATCH 2/5] EPS file fonts: compare each glyph once, and keep a full font's new characters as outlines `fits` compared each glyph with every earlier glyph of its character in the string, so a long string of one character took quadratic work. It now compares each glyph once with the one its character already has, as PDF import's gathering does. It also checks the font has room for the characters it doesn't have yet: a string that needs one more than the font can hold comes in as outlines, keeping the file's look, instead of as type the kept font can't draw. --- crates/eps/src/import/file_fonts.rs | 61 +++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/import/file_fonts.rs b/crates/eps/src/import/file_fonts.rs index 0ce2046aea..7d9e7f643c 100644 --- a/crates/eps/src/import/file_fonts.rs +++ b/crates/eps/src/import/file_fonts.rs @@ -50,15 +50,24 @@ impl FileFontGlyphs { i } - /// Can `glyphs` all be drawn in font `font`: no character among them has a glyph there, or in - /// `glyphs` itself, that differs in outline or advance? A font keeps one glyph per character. + /// Can `glyphs` all be drawn in font `font`: no character among them has a glyph there, or + /// earlier in `glyphs`, that differs in outline or advance (a font keeps one glyph per + /// character), and the font has room for the characters it doesn't have yet? Each glyph is + /// compared with the one its character has, once, as PDF import does. pub fn fits(&self, font: usize, glyphs: &[FileGlyph]) -> bool { let Some(f) = self.fonts.get(font) else { return false }; - let same = |a: &FileGlyph, b: &FileGlyph| a.outline == b.outline && a.advance == b.advance; - glyphs.iter().enumerate().all(|(i, g)| { - f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).is_none_or(|kept| same(kept, g)) - && glyphs.iter().take(i).filter(|e| e.ch == g.ch).all(|e| same(e, g)) - }) + let mut new: HashMap = HashMap::new(); + for g in glyphs { + let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied()); + match kept { + Some(k) if k.outline != g.outline || k.advance != g.advance => return false, + Some(_) => {} + None => { + new.insert(g.ch, g); + } + } + } + f.glyphs.len().saturating_add(new.len()) <= MAX_FILE_GLYPHS && self.count.saturating_add(new.len()) <= MAX_GLYPHS } /// Gather `glyph` for font `font`, unless it already has one for its character or is full. @@ -131,3 +140,41 @@ pub(crate) fn keep_file_fonts(nodes: &mut [Arc], kept: &HashMap<(String, S } } } + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::Shape; + + fn glyph(ch: char) -> FileGlyph { + FileGlyph { ch, outline: kurbo::Rect::new(0.0, 0.0, 400.0, 500.0).to_path(0.1), advance: 600.0 } + } + + /// A font full of glyphs takes no new character, so a string that needs one doesn't fit (it + /// comes in as outlines rather than as type the kept font can't draw); its own characters + /// still fit. + #[test] + fn a_full_font_takes_no_new_character() { + let mut g = FileFontGlyphs::default(); + let f = g.font("F", "Regular", FileFontInfo::default); + let chars: Vec = (0x10000u32..).filter_map(char::from_u32).take(MAX_FILE_GLYPHS).collect(); + for &c in &chars { + g.add(f, glyph(c)); + } + assert!(g.fits(f, &[glyph(chars[0]), glyph(chars[1])])); + assert!(!g.fits(f, &[glyph(chars[0]), glyph('A')])); + } + + /// A long string of one character compares each glyph with that character's once, not with + /// every one before it: a quarter of a million of them fit at once. + #[test] + fn a_long_string_of_one_character_fits_in_linear_time() { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut g = FileFontGlyphs::default(); + let f = g.font("F", "Regular", FileFontInfo::default); + tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok(); + }); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true)); + } +} From 610849efa304caeab38f508523750c68d167bfd5 Mon Sep 17 00:00:00 2001 From: JonRC Date: Mon, 23 Nov 2026 00:53:54 -0300 Subject: [PATCH 3/5] EPS file fonts: only type shown in a carried font gets the kept font The kept fonts were attached by family and style, so type in a font the file only names whose family and style are those of a carried font (`TestOne-Roman` beside an embedded `TestOne`) got the carried font too, after its spacing had been set for the fallback font. Type shown in a carried font is now marked when it is made, and only marked type gets the kept font. --- crates/eps/src/import/file_fonts.rs | 24 ++++++++++++++++++------ crates/eps/src/import/tests_type1.rs | 13 +++++++++++++ crates/eps/src/import/text.rs | 8 +++++++- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/import/file_fonts.rs b/crates/eps/src/import/file_fonts.rs index 7d9e7f643c..83e51bb7ee 100644 --- a/crates/eps/src/import/file_fonts.rs +++ b/crates/eps/src/import/file_fonts.rs @@ -106,9 +106,10 @@ impl FileFontGlyphs { } } -/// The type among `nodes` (and in their groups) set in the families and styles `kept` holds fonts -/// for (family and style → the font's blob in `images`): drawn in them while its text is the -/// file's, and laid out again for its bounds. +/// The type among `nodes` (and in their groups) shown in fonts the file carries ([`mark`]), in the +/// families and styles `kept` holds fonts for (family and style → the font's blob in `images`): +/// drawn in them while its text is the file's, and laid out again for its bounds. Type in a font +/// the file only names keeps the fallback font, also where its family and style are the same. pub(crate) fn keep_file_fonts(nodes: &mut [Arc], kept: &HashMap<(String, String), String>, images: &BTreeMap) { if kept.is_empty() { return; @@ -121,6 +122,9 @@ pub(crate) fn keep_file_fonts(nodes: &mut [Arc], kept: &HashMap<(String, S keep_file_fonts(children, kept, images); } let NodeKind::Text(t) = &n.kind else { continue }; + if t.file_fonts.is_none() { + continue; + } let mut fonts: Vec = vec![]; for r in &t.runs { let (family, style) = (&r.style.font_family, &r.style.font_style); @@ -130,10 +134,11 @@ pub(crate) fn keep_file_fonts(nodes: &mut [Arc], kept: &HashMap<(String, S fonts.push(FileFont { family: family.clone(), style: style.clone(), key: key.clone() }); } } - if fonts.is_empty() { - continue; - } if let NodeKind::Text(t) = &mut Arc::make_mut(n).kind { + if fonts.is_empty() { + t.file_fonts = None; + continue; + } t.file_fonts = Some(Box::new(FileFonts::new(fonts, &t.plain_text()))); db.bind_file_fonts(t, |key| images.get(key)); t.cached_bounds = Some(vectorcraft_text::layout(db, t).bounds); @@ -141,6 +146,13 @@ pub(crate) fn keep_file_fonts(nodes: &mut [Arc], kept: &HashMap<(String, S } } +/// Mark type `t` as shown in a font the file carries, so that [`keep_file_fonts`] gives it the font +/// kept for its family and style (the key is filled in then). +pub(crate) fn mark(t: &mut vectorcraft_doc::TextObject) { + let fonts = t.runs.first().map(|r| FileFont { family: r.style.font_family.clone(), style: r.style.font_style.clone(), key: String::new() }); + t.file_fonts = Some(Box::new(FileFonts::new(fonts.into_iter().collect(), &t.plain_text()))); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs index d94be757ac..500bf897eb 100644 --- a/crates/eps/src/import/tests_type1.rs +++ b/crates/eps/src/import/tests_type1.rs @@ -178,6 +178,19 @@ fn embedded_type1_type_draws_with_the_files_glyphs() { assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs); } +/// Type in a font the file only names keeps the fallback font, and the spacing set for it, also +/// when its family and style are those of a font the file carries (`TestOne-Roman` beside the +/// embedded `TestOne`): only type shown in the carried font gets the font kept from it. +#[test] +fn a_named_font_in_a_carried_family_and_style_keeps_the_fallback_font() { + let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show /TestOne-Roman 50 selectfont 10 60 moveto (AA) show"); + let t = texts(&r); + assert_eq!(t.len(), 2, "{:?}", all(&r.document)); + assert_eq!((t[1].runs[0].style.font_family.as_str(), t[1].runs[0].style.font_style.as_str()), ("Test One", "Regular")); + assert!(t[0].file_fonts.is_some()); + assert!(t[1].file_fonts.is_none(), "the named font's type isn't drawn in the carried font"); +} + /// A character the file draws with a different glyph from the one the kept font already has for /// it (here a second font of the same name whose A is a narrower square) can't go in that font: /// that string comes in as outlines, the first stays type in the file's glyphs. diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index e88c4d3bb9..eff4f8b20e 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -823,10 +823,13 @@ impl Interp<'_> { for ((d, ..), &(_, n)) in moves.iter().zip(&codes.codes) { let c: String = chars.by_ref().take(n).collect(); if painted && !c.trim().is_empty() { - let (t, ..) = self.set_text_in(&c, pen, vertical)?; + let (mut t, ..) = self.set_text_in(&c, pen, vertical)?; if draw == Draw::Path { self.type_path(&t)?; } else { + if kept { + super::file_fonts::mark(&mut t); + } let clips = self.g.clips.clone(); self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips); } @@ -880,6 +883,9 @@ impl Interp<'_> { if draw == Draw::Path { self.type_path(&t)?; } else { + if kept { + super::file_fonts::mark(&mut t); + } let clips = self.g.clips.clone(); if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some() && let Some(after) = self.out.drawn.get_mut(start..) From a6511830f2d8fdfd6f038ca3b1a57fe4ef55f02b Mon Sep 17 00:00:00 2001 From: JonRC Date: Mon, 23 Nov 2026 00:53:54 -0300 Subject: [PATCH 4/5] EPS file fonts: decide carried or fallback per family and style The warning took a family as carried when any style of it was, so a named bold beside a carried regular lost its fallback warning. Carried and fallback are now decided per family and style, and a family can be named in both sentences. --- crates/eps/src/import.rs | 30 ++++++++++++++++------------ crates/eps/src/import/tests_type1.rs | 15 ++++++++++++++ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index f85ed7df3e..7833ef787d 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -320,17 +320,18 @@ fn read_checked(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncodi } /// The families of the type in `d` (its layers and its symbols) that aren't available, each once -/// in the order the type comes, at most [`MAX_MISSING_FONTS`]: the document's, whether its type -/// came from the page or from an editing copy, and none for type only measured or outlined. Those -/// drawn in fonts the file carries (bound to the document's type) come first, the rest second. +/// in the order the type comes, at most [`MAX_MISSING_FONTS`] a list: the document's, whether its +/// type came from the page or from an editing copy, and none for type only measured or outlined. +/// The first list holds those drawn in fonts the file carries (bound to the document's type), the +/// second those in the fallback font; a family whose styles differ in that is in both. fn missing_fonts(d: &Document) -> (Vec, Vec) { let db = vectorcraft_text::FontDb::global(); - let mut bound: HashSet = HashSet::new(); + let mut bound: HashSet<(String, String)> = HashSet::new(); let mut find_bound = |n: &Node| { if let NodeKind::Text(t) = &n.kind { for font in t.file_fonts_in_use() { if t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some() { - bound.insert(font.family.clone()); + bound.insert((font.family.clone(), font.style.clone())); } } } @@ -339,26 +340,29 @@ fn missing_fonts(d: &Document) -> (Vec, Vec) { for s in &d.symbols { s.art.walk(&mut find_bound); } - let mut checked: HashSet = HashSet::new(); - let mut missing: Vec = Vec::new(); + let mut checked: HashSet<(String, String)> = HashSet::new(); + let (mut carried, mut missing): (Vec, Vec) = (Vec::new(), Vec::new()); let mut add = |n: &Node| { let NodeKind::Text(t) = &n.kind else { return }; for run in &t.runs { - let family = run.style.font_family.as_str(); - if missing.len() >= MAX_MISSING_FONTS || family.is_empty() || checked.contains(family) { + let key = (run.style.font_family.clone(), run.style.font_style.clone()); + if key.0.is_empty() || checked.contains(&key) { continue; } - checked.insert(family.to_string()); - if db.find_family(family).is_none() { - missing.push(family.to_string()); + if db.find_family(&key.0).is_none() { + let list = if bound.contains(&key) { &mut carried } else { &mut missing }; + if list.len() < MAX_MISSING_FONTS && !list.contains(&key.0) { + list.push(key.0.clone()); + } } + checked.insert(key); } }; d.walk(&mut add); for s in &d.symbols { s.art.walk(&mut add); } - missing.into_iter().partition(|family| bound.contains(family)) + (carried, missing) } /// [`import_names`] before the type's fonts are checked (a `.ai` when `ai_file`, see [`import_ai`]). diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs index 500bf897eb..f83afc42de 100644 --- a/crates/eps/src/import/tests_type1.rs +++ b/crates/eps/src/import/tests_type1.rs @@ -178,6 +178,21 @@ fn embedded_type1_type_draws_with_the_files_glyphs() { assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs); } +/// 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] +fn a_carried_style_leaves_a_named_style_of_its_family_in_the_fallback_warning() { + let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show /TestOne-Bold 12 selectfont 10 80 moveto (x) show"); + assert_eq!(texts(&r).iter().map(|t| t.runs[0].style.font_style.as_str()).collect::>(), ["Regular", "Bold"]); + assert_eq!( + r.warnings, + [ + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One", + "fonts that aren't available show in the fallback font until they are: Test One", + ] + ); +} + /// Type in a font the file only names keeps the fallback font, and the spacing set for it, also /// when its family and style are those of a font the file carries (`TestOne-Roman` beside the /// embedded `TestOne`): only type shown in the carried font gets the font kept from it. From fc6b197b1c08b67a224a7f88e7dcc91f561fba94 Mon Sep 17 00:00:00 2001 From: JonRC Date: Mon, 23 Nov 2026 02:07:00 -0300 Subject: [PATCH 5/5] EPS file fonts: classify each type's fonts by its own bound fonts The carried families were collected for the whole document, so type in a font the file only names, of the same family and style as a carried font, counted as carried though it draws in the fallback font, and its fallback warning was missing. Each text's runs are now classified by the file fonts bound to that text. --- crates/eps/src/import.rs | 39 ++++++++++------------------ crates/eps/src/import/tests_type1.rs | 8 ++++++ 2 files changed, 22 insertions(+), 25 deletions(-) diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 7833ef787d..79316319a4 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -322,40 +322,29 @@ fn read_checked(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncodi /// The families of the type in `d` (its layers and its symbols) that aren't available, each once /// in the order the type comes, at most [`MAX_MISSING_FONTS`] a list: the document's, whether its /// type came from the page or from an editing copy, and none for type only measured or outlined. -/// The first list holds those drawn in fonts the file carries (bound to the document's type), the -/// second those in the fallback font; a family whose styles differ in that is in both. +/// The first list holds those of type drawn in fonts the file carries (bound to that type), the +/// second those of type in the fallback font; a family both happen to is in both. fn missing_fonts(d: &Document) -> (Vec, Vec) { let db = vectorcraft_text::FontDb::global(); - let mut bound: HashSet<(String, String)> = HashSet::new(); - let mut find_bound = |n: &Node| { - if let NodeKind::Text(t) = &n.kind { - for font in t.file_fonts_in_use() { - if t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some() { - bound.insert((font.family.clone(), font.style.clone())); - } - } - } - }; - d.walk(&mut find_bound); - for s in &d.symbols { - s.art.walk(&mut find_bound); - } - let mut checked: HashSet<(String, String)> = HashSet::new(); let (mut carried, mut missing): (Vec, Vec) = (Vec::new(), Vec::new()); let mut add = |n: &Node| { let NodeKind::Text(t) = &n.kind else { return }; + // The families and styles this type is drawn in from fonts the file carries. + let bound: Vec<(&str, &str)> = t + .file_fonts_in_use() + .iter() + .filter(|font| t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some()) + .map(|font| (font.family.as_str(), font.style.as_str())) + .collect(); for run in &t.runs { - let key = (run.style.font_family.clone(), run.style.font_style.clone()); - if key.0.is_empty() || checked.contains(&key) { + let (family, style) = (run.style.font_family.as_str(), run.style.font_style.as_str()); + if family.is_empty() { continue; } - if db.find_family(&key.0).is_none() { - let list = if bound.contains(&key) { &mut carried } else { &mut missing }; - if list.len() < MAX_MISSING_FONTS && !list.contains(&key.0) { - list.push(key.0.clone()); - } + let list = if bound.contains(&(family, style)) { &mut carried } else { &mut missing }; + if list.len() < MAX_MISSING_FONTS && !list.iter().any(|f| f == family) && db.find_family(family).is_none() { + list.push(family.to_string()); } - checked.insert(key); } }; d.walk(&mut add); diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs index f83afc42de..21ff20abec 100644 --- a/crates/eps/src/import/tests_type1.rs +++ b/crates/eps/src/import/tests_type1.rs @@ -204,6 +204,14 @@ fn a_named_font_in_a_carried_family_and_style_keeps_the_fallback_font() { assert_eq!((t[1].runs[0].style.font_family.as_str(), t[1].runs[0].style.font_style.as_str()), ("Test One", "Regular")); assert!(t[0].file_fonts.is_some()); assert!(t[1].file_fonts.is_none(), "the named font's type isn't drawn in the carried font"); + // The warning says so for each: one drawn as the file draws it, one in the fallback font. + assert_eq!( + r.warnings, + [ + "fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One", + "fonts that aren't available show in the fallback font until they are: Test One", + ] + ); } /// A character the file draws with a different glyph from the one the kept font already has for