diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 4a261f2582..3ddc8636c8 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -7150,6 +7150,166 @@ fn art_styles_are_written_in_their_forms() { assert!(!two.contains("%AI9_BeginArtStyleList"), "{two}"); } +/// A document with `k` of each object a save checks a style on, on rows 20 pt apart: objects linked +/// to a new document's graphic style and to one of the document's own, objects with the same drop +/// shadow, two objects with different gradients under a drop shadow on the same outline, and paths +/// with a Calligraphic brush and a drop shadow. +fn checked_styles_document(k: usize) -> Document { + let mut doc = Document::new(400.0, 20.0 * k as f64 + 20.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + let lit_ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(solid(Color::rgb(0.2, 0.5, 0.9)), solid(Color::BLACK), 1.0) }; + let mut lit = vectorcraft_doc::GraphicStyle::new("Lit", lit_ap); + lit.id = 40; + doc.graphic_styles.push(lit); + let ramp = |c: Color| { + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, c)]; + Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Linear, stops, ..Gradient::default() }))) + }; + for i in 0..k { + let y = 10.0 + 20.0 * i as f64; + for (x, name) in [(10.0, "Sunshine"), (60.0, "Lit")] { + let g = doc.graphic_style(name).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 15.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + let n = styled_rect(&mut doc, "Shadowed", Rect::new(110.0, y, 150.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + for c in [Color::BLACK, Color::rgb(0.9, 0.2, 0.1)] { + let n = styled_rect(&mut doc, "Graded", Rect::new(160.0, y, 200.0, y + 15.0), ramp(c), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + } + let stroke = Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 2.0); + let mut line = Node::path(doc.alloc_id(), shapes::line((210.0, y).into(), (380.0, y + 10.0).into()), stroke); + line.appearance.stroke_mut().unwrap().brush = Some("Nib".into()); + line.appearance.effects = vec![drop_shadow()]; + put(&mut doc, line); + } + doc +} + +/// A save parses each style text once, however many objects it checks with it: the panel's styles, +/// objects linked to them, objects with the same style of their own and brushed paths. Each object +/// is still checked: every linked object keeps its link, each graded object reads back with its own +/// gradient, and each brushed path with its brush. +#[test] +fn a_save_parses_each_style_text_once() { + let parses = |doc: &Document| { + crate::import::ART_STYLE_PARSES.set(0); + let out = export_ai_editing(doc, &opts()).unwrap(); + (crate::import::ART_STYLE_PARSES.get(), String::from_utf8(out.program).unwrap().replace("\r\n", "\n")) + }; + let (one, _) = parses(&checked_styles_document(1)); + let doc = checked_styles_document(4); + let (four, p) = parses(&doc); + assert!(one > 0); + assert_eq!(four, one, "parses with one of each object and with four"); + for linked in ["1 (Sunshine) XW\n", "1 (Lit) XW\n"] { + assert_eq!(p.matches(linked).count(), 4, "{linked}"); + } + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + let paints: Vec<&Paint> = + kids.iter().filter(|n| n.name.as_deref() == Some("Graded")).filter_map(|n| n.appearance.fill().map(|f| &f.paint)).collect(); + let graded: Vec<&Paint> = doc.layers[0] + .children() + .unwrap() + .iter() + .filter(|n| n.name.as_deref() == Some("Graded")) + .map(|n| &n.appearance.fill().unwrap().paint) + .collect(); + assert_eq!(paints.len(), 8); + for (got, want) in paints.iter().zip(&graded) { + let (Paint::Gradient(got), Paint::Gradient(want)) = (got, want) else { panic!("a gradient fill: {got:?}") }; + assert_eq!(got.gradient.stops, want.gradient.stops); + } + let brushed: Vec<&Arc> = kids.iter().filter(|n| n.appearance.stroke().and_then(|s| s.brush.as_deref()) == Some("Nib")).collect(); + assert_eq!(brushed.len(), 4); + assert!(brushed.iter().all(|n| n.appearance.effects.len() == 1 && matches!(n.kind, NodeKind::Path { .. }))); +} + +/// A save that keeps each style text's parse writes the same program, header, warnings and private +/// data as one that parses the text again at every check. +#[test] +fn a_save_writes_the_same_with_each_style_text_parsed_once() { + let save = |doc: &Document, reparse: bool| { + writer::REPARSE.set(reparse); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::REPARSE.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + for doc in [styles_document(), checked_styles_document(4), brushes_document()] { + let (once, again) = (save(&doc, false), save(&doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } +} + +/// The CPU time of saving a document with 40 graphic styles, 20,000 rectangles linked to them in +/// turn and 5,000 paths with an Outer Glow of their own in 20 settings, with each style text's parse +/// kept and with the text parsed again at every check: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture style_parse_time`. +#[test] +#[ignore = "timing; run by hand"] +fn style_parse_time() { + let mut doc = Document::new(2000.0, 2000.0); + let mut ids = vec![]; + for i in 0..40u32 { + let shade = i as f32 / 40.0; + let mut ap = Appearance::basic(solid(Color::rgb(shade, 0.4, 1.0 - shade)), solid(Color::BLACK), 1.0 + f64::from(i % 4)); + let round = fx("stylize.roundCorners", serde_json::json!({"radius": 2.0 + f64::from(i % 5)})); + ap.effects = vec![fx("stylize.dropShadow", serde_json::json!({"x": f64::from(i % 7), "y": 4.0})), round]; + let mut g = vectorcraft_doc::GraphicStyle::new(format!("Style {i}"), ap); + g.id = 100 + i; + ids.push(g.id); + doc.graphic_styles.push(g); + } + for i in 0..20_000usize { + let g = doc.graphic_style_by_id(ids[i % ids.len()]).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + for i in 0..5_000usize { + let glow = fx("stylize.outerGlow", serde_json::json!({"blur": 1.0 + (i % 20) as f64})); + let (x, y) = ((i % 100) as f64 * 20.0, 1000.0 + (i / 100) as f64 * 20.0); + let n = styled_rect(&mut doc, "Glow", Rect::new(x, y, x + 15.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![glow]); + put(&mut doc, n); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + let mut times: [Vec; 2] = [vec![], vec![]]; + let mut parses = [0, 0]; + let mut outputs: [Vec; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, reparse) in [(0, true), (1, false)] { + writer::REPARSE.set(reparse); + crate::import::ART_STYLE_PARSES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + parses[k] = crate::import::ART_STYLE_PARSES.get(); + outputs[k] = out.program; + } + } + writer::REPARSE.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "parsed at every check"), (1, "parsed once")] { + times[k].sort_unstable(); + let ms: Vec = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} parses, runs {}", times[k][3] as f64 / 1e6, parses[k], ms.join(" ")); + } +} + /// Objects whose appearance the reader wouldn't read with their style are written as their /// drawn look, with the warnings they were written with before; graphic styles it wouldn't read /// are left out with a warning; and a document without effects or styles of its own has no art diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index f268bcbaf6..39c3157350 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -37,7 +37,7 @@ pub(super) use envelopes::ENVELOPES; pub(super) use meshes::MESHES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] -pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; +pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, REPARSE, STYLE_LINKS, WARPED_IMAGES, same_appearance}; pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index 986d60ef9c..239668a09a 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -565,14 +565,14 @@ impl Writer<'_> { /// Does the reader read the brushed strokes of style text `text` with their brushes on them? pub(super) fn brushed_style_reads(&mut self, text: &str) -> bool { self.brush_set(); - let section = super::styles::known_style("x", text); + let Some(parsed) = self.styles.parsed.get(text) else { return false }; let written = &self.brush_set.written; let read = self.brush_set.read.get_or_insert_with(|| { let brushes: Vec<(&str, &str, &str, Option<&Node>)> = written.iter().map(|b| (b.plugin, b.brush.name.as_str(), b.params.as_str(), b.art.as_ref())).collect(); crate::import::BrushesRead::new(&brushes) }); - read.style_reads(section.as_bytes(), "x") + read.style_reads(parsed) } /// The brushes' art in a non-printing block, then the brush manager's order and the brushes in diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 50aa4df931..0af8e313fa 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -2,9 +2,9 @@ //! object itself on `%_` lines and `1 (style) XW`; the styles they name and the Graphic Styles //! panel's styles in `%AI9_BeginArtStyles`, and the panel's order in `%AI9_BeginArtStyleList` (see //! [`crate::ai_editing`] for the form). Each style is read back before it is written -//! ([`crate::import::read_art_style`]: the `.ai` reader's style parser and its reading of a graphic +//! ([`crate::import::read_parsed_style`]: the `.ai` reader's style parser and its reading of a graphic //! style, with the object's own gradient): one that reads back differently is not written, and the -//! object is written as its drawn look alone. +//! object is written as its drawn look alone. Each style text is parsed once per save ([`Parsed`]). use std::collections::{HashMap, HashSet}; use std::fmt::Write; @@ -126,7 +126,7 @@ fn candidate(n: &Node) -> bool { /// Is `n` an image, embedded or linked, without an opacity mask whose appearance is one Warp, with /// no fills or strokes that paint and no effects on them: an image the reader reads with its Warp -/// live ([`crate::import::read_art_style`]'s `image_warp`)? +/// live ([`crate::import::read_parsed_style`]'s `image_warp`)? fn warped_image(n: &Node) -> bool { matches!(n.kind, NodeKind::Image(_)) && n.extras().mask.is_none() @@ -162,8 +162,8 @@ fn plain_member(n: &Node) -> bool { pub(in crate::ai_editing) struct Styles { /// Every style, in the order written: its name and text. known: Vec<(String, String)>, - /// The panel's styles written, by the graphic style's id. - panel: HashMap, + /// The panel's styles written, by the graphic style's id: each one's place in [`Self::known`]. + panel: HashMap, /// The panel's styles written, in its order. listed: Vec, /// The names styles have, and the name of each object style by its text. @@ -172,6 +172,35 @@ pub(in crate::ai_editing) struct Styles { next_anon: u64, /// How many objects were written with the graphic style they are linked to. pub(super) links_written: usize, + /// Every style text checked so far, as the reader parses it. + pub(super) parsed: Parsed, +} + +/// Style texts as the reader parses them ([`crate::import::parse_art_style`]), each parsed once +/// however many styles and objects are checked with it; a text the reader doesn't parse is kept +/// as `None`. +#[derive(Default)] +pub(super) struct Parsed(HashMap>); + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`Parsed`] keeps nothing: every check parses its style text again. + pub(in crate::ai_editing) static REPARSE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +impl Parsed { + /// Style text `text` as the reader parses it (`None` when it doesn't). + pub(super) fn get(&mut self, text: &str) -> Option<&crate::import::ParsedStyle> { + #[cfg(test)] + if REPARSE.get() { + self.0.remove(text); + } + if !self.0.contains_key(text) { + let parsed = crate::import::parse_art_style(known_style("x", text).as_bytes(), "x"); + self.0.insert(text.to_owned(), parsed); + } + self.0.get(text).and_then(Option::as_ref) + } } impl Styles { @@ -652,7 +681,7 @@ impl Writer<'_> { continue; } let xy = Xy { blend: g.blend, opacity: g.opacity.clamp(0.0, 1.0), isolate: g.isolate, knockout: g.knockout, shape: false }; - let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t)); + let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t, &mut self.styles.parsed)); let Some(text) = text else { self.warn(PANEL_STYLES); continue; @@ -669,7 +698,7 @@ impl Writer<'_> { continue; } if g.id != 0 { - self.styles.panel.insert(g.id, g.name.clone()); + self.styles.panel.insert(g.id, self.styles.known.len()); } self.styles.listed.push(g.name.clone()); self.styles.known.push((g.name.clone(), text)); @@ -701,14 +730,13 @@ impl Writer<'_> { } let doc = self.doc; if let Some(id) = orig.extras().graphic_style - && let Some(name) = self.styles.panel.get(&id).cloned() + && let Some((name, text)) = self.styles.panel.get(&id).and_then(|i| self.styles.known.get(*i)) && let Some(g) = doc.graphic_style_by_id(id) && g.transparency_matches(orig) && g.appearance_on(orig).approx_eq(&orig.appearance) - && let Some(text) = self.styles.known.iter().find(|(n, _)| *n == name).map(|(_, t)| t.clone()) - && object_reads(orig, &text) + && object_reads(orig, text, &mut self.styles.parsed) { - return Some(name); + return Some(name.clone()); } let brushed = brushed(orig); if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) { @@ -720,7 +748,7 @@ impl Writer<'_> { let rule = object_rule(orig); let text = self .style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))) - .filter(|t| object_reads(orig, t) && (!brushed || self.brushed_style_reads(t))); + .filter(|t| object_reads(orig, t, &mut self.styles.parsed) && (!brushed || self.brushed_style_reads(t))); let Some(text) = text else { if let Some(mark) = saved.0 { self.gradient_rollback(mark); @@ -784,7 +812,12 @@ impl Writer<'_> { if !self.take_objects(1 + own) { return; } - let linked = orig.extras().graphic_style.and_then(|id| self.styles.panel.get(&id)).is_some_and(|p| p == name); + let linked = orig + .extras() + .graphic_style + .and_then(|id| self.styles.panel.get(&id)) + .and_then(|i| self.styles.known.get(*i)) + .is_some_and(|(p, _)| p == name); if linked { self.styles.links_written += 1; } else if brushed(orig) { @@ -937,13 +970,12 @@ fn own_style_holds(ap: &Appearance) -> bool { } /// Does the reader read graphic style `g` from style text `text` as it is? It leaves out a graphic -/// style with a brush on a stroke that paints. -fn panel_reads(g: &GraphicStyle, text: &str) -> bool { +/// style with a brush on a stroke that paints. `parsed` holds the texts already parsed. +fn panel_reads(g: &GraphicStyle, text: &str, parsed: &mut Parsed) -> bool { if g.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && !s.paint.is_none())) { return false; } - let section = known_style("x", text); - let Some(read) = crate::import::read_art_style(section.as_bytes(), "x", None) else { return false }; + let Some(read) = parsed.get(text).and_then(|st| crate::import::read_parsed_style(st, None)) else { return false }; // The opacity within the written number's precision. read.transparency.is_some_and(|t| (t.0 - g.opacity).abs() <= 1e-4 && (t.1, t.2, t.3) == (g.blend, g.isolate, g.knockout)) && same_appearance(&read.appearance, &g.appearance) @@ -952,19 +984,20 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool { /// Does the reader read object `n` written with style text `text` as it is: a path or compound /// path with a style it reads on any object, filled by the non-zero rule when the style fills it, /// or a group with no fills or strokes of its own, with effects that move the outline only where the -/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a +/// reader reads them ([`crate::import::parsed_moves_with`]), or an image ([`warped_image`]) with a /// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look. -fn object_reads(n: &Node, text: &str) -> bool { - let section = known_style("x", text); +/// `parsed` holds the texts already parsed. +fn object_reads(n: &Node, text: &str, parsed: &mut Parsed) -> bool { + let Some(st) = parsed.get(text) else { return false }; let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); - let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; + let Some(mut read) = crate::import::read_parsed_style(st, own) else { return false }; let group = matches!(n.kind, NodeKind::Group { .. }); let image = matches!(n.kind, NodeKind::Image(_)); if (image && !(read.image_warp && warped_image(n))) || (!image && !read.simple) || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) - || !crate::import::style_moves_with(section.as_bytes(), "x", n) + || !crate::import::parsed_moves_with(st, n) { return false; } diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 0d451ec9da..ba38492f77 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -89,14 +89,14 @@ use obj::PsError; pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; +#[cfg(test)] +pub(crate) use ai::{ART_STYLE_PARSES, ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ai::{ BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, - MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads, - brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list, - style_moves_with, symbol_art_member, turn_brush_art_over, warp_number, + MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle, + blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with, + read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, }; -#[cfg(test)] -pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 78990f9db7..5b170b239e 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -57,13 +57,15 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, - slot_of, style_moves_with, symbol_art_member, + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page, + read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, read_beside, read_in, symbols, variables, }; +#[cfg(test)] +pub(crate) use style::ART_STYLE_PARSES; pub(crate) use read::is_look_slot; pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index ef45364de5..afef3af634 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -799,14 +799,16 @@ impl BrushesRead { Self { drafts, by_name, bending } } - /// Does the reader read every stroke of art style `style` in `section` (the text between - /// `%AI9_BeginArtStyles` and its end) that names a brush with that brush on it, at the brush's - /// own settings? A style the reader doesn't read, or that names a brush no object gives, or an - /// Art brush in a style with effects, isn't read so. - pub(crate) fn style_reads(&self, section: &[u8], style: &str) -> bool { + /// Does the reader read every stroke of art style `parsed` ([`crate::import::parse_art_style`]) + /// that names a brush with that brush on it, at the brush's own settings? A style the reader + /// doesn't read, or that names a brush no object gives, or an Art brush in a style with effects, + /// isn't read so. + pub(crate) fn style_reads(&self, parsed: &crate::import::ParsedStyle) -> bool { use super::style::StyleItem; - let styles = super::style::art_styles(section); - let Some(st) = styles.get(style).filter(|st| st.plain) else { return false }; + let st = &parsed.style; + if !st.plain { + return false; + } st.items.iter().all(|item| match item { StyleItem::Stroke { brush: Some((name, settings)), .. } => { let Some(draft) = self.by_name.get(name).and_then(|i| self.drafts.get(*i)) else { return false }; diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 27a10033db..cc43157bcb 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,7 +155,7 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; -pub(crate) use ops::{read_art_style, read_style_list, style_moves_with}; +pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 39499b064d..5283762a51 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1453,16 +1453,30 @@ pub(crate) fn read_style_list(section: &[u8]) -> Vec { crate::import::ai::style::art_style_list(section).iter().map(|raw| obj::text(raw)).filter(|name| !name.is_empty()).collect() } -/// Art style `name` of `section` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], -/// with a style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads -/// it on objects other than type. A stroke that names a brush is read with that brush's name, as -/// [`styled`] reads it on a path or compound path when the Brushes panel keeps that brush at those -/// settings, which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the section -/// doesn't define it, the reader doesn't read it, or it paints with a pattern or a gradient that -/// isn't the object's own. -pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&Paint>) -> Option { +/// An art style as the reader parses it ([`parse_art_style`]), which a writer reads on any number of +/// objects ([`read_parsed_style`], [`parsed_moves_with`], +/// [`crate::import::ai::brush::BrushesRead::style_reads`]). +#[derive(Clone, Debug)] +pub(crate) struct ParsedStyle { + pub(in crate::import::ai) style: crate::import::ai::style::ArtStyle, +} + +/// Art style `name` of `section` (the text between `%AI9_BeginArtStyles` and its end) as the reader +/// parses it. `None` when the section doesn't define it. +pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option { + crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style }) +} + +/// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a +/// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on +/// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`] +/// reads it on a path or compound path when the Brushes panel keeps that brush at those settings, +/// which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the reader doesn't +/// read it, or it paints with a pattern or a gradient that isn't the object's own. `parsed` is left as +/// it is, for the next object. +pub(crate) fn read_parsed_style(parsed: &ParsedStyle, own_gradient: Option<&Paint>) -> Option { use crate::import::ai::style::StyleItem; - let mut st = crate::import::ai::style::art_styles(section).remove(name)?; + let mut st = parsed.style.clone(); if st.items.iter().filter(|i| matches!(i, StyleItem::Gradient { .. })).count() == 1 { let own = own_gradient?; for item in &mut st.items { @@ -1491,11 +1505,10 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency }) } -/// Is art style `name` of `section` read on `object` as far as an effect that moves the outline -/// goes: the style has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? -/// `false` when the section doesn't define it. -pub(crate) fn style_moves_with(section: &[u8], name: &str, object: &Node) -> bool { - crate::import::ai::style::art_styles(section).remove(name).is_some_and(|st| !st.moves_outline() || moves_with(object, &st)) +/// Is art style `parsed` read on `object` as far as an effect that moves the outline goes: the style +/// has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? +pub(crate) fn parsed_moves_with(parsed: &ParsedStyle, object: &Node) -> bool { + !parsed.style.moves_outline() || moves_with(object, &parsed.style) } /// A style's stroke as an appearance item (`None` for a fill). diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index e0068a52be..0d87028ec0 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -419,8 +419,16 @@ fn closes(data: &[u8]) -> bool { false } +#[cfg(test)] +thread_local! { + /// How many times [`art_styles`] has parsed a section on this thread. + pub(crate) static ART_STYLE_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// [`art_styles_in`], names read in the default encoding. pub(super) fn art_styles(data: &[u8]) -> HashMap { + #[cfg(test)] + ART_STYLE_PARSES.set(ART_STYLE_PARSES.get() + 1); art_styles_in(data, &mut Names::default()) } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index c4b006fe2a..2b48fd268b 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1445,7 +1445,8 @@ fn warp_numbers_are_the_dialogs_order() { /// and nothing for styles it doesn't read. #[test] fn a_style_is_read_as_a_writer_checks_it() { - let read = |data: &str, own: Option<&Paint>| crate::import::read_art_style(data.as_bytes(), "Odd", own); + let parse = |data: &str, name: &str| crate::import::parse_art_style(data.as_bytes(), name); + let read = |data: &str, own: Option<&Paint>| parse(data, "Odd").and_then(|st| crate::import::read_parsed_style(&st, own)); let style = |kids: &[String]| format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", kids)); let gradient = fill("Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB"); let stack = compound("Stack Style Filter", std::slice::from_ref(&gradient)); @@ -1456,11 +1457,18 @@ fn a_style_is_read_as_a_writer_checks_it() { assert_eq!(got.appearance.items[0].paint(), &own); assert_eq!(got.transparency.map(|t| (t.0, t.1)), Some((0.5, BlendMode::Multiply))); assert!(got.simple && !got.pathfinder); + // One parse read on two objects: each takes its own gradient, and the parse is left as it was. + let parsed = parse(&data, "Odd").unwrap(); + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let first = crate::import::read_parsed_style(&parsed, Some(&own)).unwrap(); + let second = crate::import::read_parsed_style(&parsed, Some(&black)).unwrap(); + assert_eq!((first.appearance.items[0].paint(), second.appearance.items[0].paint()), (&own, &black)); + assert_eq!(parsed.style, parse(&data, "Odd").unwrap().style); // A gradient that isn't the object's own, a pattern, another name, two gradients: nothing. assert!(read(&data, None).is_none()); let pattern = style(&[compound("Stack Style Filter", &[fill("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p")])]); assert!(read(&pattern, None).is_none()); - assert!(crate::import::read_art_style(data.as_bytes(), "Even", Some(&own)).is_none()); + assert!(parse(&data, "Even").is_none()); assert!(read(&style(&[compound("Stack Style Filter", &[gradient.clone(), gradient])]), Some(&own)).is_none()); // Damaged text: every cut of the style, and stray bytes, without a panic. for cut in 0..data.len() {