diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 17177671cf..88daf4d7a1 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -118,7 +118,12 @@ //! `%AI24_EndSymbolList`); each instance as `/SymbolInstance :`, `(name) /SymbolRef ,`, the //! matrix taking the art to art space as `a b c d tx ty /RTransformMatrix`, `;`, then its name //! and opacity mask and a state block as a group's with its opacity and blending mode (an -//! instance with isolation, knockout or knockout shape of its own is written as its art). The +//! instance with isolation, knockout or knockout shape of its own is written as its art). A +//! dynamic symbol's art dictionary also holds `VectorCraftDynamicSymbol` (`/Int`, 1), and the +//! dictionary of an instance with changes of its own (`symbol_overrides`) holds +//! `VectorCraftSymbolOverrides`, a `/String` of the changes as hex-coded JSON: the format's own +//! entries, as other apps' editing data is not documented, read back by this reader and left out by +//! others. The //! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and //! a gradient's take the art to the canvas's space turned y up about art space's origin there, //! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are @@ -191,7 +196,7 @@ //! and instances of //! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects //! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice -//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as +//! guides, export types left out, gradient meshes the reader wouldn't read back as //! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh //! on a large canvas as their drawn look, blends the reader wouldn't read back live as //! their steps, other live objects (placed documents included) as their art, @@ -220,6 +225,7 @@ use vectorcraft_pdf::PrivateData; use crate::ps; mod writer; +pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; use writer::Writer; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 22d3203e3b..602b86910b 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -6394,7 +6394,8 @@ fn instances_the_data_cant_hold_are_written_as_their_art() { let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, changed).unwrap(); doc.insert(Some(layer), usize::MAX, plain).unwrap(); - assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART, writer::SYMBOL_OPTIONS]); + doc.symbols[0].dynamic = false; + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); let back = read_back(&doc); assert_eq!(kinds(&back), ["art", "instance"]); let green = back.layers[0].children().unwrap()[0].clone(); @@ -6890,7 +6891,7 @@ fn symbol_options_and_linked_images_in_symbols_are_reported() { let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, one).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); - assert_eq!(out.warnings, [writer::SYMBOL_OPTIONS, writer::LINKS_EMBEDDED]); + assert_eq!(out.warnings, [writer::LINKS_EMBEDDED]); let p = program_shown(&doc); assert!(p.contains("%AI5_BeginRaster") && !p.contains("%AI5_BeginPlace"), "{p}"); let back = read_back(&doc); @@ -15982,3 +15983,56 @@ fn a_mesh_eight_levels_down_is_written_as_a_mesh() { assert_eq!(back.len(), 1, "{back:#?}"); assert_mesh_exact(mesh_of(&back[0]), &want, "eight levels down"); } + +fn dynamic_doc() -> Document { + let mut doc = Document::new(200.0, 100.0); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: true, name: "Leaf".into(), art: Arc::new(art) }); + let layer = doc.layers[0].id; + for (x, c) in [(10.0, Color::rgb(1.0, 0.0, 0.0)), (50.0, Color::rgb(0.0, 0.0, 1.0))] { + let mut i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0))); + i.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { fill: Some(solid(c)), opacity: Some(0.5), ..Default::default() }]; + doc.insert(Some(layer), usize::MAX, i).unwrap(); + } + let plain = instance(&mut doc, "Leaf", Affine::translate((90.0, 10.0))); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + doc +} + +#[test] +fn dynamic_symbols_and_their_instance_changes_survive_a_round_trip() { + let doc = dynamic_doc(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + assert!(back.symbols[0].dynamic); + let kids = back.layers[0].children().unwrap(); + assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))); + let want: Vec<_> = doc.layers[0].children().unwrap().iter().map(|n| n.extras().symbol_overrides.clone()).collect(); + let got: Vec<_> = kids.iter().map(|n| n.extras().symbol_overrides.clone()).collect(); + assert_eq!(got, want); + assert_ne!(got[0], got[1]); + assert!(got[2].is_empty()); +} + +#[test] +fn static_symbols_write_no_dynamic_entries() { + let mut doc = dynamic_doc(); + doc.symbols[0].dynamic = false; + let layer = doc.layers[0].id; + for n in doc.layers[0].children().unwrap().to_vec() { + doc.remove(n.id).unwrap(); + } + for x in [10.0, 50.0] { + let i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0))); + doc.insert(Some(layer), usize::MAX, i).unwrap(); + } + let p = program(&doc); + assert!(!p.contains("VectorCraftDynamicSymbol") && !p.contains("VectorCraftSymbolOverrides")); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty()); + let back = read_back(&doc); + assert!(!back.symbols[0].dynamic); + let kids = back.layers[0].children().unwrap(); + assert_eq!(kids.len(), 2); + assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }) && n.extras().symbol_overrides.is_empty())); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 41254840cb..6c1f4a398f 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -48,8 +48,9 @@ pub(super) use paints::{ GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, }; +pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; #[cfg(test)] -pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; +pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] @@ -286,6 +287,7 @@ pub(super) struct Writer<'a> { symbol_scales: HashMap, /// The entries a symbol's dictionary adds to its art's dictionary, and the art's id. root_entries: Option<(vectorcraft_doc::NodeId, String)>, + instance_entries: Option<(vectorcraft_doc::NodeId, String)>, /// The objects that may be written with an art style, as they were before baking, by id /// ([`styles::styled_objects`]). pub(super) styled: HashMap>, @@ -405,6 +407,7 @@ impl<'a> Writer<'a> { inner_scale: 1.0, symbol_scales: HashMap::new(), root_entries: None, + instance_entries: None, styled: HashMap::new(), symbol_styled: HashMap::new(), pattern_styled: HashMap::new(), @@ -818,7 +821,7 @@ impl<'a> Writer<'a> { mask_window = self.windowed.take(); } } - NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy), + NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(n, symbol, *xf, xy), NodeKind::SymbolInstance { symbol, xf } => { if !self.open_group("u") { return; @@ -1016,6 +1019,10 @@ impl<'a> Writer<'a> { Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e), _ => None, }; + let entries = match &self.instance_entries { + Some((id, _)) if *id == n.id => entries.or_else(|| self.instance_entries.take().map(|(_, e)| e)), + _ => entries, + }; let role = match &self.blend_role { Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e), _ => None, diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index 4d4bb2acba..a616d748d1 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -14,7 +14,27 @@ use crate::ps; pub(in crate::ai_editing) const SYMBOL_ART: &str = "symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects, instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times, instances on the layers of a large canvas and instances of symbols past 4,096 are written as their art in the editing data for other apps"; pub(in crate::ai_editing) const SYMBOL_OPTIONS: &str = - "the 9-slice guides, export types and dynamic type of symbols are left out of the editing data for other apps"; + "the 9-slice guides and export types of symbols are left out of the editing data for other apps"; +pub(in crate::ai_editing) const SYMBOL_CHANGES: &str = + "the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out"; +pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol"; +pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides"; +const MAX_OVERRIDES_BYTES: usize = 1 << 20; + +pub(crate) fn hex_decode(s: &str) -> Option> { + if !s.len().is_multiple_of(2) || s.len() / 2 > MAX_OVERRIDES_BYTES { + return None; + } + s.as_bytes().chunks(2).map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok()).collect() +} + +fn hex_encode(b: &[u8]) -> String { + b.iter().fold(String::with_capacity(b.len() * 2), |mut s, v| { + let _ = write!(s, "{v:02x}"); + s + }) +} + pub(in crate::ai_editing) const MISSING_SYMBOL: &str = "symbol instances of symbols the document doesn't have are written as empty groups in the editing data for other apps"; /// The most an instance may scale its symbol's art, nested instances' scales included: the art's @@ -55,7 +75,8 @@ impl Writer<'_> { /// that keeps the art's area as it is written and scales it as the definition allows /// ([`Self::keeps_scale`]). pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool { - let own = vectorcraft_brush::stain(n).is_some() || !n.extras().symbol_overrides.is_empty(); + let dynamic = self.symbol_doc.symbols.iter().any(|s| s.name == symbol && s.dynamic); + let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !n.extras().symbol_overrides.is_empty()); let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape; // The matrix as written (to ten decimals) must still keep the art's area. let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10)); @@ -153,7 +174,16 @@ impl Writer<'_> { /// canvas's space turned y up about art space's origin there) as `a b c d tx ty /// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd` /// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two. - pub(super) fn symbol_instance(&mut self, symbol: &str, xf: Affine, xy: Xy) { + pub(super) fn symbol_instance(&mut self, n: &Node, symbol: &str, xf: Affine, xy: Xy) { + let o = &n.extras().symbol_overrides; + if !o.is_empty() + && let Ok(json) = serde_json::to_vec(o) + && json.len() <= MAX_OVERRIDES_BYTES + { + let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes())); + self.instance_entries = Some((n.id, e)); + self.warn(SYMBOL_CHANGES); + } let m = self.instance_space * xf; let _ = write!(self.body, "/SymbolInstance :\n{} /SymbolRef ,\n", ps::bytes(symbol.as_bytes())); for v in m.as_coeffs() { @@ -201,7 +231,7 @@ impl Writer<'_> { self.warn(SYMBOL_COUNT); return false; } - if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() { + if doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() { self.warn(SYMBOL_OPTIONS); } // The art's effects are its own, not those of a drawn look that first places it, and its @@ -260,7 +290,10 @@ impl Writer<'_> { (self.to_art, self.grad_space, self.canvas, self.instance_space) = (Affine::IDENTITY, about_origin, Affine::IDENTITY, about_origin); self.block_end = usize::MAX; let registration = u16::from(doc.symbol_registration(name).0.min(8)) + 1; - let entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n"); + let mut entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n"); + if sym.dynamic { + let _ = writeln!(entries, "%_1 /Int ({DYNAMIC_KEY}) ,"); + } // The canvas draws a symbol's art even when its root is hidden, so the root is written shown. let shown; let root: &Node = if sym.art.visible { diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 67b3e799e2..418ac283a8 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -620,7 +620,7 @@ impl<'a> Reader<'a> { || sub.mesh.is_some() || sub.gradient_def.is_some(); let head = sub.symbol.take().unwrap_or_default(); - let registration = head.registration; + let (registration, dynamic) = (head.registration, head.dynamic); let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; let Some(frame) = sub.frames.pop().filter(|_| measured) else { return }; let mut kids = frame.children; @@ -662,7 +662,7 @@ impl<'a> Reader<'a> { } } let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name }); - self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false }); + self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic }); if let Some(reg) = registration.and_then(symbol_registration) { self.doc.set_symbol_registration(&named, reg); } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 2eee5a0a15..a2e546eb97 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -781,6 +781,19 @@ impl<'a> Reader<'a> { { head.registration = Some(*r); } + if self.frames.len() == 1 + && let Some(head) = self.symbol.as_mut() + && o.nums(crate::ai_editing::DYNAMIC_KEY).first().is_some_and(|v| *v != 0.0) + { + head.dynamic = true; + } + if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY) + && let Some(bytes) = crate::ai_editing::hex_decode(&text) + && let Ok(list) = serde_json::from_slice::>(&bytes) + && let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) + { + n.extras_mut().symbol_overrides = list.into_iter().filter(|s| !s.is_empty()).collect(); + } self.constraint_art(o); self.placed_page(o); // A blend's key object or spine. diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 02d4a3354a..a155d9f505 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -244,6 +244,7 @@ pub(super) struct PatternHead { pub(super) struct SymbolHead { /// `AI13PatternRegistrationType` in the dictionary after the art. pub(super) registration: Option, + pub(super) dynamic: bool, /// Art the reader left out (type, a placed file, non-native art, an image it can't read or /// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the /// page draws them, within the box of the rest.