From 40ceb9258a1a1547a03f22bf4bdaafc75a968cbf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 14:47:15 -0800 Subject: [PATCH] .ai import: a file opened without its PDF part reads its text document once Opening a .ai from its editing data alone checked whether the text document makes all of its type, then built the document, and each step decoded and parsed the text document and scanned the text objects' frames again. A file with envelopes of type, which waits on its PDF part, did this up to four times. The check and the builds now share one read of the frames and of the text document. It is kept with the decoded editing data for the build with the PDF part and for the build without it that can follow, also when the check failed. The build applies its own pattern paints to the shared text document, as before. The document and notes are unchanged: new tests compare them against the same opens with every check and build reading the text afresh, and count one read and one scan on each route. --- crates/eps/src/import/ai.rs | 2 + crates/eps/src/import/ai/frames.rs | 8 ++ crates/eps/src/import/ate.rs | 8 ++ crates/eps/src/import/native.rs | 2 + crates/eps/src/import/native/build.rs | 155 ++++++++++++++++++++++--- crates/eps/src/import/native/layers.rs | 29 ++--- crates/eps/src/import/tests_native.rs | 110 +++++++++++++++++- docs/target-app-parity.md | 1 + 8 files changed, 281 insertions(+), 34 deletions(-) diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 1a73f64a50..6676428408 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -41,6 +41,8 @@ pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright}; pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID}; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; +#[cfg(test)] +pub(crate) use frames::TEXT_FRAME_SCANS; pub(crate) use frames::text_frames; pub use obj::{NameEncoding, Names}; pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS; diff --git a/crates/eps/src/import/ai/frames.rs b/crates/eps/src/import/ai/frames.rs index f6b00c44c5..a792b4a665 100644 --- a/crates/eps/src/import/ai/frames.rs +++ b/crates/eps/src/import/ai/frames.rs @@ -21,9 +21,17 @@ const MAX_OBJECTS: usize = 100_000; const MAX_OBJECT: usize = 256 << 10; const OBJECT: &[u8] = b"/AI11Text :"; +#[cfg(test)] +thread_local! { + /// How many times [`text_frames`] has scanned an editing copy on this thread. + pub(crate) static TEXT_FRAME_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The `/Art` path of each text object of `data` (an editing copy's document text), in art space /// (y up), by its story and frame. Objects without a readable path are left out. pub(crate) fn text_frames(data: &[u8]) -> HashMap<(u32, usize), BezPath> { + #[cfg(test)] + TEXT_FRAME_SCANS.set(TEXT_FRAME_SCANS.get() + 1); let mut out = HashMap::new(); let mut at = 0; while let Some(i) = data.get(at..).and_then(|d| find(d, OBJECT)) { diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 0c73b65092..c971b250f2 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -576,6 +576,12 @@ impl DocFont { } } +#[cfg(test)] +thread_local! { + /// How many times [`Texts::read`] has read a text document on this thread. + pub(super) static TEXTS_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The text document of an editing copy. pub(super) struct Texts { stories: Vec, @@ -615,6 +621,8 @@ impl Texts { fn find(h: &[u8], n: &[u8], from: usize) -> Option { h.get(from..)?.windows(n.len()).position(|w| w == n).map(|p| p + from) } + #[cfg(test)] + TEXTS_READS.set(TEXTS_READS.get() + 1); let start = find(data, b"%AI11_BeginTextDocument", 0)?; let from = find(data, b"/ASCII85Decode", start)? + b"/ASCII85Decode".len(); let end = find(data, b"~>", from)? + 2; diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index ac57122bd4..dad13c569f 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -47,6 +47,8 @@ mod layers; mod plan; mod slots; +#[cfg(test)] +pub(crate) use build::READ_AFRESH; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index bb970debe3..86d6976d89 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -116,13 +116,20 @@ pub(super) type Built = Result<(Document, Vec), String>; /// look draws), no object is unread or has another placement or drawn art that the page would /// choose, no linked image shows a placeholder, and its artboards are the pages, one for one and of their size, in points or in the pages' /// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for -/// [`build_from`] with the page. -pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result> { - let Some(scale) = alone_scale(&structure, data, pages, unit) else { +/// [`build_from`] with the page. `text` keeps what was read of the text of `data` for the check and +/// the build, and for any later build of `data`. +pub(super) fn build_without_page( + structure: Structure, + data: &[u8], + pages: &[(f64, f64)], + unit: f64, + text: &mut ReadText, +) -> Result> { + let Some(scale) = alone_scale(&structure, data, pages, unit, text) else { return Err(Box::new(structure)); }; let (styles, own_size) = (structure.styles_read, structure.symbols_own_size); - let built = build_from(structure, data, None, Page::Artboard, false, false, 1.0).map(|(mut doc, notes)| { + let built = build_weighing(structure, data, None, Page::Artboard, false, false, 1.0, &mut None, text).map(|(mut doc, notes)| { if scale != 1.0 { // The graphic styles read from the file are drawn in its units too. scale_read_document(&mut doc, scale, styles, own_size); @@ -133,9 +140,56 @@ pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f6 } /// The scale [`build_without_page`] draws `structure` (the editing copy `data` read) at on `pages` -/// in units of `unit` points, when it builds it without the page. -pub(super) fn alone_scale(structure: &Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Option { - page_scale_alone(structure, pages, unit).filter(|_| nothing_waits_on_page(structure) && type_all_made(structure, data)) +/// in units of `unit` points, when it builds it without the page. `text` keeps what was read of the +/// text of `data`. +pub(super) fn alone_scale(structure: &Structure, data: &[u8], pages: &[(f64, f64)], unit: f64, text: &mut ReadText) -> Option { + page_scale_alone(structure, pages, unit).filter(|_| nothing_waits_on_page(structure) && type_all_made(structure, data, text)) +} + +/// The text objects' frames and the text document of an editing copy, each read the first time it +/// is asked for and kept for every later check and build of the same copy. +#[derive(Default)] +pub(super) struct ReadText { + /// [`ai::text_frames`] of the copy, once scanned. + frames: Option>, + /// [`Texts::read`] of the copy, once read: `Some(None)` when it has no text document that can + /// be read. + texts: Option>, +} + +#[cfg(test)] +thread_local! { + /// While set, [`ReadText`] keeps nothing on this thread: each check and build reads the text afresh. + pub(crate) static READ_AFRESH: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +impl ReadText { + /// Forgets what was read while [`READ_AFRESH`] is set (only in tests). + fn forget_in_tests(&mut self) { + #[cfg(test)] + if READ_AFRESH.get() { + *self = Self::default(); + } + } + + /// The `/Art` path of each text object of `data` ([`ai::text_frames`]). + fn frames(&mut self, data: &[u8]) -> &std::collections::HashMap<(u32, usize), kurbo::BezPath> { + self.forget_in_tests(); + 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> { + self.forget_in_tests(); + self.texts.get_or_insert_with(|| Texts::read(data)).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> { + 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() + } } /// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its @@ -152,17 +206,18 @@ fn nothing_waits_on_page(structure: &Structure) -> bool { /// Does the text document of `data` (read as `structure`) make the type of every text object, those /// that don't show included, with at least one that shows, and none of them type that a look draws? -fn type_all_made(structure: &Structure, data: &[u8]) -> bool { +/// The frames and the text document are read into `text` when it doesn't have them yet. +fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> bool { let mut infos = vec![]; collect_slots(&structure.doc.layers, true, &mut infos); if !infos.iter().any(|i| i.shown) || infos.iter().any(|i| i.look.is_some()) { return false; } - let frames = ai::text_frames(data); + let frames = text.frames(data); 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) = Texts::read(data) else { return false }; + let Some(texts) = text.texts(data) else { return false }; let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos .iter() @@ -244,13 +299,14 @@ pub(super) fn build_from( trust: bool, unit: f64, ) -> Result<(Document, Vec), String> { - build_weighing(structure, data, visible, page, outlined, trust, unit, &mut None) + build_weighing(structure, data, visible, page, outlined, trust, unit, &mut None, &mut ReadText::default()) } /// [`build_from`]. When the layers with their live envelopes don't draw as the page, and don't with /// the drawn art of every live envelope put back either, `free` is set to the envelopes of type /// (by their place among them, as read) that opened live and that the page doesn't hold against -/// them ([`held_back`]), whether or not the layers are then used, and however. +/// them ([`held_back`]), whether or not the layers are then used, and however. The text of `data` +/// is taken from `text`, and read into it when it doesn't have it yet. #[allow(clippy::too_many_arguments)] pub(super) fn build_weighing( structure: Structure, @@ -261,6 +317,7 @@ pub(super) fn build_weighing( trust: bool, unit: f64, free: &mut Option>, + text: &mut ReadText, ) -> Result<(Document, Vec), String> { let Structure { mut doc, @@ -425,7 +482,7 @@ pub(super) fn build_weighing( collect_slots(&doc.layers, true, &mut infos); super::slots::limit_look_slots(&mut doc.layers, &mut infos, shown.len(), outlined); // Each text object's own frame or path, by its story and frame. - let frames = ai::text_frames(data); + let frames = text.frames(data); for info in &mut infos { info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(to_doc * p.clone()))); } @@ -439,14 +496,14 @@ 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 = Texts::read(data).map(|t| t.with_patterns(text_patterns)); + let texts = text.texts_with(data, text_patterns); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos .iter() .map(|i| { let n = i.story?; - read.entry(n).or_insert_with(|| texts.as_ref().and_then(|t| t.story(n as usize)).map(Arc::new)).clone() + read.entry(n).or_insert_with(|| texts.and_then(|t| t.story(n as usize)).map(Arc::new)).clone() }) .collect(); if stories.iter().flatten().map(|s| s.len()).sum::() > MAX_TEXT { @@ -3311,4 +3368,72 @@ mod candidate_tests { assert!(typed && kept.node(drawn[0].0).is_none() && kept.node(drawn[1].0).is_some()); assert!(!notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}"); } + + /// The editing copy of a 100 × 100 file whose one layer holds a square and `stories` objects of + /// point type, each its own story, with the text document that makes them. + fn many_stories(stories: u32) -> Vec { + use crate::import::tests_native::{Story, layer, native_with_text, square, text_object, unsplit_text_document}; + let texts: Vec = (0..stories).map(|i| format!("Story {i}\r")).collect(); + let anchor = |i: u32| (8170.0 + f64::from(i % 40), 8180.0 + f64::from(i / 40 % 40)); + let list: Vec> = (0..stories).zip(&texts).map(|(i, t)| (t.as_str(), 0, anchor(i), (0.0, 0.0), 0.0)).collect(); + let objects: String = (0..stories).map(text_object).collect(); + native_with_text(&layer("Art", true, &format!("{}\n{objects}", square(10, 10))), &unsplit_text_document(&list)).into_bytes() + } + + /// The check and the build of layers that open without the page, each reading the text of the + /// editing copy afresh, as [`build_without_page`] did before it read it once for both. + fn alone_reading_twice(structure: Structure, data: &[u8], pages: &[(f64, f64)]) -> Option { + let scale = alone_scale(&structure, data, pages, 1.0, &mut ReadText::default())?; + assert_eq!(scale, 1.0); + Some(build_from(structure, data, None, Page::Artboard, false, false, 1.0)) + } + + /// Layers that open without the page, their text read once for the check and the build, come in + /// as they do with the text read afresh for each. + #[test] + fn layers_alone_read_their_text_once_and_come_in_as_with_two_reads() { + let data = many_stories(12); + let read = || ai::read_over_page(&data, false, ai::NameEncoding::default()).unwrap(); + let pages = [(100.0, 100.0)]; + let Some(Ok(twice)) = alone_reading_twice(read(), &data, &pages) else { panic!("didn't open without the page") }; + let Ok(Ok(once)) = build_without_page(read(), &data, &pages, 1.0, &mut ReadText::default()) else { panic!("didn't open without the page") }; + assert_eq!(once, twice); + let mut texts = vec![]; + once.0.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + assert_eq!(texts.len(), 12, "{:?}", once.1); + assert!(texts.iter().enumerate().all(|(i, t)| *t == format!("Story {i}")), "{texts:?}"); + } + + /// The check and the build of layers that open without the page, 2,000 objects of point type in + /// them, timed with the text read afresh for each and read once for both, alternating, seven runs + /// of each: `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture text_read_once_timing`. + #[test] + #[ignore = "a timing, run by hand"] + fn text_read_once_timing() { + let data = many_stories(2000); + let read = || ai::read_over_page(&data, false, ai::NameEncoding::default()).unwrap(); + let pages = [(100.0, 100.0)]; + let (mut twice, mut once) = (vec![], vec![]); + for _ in 0..7 { + let structure = read(); + let start = std::time::Instant::now(); + let Some(Ok(a)) = alone_reading_twice(structure, &data, &pages) else { panic!("didn't open without the page") }; + twice.push(start.elapsed()); + let structure = read(); + let start = std::time::Instant::now(); + let Ok(Ok(b)) = build_without_page(structure, &data, &pages, 1.0, &mut ReadText::default()) else { + panic!("didn't open without the page") + }; + once.push(start.elapsed()); + assert_eq!(a, b); + } + println!("read twice: {twice:?}\nread once: {once:?}"); + twice.sort(); + once.sort(); + println!("median: read twice {:?}, read once {:?}", twice[3], once[3]); + } } diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 5154718a2f..d46da2b8ff 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,5 +1,5 @@ use super::build::{ - PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_weighing, build_without_page, reid_page_art, scale_symbol_art, + PAGE_MOVE, Page, ReadText, alone_scale, build, build_from, build_on_page, build_weighing, build_without_page, reid_page_art, scale_symbol_art, }; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -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 } = layers; + let AiLayers { data, structure, alone, mut text } = layers; let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), @@ -194,7 +194,7 @@ pub fn layered_ai_from( 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| { count = structure.warped_type.envelope_count(); - build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free) + build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); // Layers that waited on the page only for their envelopes of type open alone, as they would // have without them, unless one opened live with the layers drawing as the page. Alone, each @@ -210,7 +210,7 @@ pub fn layered_ai_from( if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) { structure.warped_type.open_alone(free, count); } - build_without_page(structure, &data, &pages, unit).ok()?.ok() + build_without_page(structure, &data, &pages, unit, &mut text).ok()?.ok() }) { done.setup.bleed = visible.setup.bleed; @@ -248,27 +248,28 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> 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 }), + Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }), }; if !has_layers(&data) { - return Err(AiLayers { data: Ok(data), structure: None, alone: None }); + return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() }); } // 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) { Ok(structure) => structure, - Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None }), + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }), }; + 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).is_some() { + 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 }); + return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text }); } - match build_without_page(structure, &data, pages, unit) { + 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 }), - Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None }), + 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 }), } } @@ -283,12 +284,14 @@ pub struct AiLayers { /// The pages and their unit the layers open on without the PDF part, when they wait on it only /// for their envelopes of type ([`ai_layers_alone`]). 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, } 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 } + Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default() } } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 5a12d24dc2..dbac845dad 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -44,12 +44,12 @@ fn native_large_canvas(size: f64, scale: f64, layers: &str) -> String { } /// A layer as the format writes it. -fn layer(name: &str, visible: bool, body: &str) -> String { +pub(super) fn layer(name: &str, visible: bool, body: &str) -> String { format!("%AI5_BeginLayer\n{} 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n", u8::from(visible)) } /// A yellow square of 4 points at (`x`, `y`) in the format's operators. -fn square(x: u32, y: u32) -> String { +pub(super) fn square(x: u32, y: u32) -> String { format!("0 0 1 0 k\n{x} {y} m\n{} {y} L\n{} {} L\n{x} {} L\nf", x + 4, x + 4, y + 4, y + 4) } @@ -3243,9 +3243,9 @@ fn custom_colours_open_paths_and_planar_group_marks_are_read() { /// A text document of `stories` (each as the text, its alignment code, its anchor and the frame's /// translation, and the start of its first line from the anchor), one font and a 14 point default. /// A story: its text, alignment code, anchor, frame translation and first line's start. -type Story<'a> = (&'a str, u8, (f64, f64), (f64, f64), f64); +pub(super) type Story<'a> = (&'a str, u8, (f64, f64), (f64, f64), f64); -fn text_document(stories: &[Story<'_>]) -> String { +pub(super) fn text_document(stories: &[Story<'_>]) -> String { let story = |(text, align, anchor, _t, start): &Story<'_>| { let n = text.chars().count(); format!( @@ -3290,7 +3290,7 @@ fn named_text_document(stories: &[Story<'_>]) -> String { /// The editing copy of a 100 × 100 file with `layers` and the text `document`; its template box is /// centred at (50, 50). -fn native_with_text(layers: &str, document: &str) -> String { +pub(super) fn native_with_text(layers: &str, document: &str) -> String { let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); format!( "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\ @@ -3299,8 +3299,18 @@ fn native_with_text(layers: &str, document: &str) -> String { ) } +/// [`text_document`] of `stories`, padded so that [`native_with_text`] doesn't split the end of its +/// data, `~>`, across two lines. +pub(super) fn unsplit_text_document(stories: &[Story<'_>]) -> String { + let mut doc = text_document(stories); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + doc +} + /// A text object of story `story`, as the layers hold it. -fn text_object(story: u32) -> String { +pub(super) fn text_object(story: u32) -> String { format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n2 /TextAntialiasing ,\n;\n") } @@ -6058,6 +6068,94 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { assert_eq!(loose, [("Note".to_string(), true)], "{notes:?}"); } +/// What `f` returns, with how many times it read a text document and scanned the text objects' +/// frames of an editing copy on this thread; with `afresh`, each check and build reads them anew, +/// keeping nothing for the next. +fn text_reads(afresh: bool, f: impl FnOnce() -> T) -> (T, u64, u64) { + crate::import::ate::TEXTS_READS.set(0); + crate::import::ai::TEXT_FRAME_SCANS.set(0); + crate::import::native::READ_AFRESH.set(afresh); + let out = f(); + crate::import::native::READ_AFRESH.set(false); + (out, crate::import::ate::TEXTS_READS.get(), crate::import::ai::TEXT_FRAME_SCANS.get()) +} + +/// A `.ai` that opens without its PDF part reads its text document and scans its text objects' +/// frames once, for the check that its text document makes all of its type and for the build, and +/// comes in as it does when each reads them anew. +#[test] +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 (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:?}"); + assert_eq!(text_of(&d.layers[0]).iter().map(|t| t.plain_text()).collect::>(), ["Hi there", "Mid"], "{notes:?}"); + let (afresh, texts, frames) = text_reads(true, open); + assert_eq!((texts, frames), (2, 2)); + assert_eq!(afresh, Some((d, notes))); +} + +/// Layers whose text document can't be read wait on the PDF part, which then doesn't read the text +/// document or scan the frames again, and come in as they do when each check and build reads them +/// anew. +#[test] +fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() { + let art = layer("Art", true, &format!("{}\n{}", square(10, 10), text_object(0))); + 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") }; + 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); + assert_eq!((texts, frames), (1, 1), "{:?}", opened.1); + let (afresh, texts, frames) = text_reads(true, open); + assert_eq!((texts, frames), (2, 2), "{:?}", afresh.1); + assert_eq!(opened, afresh); +} + +/// An envelope of type that waits on the PDF part reads the text document and scans the frames +/// once, for the check before the PDF part is imported, the build with it, and the build without it +/// that follows when the envelope doesn't open live, and the file comes in as it does when each of +/// them reads them anew. +#[test] +fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() { + let Some(family) = installed_family() else { return }; + let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)]; + let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})")); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0)); + 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 open = |page: Document| { + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) 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. + let (opened, texts, frames) = text_reads(false, || open(pdf_part(80.0, 80.0))); + assert_eq!((texts, frames), (1, 1), "{:?}", opened.1); + let (afresh, texts, frames) = text_reads(true, || open(pdf_part(80.0, 80.0))); + assert_eq!((texts, frames), (4, 4), "{:?}", afresh.1); + assert_eq!(opened, afresh); + let (envelopes, _) = envelopes_and_type(&opened.0); + assert!(opened.2 && envelopes.is_empty(), "{envelopes:?} {:?}", opened.1); + // A PDF part that draws as those layers, with the drawn art: the envelope opens live. + let page = opened.0; + let (opened, texts, frames) = text_reads(false, || open(page.clone())); + assert_eq!((texts, frames), (1, 1), "{:?}", opened.1); + let (afresh, texts, frames) = text_reads(true, || open(page)); + assert_eq!((texts, frames), (2, 2), "{:?}", afresh.1); + assert_eq!(opened, afresh); + let (envelopes, _) = envelopes_and_type(&opened.0); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", opened.1); +} + /// The hidden type outside envelopes in the layers of `d`: each text object's name. fn loose_type_names(d: &Document) -> Vec> { let mut out = vec![]; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f506da06e1..e7c82cbd78 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1903,6 +1903,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). A `.ai` or EPS opened from its editing data whose text document makes the type of every text object that shows takes all its type from the text document: each text object stays in its own group, frame and layer, the page's type isn't matched with them, a file of more than 5,000 text objects still opens with its layers, and type the page draws differently (in another font) keeps the layers, with a warning. A line break inside a paragraph stays a line break in it (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ate.rs`). + A `.ai` opened without its PDF part decodes and parses its text document and scans its text objects' frames once, for both the check that the text document makes all of its type and the build. When the file waits on its PDF part instead (an envelope of type, or a text document that can't be read), the builds with and without the PDF part use that same read. The document and notes are the same as before. Checking and building a file of 2,000 point type objects takes a median of 164 ms instead of 270 ms over seven runs each, with the two routes alternating, on Linux (`crates/eps/src/import/native/build.rs`). `.ai` and EPS editing-data import reads a text document whose keys are written by name, as files saved for version 11 write them, and the keys that later files write by name among the numbered ones (a font record's version, a paragraph's direction). The type of such a file comes from its text document, so type outside the artboards opens and each text object keeps its own story A run that names its paragraph or character style by the style's number takes that style (`a_text_document_with_named_keys_gives_type_off_the_page_too`, `a_text_document_with_named_keys_takes_a_runs_style_by_its_number`, `crates/eps/src/import/ate/names.rs`). In SVG export without Fewer `` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned ``, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`).