From 546d274e6eff61daba8934eadf884557fb3284e7 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 07:18:04 +0000 Subject: [PATCH] .ai import: type takes the installed copy that sets its PDF part's widths When several installed faces answer to a text document font record's PostScript name and the record keeps no version (no key 5), type was set in whichever copy loaded first. Two copies can share the PostScript name, family and style and differ only in their widths (two releases of one font): the type then set at other widths than the file's own page, and envelopes of it could fail their drawn-art check. #6983 left this case out, as only the page's widths tell such copies apart. - `Opened::page_widths` (crates/pdf/src/page_widths.rs) reads the widths the pages give the characters of each font they set type in, from the font dictionaries alone and without importing any page: a simple font's `Widths` from `FirstChar`, a composite font's descendant's `W` under an `Identity-H`/`Identity-V` CMap, each code's character from the font's `ToUnicode` map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1 9.6.2, 9.7.4.3, 9.10.3, Annex D.2), by `BaseFont` without its subset tag. Zero widths (codes a subset doesn't use) are left out; subsets that give a character two widths give none. - Its cost is bounded by the file: each resource dictionary is walked once, however many pages and forms share it, within 65,536 entries for the whole file, 256 fonts and 4,096 forms; a width array that fonts share by reference is read once, and none past 4 MB of them; a `ToUnicode` map is parsed once for all the fonts that name it, and one over 256 KB decoded, or past 4 MB of maps in all (each charged at most what could be decoded of it), is left unread. `cid_ranges` reads a `W` list's values as it takes them instead of collecting the whole list. A font's widths are shared, not copied. - `postscript_face` (crates/eps/src/import/text.rs) takes, among the faces of the record's name, the first that sets those characters (the first 512 in code-point order) each within 1/1000 em. With no widths, one face, a version in the record, or no face that sets them all, the pick is the one before. The face found first is checked before any other is loaded, and the records of one name and version share their widths and their answer, so each font resolves once whatever the number of records. - The widths reach the text document through `Structure::page_widths` and `Texts::with_page_widths`; the engine reads them once per open and passes them to `ai_layers_alone`, `AiLayers::with_page_widths` and `ai_alone_with` when it reads a `.ai`'s editing copy beside a PDF part (not for a placeholder page). - `without_subset_tag` replaces two copies of the subset-tag strip in the PDF import, and `replacement` (a `ToUnicode` value that names no character) is shared with it. - A fuzz target feeds hostile font dictionaries, `ToUnicode` maps and forms that draw themselves to the reader. Measured on 224 users' files (used locally, never committed): 3 font records in 3 files change copy, each now within 0.5/1000 em of its page; those 3 renders, and no others, change, all closer to the file's own page; envelopes of type that open live go from 185 to 186, none fewer in any file; no file opens another way. Refs #6983 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/fileio/load.rs | 24 +- .../engine/src/cmd/fileio/tests_aiimport.rs | 107 ++++ crates/engine/tests/import_fuzz.rs | 55 +- crates/eps/src/ai_editing/writer/texts.rs | 4 +- crates/eps/src/import/ai/legacy_text.rs | 2 +- crates/eps/src/import/ai/read.rs | 4 + crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ate.rs | 68 +- crates/eps/src/import/native/build.rs | 25 +- crates/eps/src/import/native/layers.rs | 69 +- crates/eps/src/import/tests_native.rs | 117 +++- crates/eps/src/import/text.rs | 69 +- crates/pdf/src/import.rs | 1 + crates/pdf/src/import/builder.rs | 6 +- crates/pdf/src/import/cid.rs | 2 +- crates/pdf/src/import_scan.rs | 28 +- crates/pdf/src/import_text.rs | 6 +- crates/pdf/src/lib.rs | 2 + crates/pdf/src/page_widths.rs | 598 ++++++++++++++++++ crates/pdf/src/pages.rs | 7 + docs/file-format-parity.md | 5 +- docs/target-app-parity.md | 3 +- 22 files changed, 1111 insertions(+), 92 deletions(-) create mode 100644 crates/pdf/src/page_widths.rs diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ff0e14c40d..1e8cfdbe7d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -255,12 +255,15 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) return None; } let private = opened.illustrator_data()?; - Some(editing_copy_alone(&private, opts)) + // A placeholder page's fonts aren't the art's. + Some(editing_copy_alone(&private, opts, Default::default())) } -/// [`from_editing_data_alone`] of `private`, the editor's copy already read. -fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec)> { - vectorcraft_eps::ai_alone_with(private, opts.legacy_names) +/// [`from_editing_data_alone`] of `private`, the editor's copy already read, with `widths`, the +/// widths the file's PDF part gives the characters of its fonts, which tell installed copies of a +/// font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]). +fn editing_copy_alone(private: &[u8], opts: &LoadOptions, widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec)> { + vectorcraft_eps::ai_alone_with(private, opts.legacy_names, widths) .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))) } @@ -444,6 +447,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Err(e) => Err(err(e)), }; let mut read = restore_or_import(editing, || { + // The widths the PDF part gives the characters of its fonts, which tell installed + // copies of a font apart: read once, when the editing copy is. + let page_widths = std::cell::OnceCell::new(); + let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone(); // Type all from the text document and nothing that needs the PDF part: the layers // alone, the PDF part not imported. Else what was read of the layers is kept for // reading them with the PDF part. @@ -451,7 +458,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?))) { let pages = o.trim_pages(); - match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) { + match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) { Ok((mut doc, warnings)) => { doc.setup.bleed = pages.bleed; editing_data = true; @@ -473,9 +480,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // decoded draws nothing either): its notes are at most the page's own. let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); let copy_alone = || match &private { - Some(private) => Some(editing_copy_alone(private, opts)), + Some(private) => Some(editing_copy_alone(private, opts, widths())), None if layers.is_some() => { - opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts)) + opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths())) } None => None, }; @@ -487,7 +494,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let (doc, warnings, read) = match alone { Some((doc, warnings)) => (doc, warnings, true), None => { - let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode)); + let layers = + layers.or_else(|| private.as_deref().map(|p| vectorcraft_eps::AiLayers::decode(p).with_page_widths(widths()))); through_editing_data(layers, opts, r.document, r.warnings, r.user_unit) } }; diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..0274232b91 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -2072,3 +2072,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() { assert_eq!(r["restored"], json!(true), "{r}"); assert_eq!(open_rows(&s).1, ["Art", "Hidden"]); } + +/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the +/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in +/// a subset of that font that gives each character the width `width` gives it, in thousandths of an +/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is +/// 200 × 100 pt, and the page `page_width` × 100. +fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec { + let story = "Hamburg"; + let n = story.chars().count() + 1; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\ + /1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \ + /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n"; + let (art, drawn) = + if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") }; + let body = format!( + "%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", + ai::layer("Art", &art), + lines.join("\n") + ); + let data = ai::editing_data(200.0, 100.0, &body); + let widths: Vec = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let page = PdfPage { + resources: format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ), + entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)), + // A page that is only type, with its art box, isn't a placeholder. + art: Some([0.0, 0.0, page_width, 100.0]), + ..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET")) + }; + pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None) +} + +/// Type from the text document of a `.ai` whose font record keeps no version, where two installed +/// copies of the font share its PostScript name, family and style and differ in their widths, is +/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether +/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF +/// part is only type (read after the layers alone, on a page of another size, were not used). +#[test] +fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular")); + let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }; + // (a square beside the type, the page's width, the options, whether the PDF part is imported) + let cases = [ + (true, 200.0, &LoadOptions::default(), false), + (true, 200.0, &trim, true), + (false, 200.0, &LoadOptions::default(), false), + (false, 200.0, &trim, true), + (false, 260.0, &LoadOptions::default(), true), + ]; + for (square, page_width, opts, imported) in cases { + let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width); + let before = vectorcraft_pdf::imports_of(&file); + let loaded = load_with("copies.ai", &file, opts).unwrap(); + let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings); + assert!(loaded.editing_data, "{case}"); + assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}"); + let art = loaded.doc.layers[0].children().unwrap(); + assert_eq!(art.len(), 1 + usize::from(square), "{case}"); + let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") }; + assert_eq!(t.plain_text(), "Hamburg"); + assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}"); + } +} + +/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded +/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives. +fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> { + let db = vectorcraft_text::FontDb::global(); + for (inter, version) in [(true, "1.0"), (false, "1.1")] { + let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap(); + assert_eq!(db.add_font(font), 1); + } + let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap(); + move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em() +} + +/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that +/// copy's version in its font record, so it opens in the same copy again, from the editing copy +/// alone as from the whole file. +#[test] +fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular")); + let mut s = Session::new(); + let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap(); + let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let versions = |doc: &vectorcraft_doc::Document| -> Vec { + let art = doc.layers[0].children().unwrap(); + art.iter() + .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None }) + .collect() + }; + assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}"); + let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings); + let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap(); + assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 058476d071..dd124c59ed 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -6,7 +6,8 @@ //! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, //! opcodes with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of -//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents +//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a +//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the //! font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, @@ -896,6 +897,58 @@ proptest! { } } +/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any +/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite +/// font's `W` of any shape, and the `ToUnicode` map of object 5. +fn arb_width_font() -> impl Strategy { + ( + prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]), + prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]), + prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]), + prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12), + prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10), + prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]), + any::(), + ) + .prop_map(|(subtype, encoding, first, widths, w, name, mapped)| { + let map = if mapped { "/ToUnicode 5 0 R" } else { "" }; + format!( + "<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \ + /DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>", + widths.join(" "), + w.join(" ") + ) + }) +} + +proptest! { + #![proptest_config(config())] + + /// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read + /// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that + /// draw themselves. + #[test] + fn pdf_font_widths_never_panic( + fonts in prop::collection::vec(arb_width_font(), 1..4), + cmap in prop::collection::vec(prop::sample::select(vec![ + "begincmap", "1 begincodespacerange", "<0000> ", "<00> ", "endcodespacerange", "2 beginbfchar", "<0001> <0041>", + "<0002> ", "<41> ", "1 beginbfrange", "<0000> <0000>", " <0000> <0041>", "<0001> <0003> [<0041> <0042>]", + "endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar", + ]), 0..12), + ) { + let list: Vec = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect(); + let map = cmap.join("\n"); + let form = format!( + "<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream", + fonts[0] + ); + let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()]; + let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more); + let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths())); + prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}"); + } +} + /// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a /// broken `#` escape, a number with a stray `-`). fn arb_dict_value() -> impl Strategy { diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 506d13d9fc..d7a85dee26 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -612,7 +612,7 @@ fn font_name(st: &CharStyle) -> FontRecord { .collect(); let name = face.postscript_name(); // The reader takes the face of a name alone as `postscript_face` finds it. - let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id()); + let by_name = crate::import::postscript_face(&name, None, None).is_some_and(|f| f.id() == face.id()); let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() }; FontRecord { name, truetype: face.is_truetype(), design, version } } @@ -659,7 +659,7 @@ fn fixed(v: f32) -> i64 { fn font_kept(st: &CharStyle) -> bool { let record = font_name(st); let version = crate::import::record_version(&record.version); - let (family, style, read) = crate::import::document_font(&record.name, version); + let (family, style, read) = crate::import::document_font(&record.name, version, None); let db = vectorcraft_text::FontDb::global(); let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id()); family == st.font_family diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index a3864b43d0..e35f61cb54 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -564,7 +564,7 @@ impl Reader<'_> { st.cmap = cmap; // The installed face of that PostScript name, as type from a text document // takes it; else the name split into a family and style. - let text = super::super::super::text::named_font(name, None); + let text = super::super::super::text::named_font(name, None, None); let (family, style, version) = text.unwrap_or_else(|| { let (family, style) = super::super::super::text::family_style(name); (family, style, None) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index b045dd128f..7433243a10 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -217,6 +217,10 @@ pub struct Structure { /// name of the art style that gives each: the styles that are one paint, a pattern this read /// (see `ate::Texts::with_patterns`). pub text_patterns: HashMap, + /// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies + /// of a font apart for type whose font record keeps no version (see + /// `ate::Texts::with_page_widths`): none until the importer sets them. + pub page_widths: vectorcraft_pdf::PageWidths, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, /// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 258d7d584b..06e2de112e 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1395,6 +1395,7 @@ impl<'a> Reader<'a> { }, styles_read, text_patterns, + page_widths: Default::default(), canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index c971b250f2..9cb3273803 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -23,6 +23,7 @@ //! a layout has its point type's anchor at its frame's point. See [`Story::place`]. use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; @@ -564,15 +565,20 @@ struct DocFont { /// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed /// copies of one font apart. version: Option, - /// [`Self::font`]'s answer, found once for every run that names the record. - font: std::sync::OnceLock, + /// The widths the file's page gives the font's characters, when it has them + /// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record + /// of the font shares them. + widths: Option>, + /// [`Self::font`]'s answer, found once for every run that names the record, and shared by the + /// records of the same name and version, which give the same answer. + font: Arc>, } impl DocFont { /// The font type set in this record's font takes: the installed copy it names /// ([`super::text::document_font`]). fn font(&self) -> &Font { - self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref())) + self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref())) } } @@ -616,6 +622,17 @@ impl Texts { Texts { patterns, ..self } } + /// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`]) + /// gives the characters of its fonts, by each record's PostScript name: a record that keeps no + /// version is set in the installed copy of its font that sets them at those widths + /// ([`super::text::postscript_face`]). + pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts { + for f in &mut self.fonts { + f.widths = page.widths(super::text::bare_name(&f.name)).cloned(); + } + self + } + /// The text document in the editing copy `data`, if it has one that can be read. pub(super) fn read(data: &[u8]) -> Option { fn find(h: &[u8], n: &[u8], from: usize) -> Option { @@ -643,6 +660,8 @@ impl Texts { return None; } let doc = names::numbered(read(&bytes)?); + // Records of one name and version share their answer. + let mut answers: HashMap<(String, Option), Arc>> = HashMap::new(); let fonts = doc .get("0")? .get("1")? @@ -652,11 +671,10 @@ impl Texts { .map(|f| { let record = f.get("0").and_then(|f| f.get("0")); let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); - DocFont { - name: text("0").unwrap_or_default().to_string(), - version: text("5").and_then(record_version).map(str::to_string), - font: std::sync::OnceLock::new(), - } + let name = text("0").unwrap_or_default().to_string(); + let version = text("5").and_then(record_version).map(str::to_string); + let font = answers.entry((name.clone(), version.clone())).or_default().clone(); + DocFont { name, version, widths: None, font } }) .collect(); let main = doc.get("1")?; @@ -1592,6 +1610,40 @@ fn art_scale(to_doc: Affine) -> f64 { mod tests { use super::*; + /// The records of a text document's font list that name one font share the widths the file's + /// page gives it and the face they resolve to, however many there are: 20,000 records of a font + /// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record + /// of another version is resolved apart. + #[test] + fn records_of_one_font_share_its_page_widths_and_answer() { + let n = 20_000; + let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>"; + let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n"); + let data = + format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes())); + let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n16 beginbfrange\n"); + for hi in 1..=16u32 { + cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n")); + } + cmap.push_str("endbfrange\nendcmap\n"); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>" + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths(); + let shared = widths.widths("Sharetest-Regular").unwrap(); + assert_eq!(shared.len(), 4096); + let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths); + assert_eq!(texts.fonts.len(), n + 1); + assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared)))); + let first = &texts.fonts[0].font; + assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first))); + assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart"); + } + #[test] fn right_to_left_paragraphs_swap_left_and_right_alignment() { let texts = Texts { diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 86d6976d89..5374730368 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -178,17 +178,25 @@ impl ReadText { self.frames.get_or_insert_with(|| ai::text_frames(data)) } - /// The text document of `data` ([`Texts::read`]), if it has one that can be read. - fn texts(&mut self, data: &[u8]) -> Option<&Texts> { + /// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths + /// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given + /// when it is first read, before any of its fonts is found: each is found once, with the widths + /// it has then. Every check and build of one open passes the same widths. + fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> { self.forget_in_tests(); - self.texts.get_or_insert_with(|| Texts::read(data)).as_ref() + self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref() } /// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]). - fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap) -> Option<&Texts> { + fn texts_with( + &mut self, + data: &[u8], + patterns: std::collections::HashMap, + page_widths: &vectorcraft_pdf::PageWidths, + ) -> Option<&Texts> { self.forget_in_tests(); - let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns)); - self.texts.insert(texts).as_ref() + let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))); + self.texts.insert(read.map(|t| t.with_patterns(patterns))).as_ref() } } @@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo for info in &mut infos { info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone()))); } - let Some(texts) = text.texts(data) else { return false }; + let Some(texts) = text.texts(data, &structure.page_widths) else { return false }; let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos .iter() @@ -336,6 +344,7 @@ pub(super) fn build_weighing( envelopes_drawn, styles_read, text_patterns, + page_widths, canvas_scale, symbols_own_size, xml_ids, @@ -496,7 +505,7 @@ pub(super) fn build_weighing( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - let texts = text.texts_with(data, text_patterns); + let texts = text.texts_with(data, text_patterns, &page_widths); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d46da2b8ff..ef22d928b9 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -149,7 +149,7 @@ pub fn layered_ai_from( all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let AiLayers { data, structure, alone, mut text } = layers; + let AiLayers { data, structure, alone, mut text, page_widths } = layers; let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), @@ -189,10 +189,17 @@ pub fn layered_ai_from( add_notes(&mut all, read.notes()); (visible, all, false) }; + // The layers read, with the widths the PDF part gives the characters of its fonts. + let read = || { + ai::read_over_page(&data, false, names).map(|mut structure| { + structure.page_widths = page_widths.clone(); + structure + }) + }; // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); - let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); @@ -205,7 +212,7 @@ pub fn layered_ai_from( let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); if !live && let Some((mut done, notes)) = alone.and_then(|(pages, unit)| { - let mut structure = ai::read_over_page(&data, false, names).ok()?; + let mut structure = read().ok()?; // With none free, nothing needs settling again: every envelope keeps its drawn art. if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) { structure.warped_type.open_alone(free, count); @@ -244,32 +251,41 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { /// reading it, when the file's text document makes all of its type and nothing in its layers needs /// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the /// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part -/// is imported. `names`: the encoding of names that aren't UTF-8. -pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec), AiLayers> { +/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the +/// PDF part gives the characters of its fonts, which tell installed copies of a font apart +/// ([`AiLayers::with_page_widths`]). +pub fn ai_layers_alone( + private: &[u8], + pages: &[(f64, f64)], + unit: f64, + names: ai::NameEncoding, + page_widths: vectorcraft_pdf::PageWidths, +) -> Result<(Document, Vec), AiLayers> { let data = match ai::decode_private(private) { Ok(data) => data, - Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }), }; if !has_layers(&data) { - return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() }); + return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths }); } // An image past the hard limits is read as an unread box, which the PDF part's art replaces. - let structure = match ai::read_over_page(&data, false, names) { + let mut structure = match ai::read_over_page(&data, false, names) { Ok(structure) => structure, - Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }), }; + structure.page_widths = page_widths.clone(); let mut text = Box::::default(); // An envelope of type opens live only where the layers with it draw as the page, as the other // live envelopes do: the PDF part is imported to compare them with. Should none open live, the // layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]). if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() { let alone = Some((pages.to_vec(), unit)); - return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text }); + return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths }); } match build_without_page(structure, &data, pages, unit, &mut text) { Ok(Ok((doc, notes))) => Ok((doc, notes)), - Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }), - Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }), } } @@ -286,12 +302,27 @@ pub struct AiLayers { alone: Option<(Vec<(f64, f64)>, f64)>, /// The text objects' frames and the text document of the editing copy, as far as they were read. text: Box, + /// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]). + page_widths: vectorcraft_pdf::PageWidths, } impl AiLayers { /// The editing copy `private` (as [`layered_ai`] takes it), decoded. pub fn decode(private: &[u8]) -> Self { - Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default() } + Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default(), page_widths: Default::default() } + } + + /// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of + /// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no + /// version is set in the installed copy of its font that sets them at those widths, where + /// several copies answer to its name. The layers read before take them too, and a text document + /// read before is read again with them, since its fonts are found once, with the widths they had + /// then. + pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self { + if let Some(Ok(structure)) = &mut self.structure { + structure.page_widths = page_widths.clone(); + } + Self { page_widths, text: Box::default(), ..self } } } @@ -581,13 +612,17 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { /// Editing data written on a large canvas comes in at its declared scale: no page holds the size. /// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]). pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec), String> { - ai_alone_with(private, ai::NameEncoding::default()) + ai_alone_with(private, ai::NameEncoding::default(), Default::default()) } -/// [`ai_alone`], with the names that aren't UTF-8 read in `names`. -pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec), String> { +/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the +/// file's PDF part gives the characters of its fonts when it has one that holds the art +/// ([`AiLayers::with_page_widths`]). +pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec), String> { let data = ai::decode_private(private)?; - build_from(ai::read_in(&data, true, names)?, &data, None, Page::Artboard, false, false, 1.0) + let mut structure = ai::read_in(&data, true, names)?; + structure.page_widths = page_widths; + build_from(structure, &data, None, Page::Artboard, false, false, 1.0) } /// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height) diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index dbac845dad..8780c92c6a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() { assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1"); } +/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of +/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em. +fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let widths: Vec = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths() +} + +/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives +/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths. +fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let chars: Vec = text.chars().collect(); + let pairs: Vec = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect(); + let cmap = format!( + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n", + pairs.len(), + pairs.join("\n") + ); + let w: Vec = chars.iter().map(|c| width(*c).to_string()).collect(); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>", + w.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths() +} + +/// The advance of `c` in installed `face`, in thousandths of an em. +fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 { + face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em() +} + +/// The version of the face that type from the text document of a `.ai` whose font record is +/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the +/// widths its PDF part gives the characters of its fonts. +fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String { + let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1); + let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc)); + let names = crate::NameEncoding::default(); + let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") }; + let texts = text_of(&d.layers[0]); + assert_eq!(texts.len(), 1, "{record}: {notes:?}"); + vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone() +} + +/// Two installed copies of one font can share its PostScript name, family and style, and differ +/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no +/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF +/// part gives them, also when the record spells the name with other punctuation. Without those +/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first +/// loaded); a version the record keeps decides first. The widths of a simple font in +/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart. +#[test] +fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() { + install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]); + let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular"); + let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone(); + let (old, new) = (copy("1.0"), copy("1.1")); + assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths"); + let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c)); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0"); + // Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's. + let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0"); + // A record whose name differs from the copies' in punctuation alone, as its PDF part's font. + assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1"); + // Widths of another font, or no copy setting the characters at the PDF part's widths. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0"); + // A version the record keeps picks the copy, and one that isn't installed gives the copy it gave. + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0"); + // The widths of a composite font. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0"); + // A font installed once is set in that copy whatever the widths. + install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]); + assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0"); + // Of several copies that set the characters at the widths, the first in the order the faces + // are found (the first loaded). + install(&[ + (true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")), + ]); + assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1"); +} + /// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character /// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large /// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point @@ -6051,7 +6150,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; // A PDF part the layers don't draw as. let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); @@ -6060,7 +6159,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}"); assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); // A PDF part that draws as those layers, with the drawn art: the envelope opens live. - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6088,7 +6187,7 @@ fn layers_that_open_alone_read_their_text_once() { let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]); let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1))); let file = private(&native_with_text(&art, &doc)); - let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok(); + let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok(); let (opened, texts, frames) = text_reads(false, open); let Some((d, notes)) = opened else { panic!("didn't open without the page") }; assert_eq!((texts, frames), (1, 1), "{notes:?}"); @@ -6107,7 +6206,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() { let file = private(&native_with_text(&art, "not a text document")); let names = crate::NameEncoding::default(); let open = || { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names) }; let (opened, texts, frames) = text_reads(false, open); @@ -6134,7 +6233,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() { let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // A PDF part the layers don't draw as: they open alone, after a build with the page and one without. @@ -6218,7 +6317,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6312,7 +6411,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the envelope's drawn art: what the page draws. @@ -6355,7 +6454,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_ let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document, trust: bool| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names) }; let (mut page, _, _) = open(pdf_part(80.0, 80.0), false); @@ -6394,7 +6493,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the drawn art of both envelopes, but the first's: the page draws diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 3de16d7bbf..c3bb2f4d7a 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -44,7 +44,7 @@ fn style_word(w: &str) -> String { /// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy /// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`). -fn bare_name(name: &str) -> &str { +pub(super) fn bare_name(name: &str) -> &str { let name = match name.split_once('+') { Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, _ => name, @@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str { } /// The font of type that a text document's font record names: by `name`, its PostScript name, and -/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that -/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the -/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is +/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the +/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face +/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) +/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is /// Microsoft YaHei). → (family, style, version). /// /// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family -pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option) { - named_font(name, version).unwrap_or_else(|| { +pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option) { + named_font(name, version, widths).unwrap_or_else(|| { let (family, style) = family_style(name); let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); (family, style, None) @@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin } /// The font of type set in the installed face of PostScript name `name` (a subset prefix and a -/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and -/// style, and its version when the family and style alone resolve to another installed copy of -/// the font. A library can keep two copies under one family and style that differ in their -/// PostScript names or their versions, and draw the same text at different widths. → (family, -/// style, version); `None` when no installed face has the name. -pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option)> { - let face = postscript_face(bare_name(name), version)?; +/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths` +/// ([`postscript_face`]): that face's own family and style, and its version when the family and +/// style alone resolve to another installed copy of the font. A library can keep two copies under +/// one family and style that differ in their PostScript names or their versions, and draw the same +/// text at different widths. → (family, style, version); `None` when no installed face has the name. +pub(crate) fn named_font( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option<(String, String, Option)> { + let face = postscript_face(bare_name(name), version, widths)?; // As the PDF import names a version: only one that the family and style don't resolve to. let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style); let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone()); Some((face.family.clone(), face.style.clone(), version)) } +/// How far an installed face's advance may be from the width a page gives a character, in +/// thousandths of an em, for the face to set it at that width: files write widths rounded. +const PAGE_WIDTH_SLACK: f64 = 1.0; + +/// The most characters of a page's font [`sets_page_widths`] compares. +const MAX_WIDTHS_COMPARED: usize = 512; + +/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`]) +/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters +/// in code-point order are compared; a character the face has no glyph for isn't set at its width. +fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool { + let k = 1000.0 / face.units_per_em(); + widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| { + let gid = face.glyph_for(*c); + gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK + }) +} + /// The installed face of PostScript name `name` (without a subset prefix), among the installed /// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there /// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named /// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in -/// `version` when it is installed, else the first. `None` when no installed face has the name. +/// `version` when it is installed. Without a version, copies whose names, family and style are all +/// one can still set the type at other widths: of those, the first that sets the characters of +/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which +/// compares the first 512 characters). Else the first. `None` when no installed face has the name. /// /// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces -pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option> { +pub(crate) fn postscript_face( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option> { let db = vectorcraft_text::FontDb::global(); let found = db.find_postscript(name)?; - if found.postscript_name() == name && version.is_none_or(|v| v == found.version) { + let widths = widths.filter(|_| version.is_none()); + let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w)); + if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) { return Some(found); } let faces = db.postscript_faces(name); let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect(); let pool = if named.is_empty() { faces } else { named }; let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned()); - Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found)) + let by_widths = || pool.iter().find(|f| on_page(f)).cloned(); + Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found)) } /// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the @@ -620,7 +653,7 @@ impl Interp<'_> { } // The installed face of that PostScript name, as type from a text document takes it; else // the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". - let (font_family, font_style, font_version) = document_font(&name, None); + let (font_family, font_style, font_version) = document_font(&name, None, None); let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() }; let mut t = TextObject::point(Point::ZERO, text, style); diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index e5a5e2e382..46bf544e9f 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -38,6 +38,7 @@ mod entry; mod reshaped; mod state; +pub(crate) use cid::replacement; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; #[cfg(any(test, feature = "read-count"))] diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index e6e34ae429..677a0d4c67 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -842,11 +842,7 @@ impl<'p> Builder<'p> { let data = o.font_data(); let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.as_ref().and_then(|d| d.postscript_name.clone())); let (weight, italic) = data.as_ref().map_or((None, false), |d| (d.weight, d.is_italic)); - // A subset's six-letter tag. - let ps = name.as_deref().map(|n| match n.split_once('+') { - Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(), - _ => n.to_string(), - }); + let ps = name.as_deref().map(|n| crate::import_scan::without_subset_tag(n).to_string()); let installed = ps.as_deref().and_then(|ps| vectorcraft_text::FontDb::global().find_postscript(ps)); let n = match (installed, name) { (Some(face), _) => FontInfo { family: face.family.clone(), style: face.style.clone(), face: Some(face) }, diff --git a/crates/pdf/src/import/cid.rs b/crates/pdf/src/import/cid.rs index 60a28d15e1..b862ed336e 100644 --- a/crates/pdf/src/import/cid.rs +++ b/crates/pdf/src/import/cid.rs @@ -70,7 +70,7 @@ impl CidText { } /// A ToUnicode value that names no character: U+FFFD alone (#708). -pub(super) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool { +pub(crate) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool { use craft_pdf::interpret::hayro_cmap::BfString; match u { BfString::Char(c) => *c == char::REPLACEMENT_CHARACTER, diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..c2b81afc65 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -1041,19 +1041,26 @@ pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option /// Each CID a `W` or `W2` array (`per` numbers a CID) gives values for, and its values: `c [v…]` /// gives CIDs from c on their values in turn, `c_first c_last v…` the same values to each of the -/// range. At most [`MAX_CIDS`] CIDs are read. -fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { +/// range. At most [`MAX_CIDS`] CIDs are read, and a list's values only as far as they take; `per` +/// is 1 or 3. +pub(crate) fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { let mut it = a.flex_iter(); let mut read = 0; loop { if let Some((first, list)) = it.next::<(u32, Array<'_>)>() { - let values: Vec = list.iter::().collect(); - for (cid, v) in (first..=u32::MAX).zip(values.chunks_exact(per)) { + // Read as they are given, no more than the CIDs read take. + let mut values = list.iter::(); + let mut v = [0.0; 3]; + for cid in first..=u32::MAX { + let Some(group) = v.get_mut(..per) else { return }; + if group.iter_mut().any(|slot| values.next().map(|x| *slot = x).is_none()) { + break; + } read += 1; if read > MAX_CIDS { return; } - each(cid, v); + each(cid, group); } } else if per == 1 && let Some((first, last, w)) = it.next::<(u32, u32, f64)>() @@ -1081,11 +1088,20 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { } } +/// A font's PostScript name without its subset's six-letter tag (`ABCDEF+Name` is `Name`, ISO +/// 32000-1 §9.6.4). +pub(crate) fn without_subset_tag(name: &str) -> &str { + match name.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest, + _ => name, + } +} + /// The PostScript name of font `f`: its `BaseFont`. A composite (Type 0) font's `BaseFont` is its /// CIDFont's name, a hyphen and its CMap's (`Name-Identity-H`, ISO 32000-1 §9.7.6.1), so its /// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one, /// the `BaseFont` without the CMap's name on its end. -fn font_name(f: &Dict<'_>) -> Option { +pub(crate) fn font_name(f: &Dict<'_>) -> Option { if f.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") { if let Some(base) = f.get::>(b"BaseFont") { return Some(String::from_utf8_lossy(base.as_ref()).into_owned()); diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index ec4fff092a..e301a91c3a 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -1148,11 +1148,7 @@ impl Families { /// The family and style of a font with base (PostScript) name `name`, or of weight `weight` /// and slant `italic` when the name has no style; whether the family is available. pub fn resolve(&self, name: &str, weight: Option, italic: bool) -> (String, String, bool) { - // A subset's six-letter tag. - let name = match name.split_once('+') { - Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest, - _ => name, - }; + let name = crate::import_scan::without_subset_tag(name); // An installed face of that exact PostScript name: its own family and style. if let Some((family, style)) = vectorcraft_text::FontDb::global().by_postscript_name(name) { return (family, style, true); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index a5f93a2a76..cd070d8c6f 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -61,6 +61,7 @@ mod lab_spot; mod linearize; mod marks; mod output; +mod page_widths; mod pages; mod patch; mod pdfx; @@ -83,6 +84,7 @@ pub use import::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; +pub use page_widths::{FontWidths, PageWidths}; #[cfg(any(test, feature = "read-count"))] pub use pages::reads_of; pub use pages::{ diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs new file mode 100644 index 0000000000..aa1f122fcd --- /dev/null +++ b/crates/pdf/src/page_widths.rs @@ -0,0 +1,598 @@ +//! The widths a PDF's pages give the characters of the fonts they set type in, read from the font +//! dictionaries alone (no page is drawn): a simple font's `Widths` from its `FirstChar`, or a +//! composite font's descendant's `W`, each code's character from the font's `ToUnicode` map, or for +//! a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1 +//! §9.6.2, §9.6.6, §9.7.4.3, §9.10.3, Annex D.2). + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::rc::Rc; +use std::sync::Arc; + +use craft_pdf::interpret::hayro_cmap::{BfString, CMap}; +use craft_pdf::syntax::object::{Array, Dict, Name, ObjRef, ObjectIdentifier, Stream}; +use craft_pdf::syntax::page::Resources; + +use crate::import::replacement; +use crate::import_scan::{cid_ranges, font_name, without_subset_tag}; + +/// The most fonts read. +const MAX_FONTS: usize = 256; +/// The most form XObjects looked into, and how deep they may nest. +const MAX_FORMS: usize = 4096; +const MAX_FORM_DEPTH: u32 = 16; +/// The most entries of font and XObject resource dictionaries looked at, all pages and forms of the +/// file together (one budget for the whole file, not one a page). +const MAX_KEYS: usize = 1 << 16; +/// The most bytes of width arrays (`Widths`, `W`) read, all fonts together; an array that fonts +/// share by reference is read once. A subset's array is a few kilobytes. +const MAX_WIDTH_TEXT: usize = 4 << 20; +/// The most characters of a font kept. +const MAX_CHARS: usize = 4096; +/// The largest `ToUnicode` map read, decoded: a subset's map names a few hundred codes. A longer one +/// is left unread. +const MAX_TO_UNICODE: usize = 256 << 10; +/// The most bytes of `ToUnicode` maps decoded, all fonts together. +const MAX_TO_UNICODE_TOTAL: usize = 4 << 20; +/// How far apart two widths a file gives one character of one font may be and still be one width, +/// in thousandths of an em: files write widths rounded. +const SAME_WIDTH: f32 = 1.0; + +/// The widths a page gives the characters of one font, in thousandths of an em, by character. +pub type FontWidths = BTreeMap; + +/// The advance widths, in thousandths of an em, that a PDF's pages give the characters of the fonts +/// they set type in, by each font's PostScript name (its `BaseFont` without a subset prefix): what +/// the copy of the font the file was set in draws them at. A `.ai`'s PDF part has them for the type +/// its text document holds, so they tell installed copies of one font apart. A font whose subsets +/// give one character two widths gives none. Cloning it, or a font's widths, shares them. +#[derive(Clone, Debug, Default)] +pub struct PageWidths { + fonts: Arc>>, +} + +impl PageWidths { + /// Each character the pages set in the font of PostScript name `name` (exactly, without a + /// subset prefix) and its width (at most 4096 characters): `None` when the pages set none in + /// that font, or its subsets give a character two widths. + pub fn widths(&self, name: &str) -> Option<&Arc> { + self.fonts.get(name) + } +} + +/// Which dictionary `d` is, to look at it once: where its text lies in the file as read. One +/// dictionary that pages or forms share is read from the same place each time (one in an object +/// stream lies in that stream's decoded data, which the reader keeps); telling it by its contents +/// would hash it again for each of them. +fn dict_key(d: &Dict<'_>) -> (usize, usize) { + let text = d.data(); + (text.as_ptr() as usize, text.len()) +} + +/// Each CID a composite font's `W` gives a width, and that width. +type CidWidths = Rc<[(u32, f32)]>; + +/// What [`page_widths`] has read so far. +#[derive(Default)] +struct Walk { + /// Each font's characters and widths; `None` when two subsets disagree. + fonts: HashMap>, + /// The font dictionaries, form XObjects and resource dictionaries already looked at. + seen_fonts: HashSet<(usize, usize)>, + seen_forms: HashSet, + walked: HashSet<(usize, usize)>, + /// The `ToUnicode` maps parsed, by their stream: `None` for one that can't be read. + maps: HashMap>>, + /// The width arrays that fonts name by reference, read: a simple font's `Widths` (its first 256 + /// numbers) and a composite font's `W` (each CID and its width). + simple_widths: HashMap>>, + cid_widths: HashMap>, + /// How many entries of resource dictionaries have been looked at. + looked: usize, + /// How many bytes of `ToUnicode` maps have been decoded. + decoded: usize, + /// How many width arrays have been read, and how many bytes of them. + arrays_read: usize, + width_text: usize, +} + +impl Walk { + /// Note `widths`, characters of the font of PostScript name `name` and their widths. A width + /// another subset gave the character already must be the same. + fn add(&mut self, name: String, widths: Vec<(char, f32)>) { + let slot = self.fonts.entry(name).or_insert_with(|| Some(BTreeMap::new())); + let Some(have) = slot else { return }; + for (c, w) in widths { + if have.get(&c).is_some_and(|was| (was - w).abs() > SAME_WIDTH) { + *slot = None; + return; + } + if have.len() < MAX_CHARS { + have.insert(c, w); + } + } + } + + /// Look at one more entry of a resource dictionary: `false` once [`MAX_KEYS`] have been. + fn look(&mut self) -> bool { + self.looked += 1; + self.looked <= MAX_KEYS + } + + /// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to + /// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach + /// [`MAX_TO_UNICODE_TOTAL`], or when it can't be read. A map is charged what was decoded of it, + /// at most the limit: a stream written plain comes back whole without being decoded. + fn character_map(&mut self, s: &Stream<'_>) -> Option> { + let id = s.obj_id(); + if !self.maps.contains_key(&id) { + let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1); + let data = s.decoded_within(left).ok(); + self.decoded += data.as_ref().map_or(left, |d| d.len().min(left)); + let map = data.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE).and_then(|d| CMap::parse(&d, |_| None)); + self.maps.insert(id, map.map(Rc::new)); + } + self.maps.get(&id)?.clone() + } + + /// Count `array`'s text against [`MAX_WIDTH_TEXT`]: `None` once the width arrays read reach it. + fn width_array<'a>(&mut self, array: Option>) -> Option> { + let array = array.filter(|_| self.width_text < MAX_WIDTH_TEXT)?; + self.arrays_read += 1; + self.width_text += array.data().len(); + Some(array) + } + + /// The first 256 numbers of simple font `f`'s `Widths`, read once for all the fonts that name + /// the same array. + fn simple_widths(&mut self, f: &Dict<'_>) -> Option> { + let read = |w: &mut Self| w.width_array(f.get::>(b"Widths")).map(|a| a.iter::().take(256).collect::>()); + let Some(r) = f.get_ref(b"Widths") else { return read(self) }; + if let Some(have) = self.simple_widths.get(&r) { + return have.clone(); + } + let got = read(self); + self.simple_widths.insert(r, got.clone()); + got + } + + /// Each CID that composite font descendant `d`'s `W` gives a width, and the width, read once for all + /// the fonts that name the same array. + fn cid_widths(&mut self, d: &Dict<'_>) -> Option { + let read = |w: &mut Self| { + let a = w.width_array(d.get::>(b"W"))?; + let mut out = Vec::new(); + cid_ranges(&a, 1, |cid, v| { + if let [w0] = v { + out.push((cid, *w0 as f32)); + } + }); + Some(out.into()) + }; + let Some(r) = d.get_ref(b"W") else { return read(self) }; + if let Some(have) = self.cid_widths.get(&r) { + return have.clone(); + } + let got = read(self); + self.cid_widths.insert(r, got.clone()); + got + } +} + +/// [`PageWidths`] of the fonts of `pages` (each page's resources) and of the forms they draw. +pub(crate) fn page_widths<'a>(pages: impl IntoIterator>) -> PageWidths { + let walk = walk(pages); + let fonts = walk.fonts.into_iter().filter_map(|(name, w)| Some((name, Arc::new(w.filter(|w| !w.is_empty())?)))).collect(); + PageWidths { fonts: Arc::new(fonts) } +} + +/// Read the fonts of `pages` and of the forms they draw. Each resource dictionary is walked once, +/// though pages and forms share it; a form without resources of its own takes those of what draws +/// it, which are walked already. At most [`MAX_KEYS`] entries are looked at. +fn walk<'a>(pages: impl IntoIterator>) -> Walk { + let mut w = Walk::default(); + let mut stack: Vec<(Resources<'a>, u32)> = pages.into_iter().map(|r| (r.clone(), 0)).collect(); + while let Some((res, depth)) = stack.pop() { + if w.walked.insert(dict_key(&res.fonts)) { + for key in res.fonts.keys() { + if w.seen_fonts.len() >= MAX_FONTS || !w.look() { + break; + } + let Some(f) = res.fonts.get::>(key.as_ref()) else { continue }; + if w.seen_fonts.insert(dict_key(&f)) + && let Some((name, widths)) = font_widths(&f, &mut w) + { + w.add(name, widths); + } + } + } + if depth >= MAX_FORM_DEPTH || !w.walked.insert(dict_key(&res.x_objects)) { + continue; + } + for key in res.x_objects.keys() { + if w.seen_forms.len() >= MAX_FORMS || !w.look() { + break; + } + let Some(s) = res.x_objects.get::>(key.as_ref()) else { continue }; + let d = s.dict(); + let form = d.get::>(b"Subtype").is_some_and(|t| t.as_ref() == b"Form"); + if let (true, Some(own)) = (form, d.get::>(b"Resources")) + && w.seen_forms.insert(s.obj_id()) + { + stack.push((Resources::from_scope(Some(own), res.clone()), depth + 1)); + } + } + } + w +} + +/// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each +/// character it names, at most [`MAX_CHARS`]. A code's character comes from the font's `ToUnicode` +/// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding; +/// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A +/// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its +/// widths are in its own glyph space) and a font whose codes' characters can't be told. +fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32)>)> { + let subtype = f.get::>(b"Subtype")?; + if subtype.as_ref() == b"Type3" { + return None; + } + let name = without_subset_tag(&font_name(f)?).to_string(); + let composite = subtype.as_ref() == b"Type0"; + let encoding = f.get::>(b"Encoding"); + let to_unicode = f.get::>(b"ToUnicode").and_then(|s| walk.character_map(&s)); + let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding"); + if to_unicode.is_none() && !win_ansi { + return None; + } + let char_of = |code: u32| match &to_unicode { + Some(map) => match map.lookup_bf_string(code).filter(|u| !replacement(u)) { + Some(BfString::Char(c)) => Some(c), + _ => None, + }, + None => win_ansi_char(code), + }; + let width = |w: f32| (w.is_finite() && w > 0.0 && w < 1e5).then_some(w); + let mut widths = Vec::new(); + if composite { + if !encoding.is_some_and(|e| matches!(e.as_ref(), b"Identity-H" | b"Identity-V")) { + return None; + } + let d = f.get::>(b"DescendantFonts").and_then(|a| a.iter::>().next())?; + for (cid, w) in walk.cid_widths(&d)?.iter() { + if widths.len() >= MAX_CHARS { + break; + } + if let (Some(c), Some(w)) = (char_of(*cid), width(*w)) { + widths.push((c, w)); + } + } + } else { + let first = f.get::(b"FirstChar")?; + // A simple font's codes are bytes. + for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) { + if let (Some(c), Some(w)) = (char_of(code), width(*w)) { + widths.push((c, w)); + } + } + } + Some((name, widths)) +} + +/// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252 +/// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which +/// it gives the space and the hyphen a second time. +fn win_ansi_char(code: u32) -> Option { + /// Codes 128 to 159; `\0` where the encoding has no character. + const HIGH: [char; 32] = [ + '\u{20AC}', '\0', '\u{201A}', '\u{192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{2C6}', '\u{2030}', '\u{160}', '\u{2039}', + '\u{152}', '\0', '\u{17D}', '\0', '\0', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}', '\u{2DC}', + '\u{2122}', '\u{161}', '\u{203A}', '\u{153}', '\0', '\u{17E}', '\u{178}', + ]; + match code { + 0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF => char::from_u32(code), + 0x80..=0x9F => HIGH.get(usize::try_from(code - 0x80).ok()?).copied().filter(|c| *c != '\0'), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; + + /// A simple font named `name`, in `encoding`, whose widths from code `first` on are `widths`. + fn simple(subtype: &str, name: &str, encoding: &str, first: u32, widths: &str) -> String { + format!("<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /Encoding /{encoding} /FirstChar {first} /Widths [{widths}] >>") + } + + /// The pages' fonts are read from their resources and from the forms they draw, a subset's + /// prefix aside: a simple font's characters from `WinAnsiEncoding` (a code 0 wide is left out) + /// or its `ToUnicode` map, a composite font's from its `ToUnicode` map, by CID. The subsets of one + /// font come together; a font whose subsets give a character two widths, a font in another + /// encoding without a `ToUnicode` map, and a Type 3 font give none. + #[test] + fn the_pages_give_each_font_the_widths_of_its_characters() { + let extra = first_extra(2); + let fonts = [ + simple("TrueType", "ABCDEF+Sample-Regular", "WinAnsiEncoding", 65, "600 0 520.5"), + simple("Type1", "GHIJKL+Sample-Regular", "WinAnsiEncoding", 128, "700"), + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /MNOPQR+Wide-Bold-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /MNOPQR+Wide-Bold /W [3 [250 610]] >>] >>" + ), + simple("Type1", "Roman-Mac", "MacRomanEncoding", 65, "500"), + format!( + "<< /Type /Font /Subtype /Type1 /BaseFont /Mapped /Encoding /MacRomanEncoding /FirstChar 3 /Widths [333] /ToUnicode {extra} 0 R >>" + ), + "<< /Type /Font /Subtype /Type3 /BaseFont /Drawn /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [1] /FontMatrix [1 0 0 1 0 0] >>" + .to_string(), + simple("TrueType", "STUVWX+Clash", "WinAnsiEncoding", 65, "640"), + ]; + let resources = |fonts: &[String], more: &str| { + let list: Vec = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect(); + format!("/Font << {} >> {more}", list.join(" ")) + }; + let first = PdfPage { resources: resources(&fonts, &format!("/XObject << /Fm0 {} 0 R >>", extra + 1)), ..PdfPage::new(100.0, 100.0, "") }; + let second = PdfPage { + resources: resources(&[simple("TrueType", "YZABCD+Clash", "WinAnsiEncoding", 65, "600")], ""), + ..PdfPage::new(100.0, 100.0, "") + }; + let cmap = + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n2 beginbfchar\n<0003> <0020>\n<0004> <03A9>\nendbfchar\nendcmap\n"; + let form_font = simple("TrueType", "EFGHIJ+Formed", "WinAnsiEncoding", 97, "480"); + let file = pdf_with( + &[first, second], + &[ + &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), + &format!( + "<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Font << /F0 {form_font} >> >> /Length 0 >>\nstream\n\nendstream" + ), + ], + None, + ); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + let got = |name: &str| widths.widths(name).map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()); + assert_eq!(got("Sample-Regular"), Some(vec![('A', 600.0), ('C', 520.5), ('€', 700.0)])); + assert_eq!(got("Wide-Bold"), Some(vec![(' ', 250.0), ('Ω', 610.0)])); + assert_eq!(got("Mapped"), Some(vec![(' ', 333.0)])); + assert_eq!(got("Formed"), Some(vec![('a', 480.0)])); + for none in ["ABCDEF+Sample-Regular", "Roman-Mac", "Drawn", "Clash", "Missing"] { + assert_eq!(got(none), None, "{none}"); + } + } + + /// [`super::walk`] of the pages of `file`. + fn walked(file: &[u8]) -> super::Walk { + let o = crate::open_pdf(file, None).unwrap(); + let pages = o.pdf.pages(); + super::walk(pages.iter().map(|p| p.resources())) + } + + /// Each resource dictionary is walked once: forms without resources of their own (which take + /// those of what draws them), forms that share one, and pages that share one look at each + /// entry once, so a file of thousands of them reads in time in proportion to it. + #[test] + fn shared_resources_are_walked_once() { + let n = 4000; + let extra = first_extra(1); + let font = simple("TrueType", "Shared", "WinAnsiEncoding", 65, "500"); + // Forms without resources, then forms that share one resource dictionary (the last object). + let shared = extra + 2 * n; + let forms: Vec = (0..2 * n) + .map(|i| { + let own = if i < n { String::new() } else { format!("/Resources {shared} 0 R ") }; + format!("<< /Type /XObject /Subtype /Form /BBox [0 0 1 {i}] {own}/Length 0 >>\nstream\n\nendstream") + }) + .chain(std::iter::once(format!("<< /Font << /F0 {} >> >>", simple("TrueType", "Formed", "WinAnsiEncoding", 66, "600")))) + .collect(); + let names: Vec = (0..2 * n).map(|i| format!("/X{i} {} 0 R", extra + i)).collect(); + let page = PdfPage { resources: format!("/Font << /F0 {font} >> /XObject << {} >>", names.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let refs: Vec<&str> = forms.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert!(w.fonts.contains_key("Shared") && w.fonts.contains_key("Formed")); + // The page's font and forms, and the shared dictionary's font. + assert!(w.looked <= 1 + 2 * n + 1, "{} entries looked at", w.looked); + // A thousand pages that share one font dictionary of 4000 entries. + let pages_n = 1000; + let extra = first_extra(pages_n); + let entries: Vec = (0..n).map(|i| format!("/F{i} {} 0 R", extra + 1 + i % 50)).collect(); + let objects: Vec = std::iter::once(format!("<< {} >>", entries.join(" "))) + .chain((0..50).map(|i| simple("TrueType", &format!("S{i}"), "WinAnsiEncoding", 65, "500"))) + .collect(); + let pages: Vec = + (0..pages_n).map(|_| PdfPage { resources: format!("/Font {extra} 0 R"), ..PdfPage::new(100.0, 100.0, "") }).collect(); + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&pages, &refs, None)); + assert_eq!(w.fonts.len(), 50); + assert!(w.looked <= n, "{} entries looked at", w.looked); + } + + /// Past [`super::MAX_FONTS`] fonts no more entries are looked at. + #[test] + fn fonts_past_the_most_read_are_not_looked_at() { + let fonts: Vec = + (0..super::MAX_FONTS + 100).map(|i| format!("/F{i} {}", simple("TrueType", &format!("N{i}"), "WinAnsiEncoding", 65, "500"))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let w = walked(&pdf_with(&[page], &[], None)); + assert_eq!(w.fonts.len(), super::MAX_FONTS); + assert!(w.looked <= super::MAX_FONTS + 1, "{} entries looked at", w.looked); + } + + /// Past [`super::MAX_KEYS`] entries of resource dictionaries, none are looked at: a font + /// dictionary of more entries than that, all naming one font, is looked at that far. + #[test] + fn entries_past_the_most_looked_at_are_left() { + let extra = first_extra(1); + let entries: Vec = (0..super::MAX_KEYS + 1000).map(|i| format!("/F{i} {extra} 0 R")).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", entries.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let w = walked(&pdf_with(&[page], &[&simple("TrueType", "Many", "WinAnsiEncoding", 65, "500")], None)); + assert_eq!(w.fonts.len(), 1); + assert!(w.looked <= super::MAX_KEYS + 1, "{} entries looked at", w.looked); + } + + /// A width array that fonts share by reference is read once for all of them: 128 composite + /// fonts naming one `W` and 128 simple fonts naming one `Widths`, each of 100,000 numbers. + #[test] + fn a_width_array_fonts_share_is_read_once() { + let numbers = 100_000; + let big: String = std::iter::repeat_n("500 ", numbers).collect(); + let extra = first_extra(1); + let cmap = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfrange\n<0000> <00FF> <0041>\nendbfrange\nendcmap\n"; + let fonts: Vec = (0..256) + .map(|i| { + if i % 2 == 0 { + format!( + "/F{i} << /Type /Font /Subtype /Type0 /BaseFont /W{i} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W {extra} 0 R >>] >>", + extra + 1 + ) + } else { + format!( + "/F{i} << /Type /Font /Subtype /TrueType /BaseFont /S{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>", + extra + 2 + ) + } + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let file = pdf_with( + &[page], + &[&format!("[0 [{big}]]"), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), &format!("[{big}]")], + None, + ); + let w = walked(&file); + assert_eq!(w.arrays_read, 2); + assert!(w.width_text <= 2 * (big.len() + 10), "{} bytes of width arrays read", w.width_text); + assert_eq!(w.fonts.len(), 256); + assert!(w.fonts.values().all(|f| f.as_ref().is_some_and(|f| f.get(&'A') == Some(&500.0)))); + } + + /// Past [`super::MAX_WIDTH_TEXT`] bytes of width arrays no more are read: of six fonts each with + /// an array of a million bytes, the sixth gives no widths. + #[test] + fn width_arrays_past_the_most_read_are_left() { + let big: String = std::iter::repeat_n("500 ", 250_000).collect(); + let extra = first_extra(1); + let fonts: Vec = (0..6) + .map(|i| { + format!( + "/F{i} << /Type /Font /Subtype /TrueType /BaseFont /M{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>", + extra + i + ) + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let arrays: Vec = (0..6).map(|_| format!("[{big}]")).collect(); + let refs: Vec<&str> = arrays.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert_eq!(w.arrays_read, 5); + assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5); + } + + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an + /// incomplete last group left out) and a range's to each, and reads no more of a long list than + /// the CIDs it takes. + #[test] + fn cid_ranges_give_each_cid_its_values() { + let extra = first_extra(1); + let long: String = std::iter::repeat_n("7 ", 70_000).collect(); + let arrays = ["[1 [10 20 30] 100 102 7]".to_string(), "[1 [1 2 3 4 5 6 7]]".to_string(), format!("[0 [{long}]]")]; + let page = PdfPage { + resources: format!("/Properties << /A {extra} 0 R /B {} 0 R /C {} 0 R >>", extra + 1, extra + 2), + ..PdfPage::new(10.0, 10.0, "") + }; + let refs: Vec<&str> = arrays.iter().map(String::as_str).collect(); + let file = pdf_with(&[page], &refs, None); + let o = crate::open_pdf(&file, None).unwrap(); + let pages = o.pdf.pages(); + let props = &pages.iter().next().unwrap().resources().properties; + let ranges = |key: &str, per: usize| { + let mut out = vec![]; + crate::import_scan::cid_ranges(&props.get::>(key).unwrap(), per, |cid, v| { + out.push((cid, v.to_vec())) + }); + out + }; + let one = |v: &[(u32, f64)]| v.iter().map(|(c, w)| (*c, vec![*w])).collect::>(); + assert_eq!(ranges("A", 1), one(&[(1, 10.0), (2, 20.0), (3, 30.0), (100, 7.0), (101, 7.0), (102, 7.0)])); + assert_eq!(ranges("B", 3), [(1, vec![1.0, 2.0, 3.0]), (2, vec![4.0, 5.0, 6.0])]); + assert_eq!(ranges("C", 1).len(), 65_536); + } + + /// A `ToUnicode` map written plain and longer than the limits is charged no more than a + /// decoded one could be: the small maps of the other fonts are still read. + #[test] + fn a_long_plain_map_leaves_the_others_read() { + let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE_TOTAL + 1000 { + big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let small = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0042>\nendbfchar\nendcmap\n"; + let extra = first_extra(1); + let cid = |name: &str, map: usize| { + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>", + extra + map + ) + }; + let n = 40; + let fonts: Vec = + std::iter::once(format!("/A {}", cid("Big", 0))).chain((0..n).map(|i| format!("/F{i} {}", cid(&format!("Small{i}"), 1 + i)))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let objects: Vec = std::iter::once(format!("<< /Length {} >>\nstream\n{big}endstream", big.len())) + .chain((0..n).map(|_| format!("<< /Length {} >>\nstream\n{small}endstream", small.len()))) + .collect(); + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert!(w.fonts.get("Big").is_some_and(Option::is_none) || !w.fonts.contains_key("Big")); + assert_eq!((0..n).filter(|i| w.fonts.get(&format!("Small{i}")).is_some_and(|f| f.as_ref().is_some_and(|m| !m.is_empty()))).count(), n); + assert!(w.decoded <= super::MAX_TO_UNICODE + 1 + n * small.len(), "{} bytes charged", w.decoded); + } + + /// A `ToUnicode` map is parsed once however many fonts name it, and one longer than + /// [`super::MAX_TO_UNICODE`] decoded is left unread, whether its stream is written plain or + /// compressed: its fonts give no widths. + #[test] + fn a_to_unicode_map_is_read_once_and_only_up_to_its_limit() { + use std::io::Write as _; + let small = + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\nendcmap\n".to_string(); + let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE { + big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + z.write_all(big.as_bytes()).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02X}")).collect(); + let extra = first_extra(1); + let cid = |name: &str, map: usize| { + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>", + extra + map + ) + }; + let fonts: Vec = (0..64).map(|i| format!("/F{i} {}", cid(&format!("U{i}"), i % 3))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let file = pdf_with( + &[page], + &[ + &format!("<< /Length {} >>\nstream\n{small}endstream", small.len()), + &format!("<< /Length {} >>\nstream\n{big}endstream", big.len()), + &format!("<< /Length {} /Filter [/ASCIIHexDecode /FlateDecode] >>\nstream\n{hex}>\nendstream", hex.len() + 1), + ], + None, + ); + let w = walked(&file); + assert_eq!(w.maps.len(), 3, "each map parsed once"); + // Each long one charged up to just past the limit. + assert!(w.decoded <= small.len() + 2 * (super::MAX_TO_UNICODE + 1), "{} bytes charged", w.decoded); + assert_eq!(w.maps.values().filter(|m| m.is_some()).count(), 1, "the long ones left unread"); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + assert_eq!(widths.widths("U0").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()), Some(vec![('A', 500.0)])); + assert!(widths.widths("U1").is_none() && widths.widths("U2").is_none()); + // Every font of the name shares one map of its widths. + assert!(std::sync::Arc::ptr_eq(widths.widths("U0").unwrap(), widths.clone().widths("U0").unwrap())); + } +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 64e6217148..1c9a2c3908 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -276,6 +276,13 @@ impl Opened { crate::file_info::file_info_in(&self.pdf) } + /// The widths the pages give the characters of the fonts they set type in, from the fonts' + /// dictionaries ([`crate::PageWidths`]), without importing any page's art. + pub fn page_widths(&self) -> crate::PageWidths { + let pages = self.pdf.pages(); + crate::page_widths::page_widths(pages.iter().map(|p| p.resources())) + } + /// How many pages the PDF has, as [`info`] lists them. pub fn page_count(&self) -> usize { self.pdf.pages().len() diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0cc9985a9c..3e87bbb974 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where several copies share its PostScript name, follows #6983; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -59,7 +59,7 @@ private editing data. VectorCraft: and the paragraph's hyphenation options and tab stops. Stroked type keeps its stroke's cap, join and miter limit. Type filled or stroked with a pattern keeps its pattern, placed in the document as a path's pattern fill would be: a character's paint names an art style of one paint, and the pattern is in that style (its colour in the text document is black). A pattern the file - doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one + doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. A record that keeps no version, in a `.ai` with a PDF part, takes among those faces the first that sets the characters the PDF part draws in that font (the first 512 in code-point order) each within 1/1000 em of the width the PDF part gives it (its `Widths` or `W`, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding`): two copies can share a name, family and style and set the type at other widths (two releases of one font). Without such widths, or with no face that sets them all, it takes the first, as before. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one frame whose last lines the file sets but which don't fit here (the fallback font, or a descent past the frame's bottom) may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines, with a warning when it does. RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb` @@ -361,6 +361,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version (no key 5), where several installed faces answer to the record's PostScript name, is set in the one whose advances match the widths the file's PDF part gives the characters it draws in that font: the case #6983 left out, two copies of one PostScript name, family and style (two releases of one font) that differ only in their widths. The PDF part's fonts are read from their dictionaries alone, without importing its pages (`Opened::page_widths`, which looks into the forms they draw too): a simple font's `Widths` from its `FirstChar`, a composite font's descendant's `W` under an `Identity-H` or `Identity-V` CMap, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding` (ISO 32000-1 §9.6.2, §9.7.4.3, §9.10.3, Annex D.2), by `BaseFont` without its subset prefix. A code 0 wide is one the subset doesn't use and is left out; a font whose subsets give one character two widths gives none. Each resource dictionary is walked once, though pages and forms share it, and at most 65,536 of their entries (for the whole file, all pages together), 256 fonts and 4,096 forms are looked at; a width array that fonts share by reference is read once, and no more are read past 4 MB of them; a `ToUnicode` map is parsed once for all the fonts that name it, and one longer than 256 KB decoded, or past 4 MB of maps in all (each charged at most what could be decoded of it), is left unread. All the records of one font share its widths and the face they resolve to, so a text document of many records of one font holds one copy of them. Of the faces `postscript_face` finds for the name, the first that sets those characters (the first 512 of them in code-point order) each within 1/1000 em of its width takes the type, and the type names its version as before. With no widths for the font, one face, a version in the record (installed or not), or no face that sets them all, the face is the one taken before; each record is still resolved once. It applies whether the layers open alone, with the PDF part imported, or from the editing data alone beside a PDF part that is only type; a `.ai` saved without its PDF part, EPS and legacy `.ai` are unchanged. On 224 users' files (used locally, never committed), 332 font records have widths to compare: 299 already took a face that sets every character within 1/1000 em, 29 have none that does and keep their face, 1 keeps the version its record names, and 3 (one font installed in two releases, in 3 files) change copy, from up to 66/1000 em off the page to within 0.5/1000 em. Those 3 renders at 40 ppi, and no others, change, all closer to the file's own page (30.0% → 24.5%, 18.0% → 12.3% and 1.03% → 0.02% of the page differing; in the first two only that font's type changes, and the rest that differs is untouched); envelopes of type that open live go from 185 to 186, none fewer in any file; no file opens another way; in one file the note on type in an envelope gives way to the note of how far the layers differ from the page (0.2%), as its envelope now opens live. Tests: `page_widths::tests::the_pages_give_each_font_the_widths_of_its_characters`, `shared_resources_are_walked_once`, `fonts_past_the_most_read_are_not_looked_at`, `a_to_unicode_map_is_read_once_and_only_up_to_its_limit`, `a_long_plain_map_leaves_the_others_read`, `a_width_array_fonts_share_is_read_once`, `width_arrays_past_the_most_read_are_left`, `cid_ranges_give_each_cid_its_values` (`vectorcraft-pdf`), `tests_native::type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths`, `ate::tests::records_of_one_font_share_its_page_widths_and_answer` (`vectorcraft-eps`), `tests_aiimport::type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in`, `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save`, and the fuzz target `import_fuzz::pdf_font_widths_never_panic` (`vectorcraft-engine`). Scores unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) came in with butt caps, miter joins and a miter limit of 10 whatever the file stroked it with, while paths kept the graphics state's. The characters' stroke now takes the line cap (`J`), line join (`j`) and miter limit (`M`) of the graphics state, as a path's stroke does, and glyphs stroked with other ones start a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined, so the glyphs before it keep their stroke (#7741). Test `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`. Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f393c7b8d8..5eeaededb5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, follows #6983; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,6 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. |