From 4d975416335e18db8ac3f3a28062961406c5b0ff Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 16:22:03 -0800 Subject: [PATCH 01/18] test: reproduce lost composite fonts in native placement --- .../engine/tests/native_composite_adoption.rs | 381 ++++++++++++++++++ 1 file changed, 381 insertions(+) create mode 100644 crates/engine/tests/native_composite_adoption.rs diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs new file mode 100644 index 0000000000..a0f1fa11f7 --- /dev/null +++ b/crates/engine/tests/native_composite_adoption.rs @@ -0,0 +1,381 @@ +//! Native placement must keep the composite fonts its editable art uses, without changing the destination's meanings. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::Path; +use std::sync::{Mutex, MutexGuard}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CompositeFont, Document, Node, NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_testkit::TempDir; +use vectorcraft_text::FontDb; + +struct FontContext { + fonts: Vec, + _lock: MutexGuard<'static, ()>, +} + +impl FontContext { + fn hold() -> Self { + static LOCK: Mutex<()> = Mutex::new(()); + let lock = LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let db = FontDb::global(); + assert!(db.face("Source Sans 3", "Regular").is_some(), "CONTROL: the bundled test face is available"); + Self { fonts: registered_fonts(), _lock: lock } + } +} + +impl Drop for FontContext { + fn drop(&mut self) { + let db = FontDb::global(); + for name in db.composite_font_names() { + if CompositeFont::named(&self.fonts, &name).is_none() { + db.remove_composite_font(&name); + } + } + for font in &self.fonts { + db.set_composite_font(font); + } + } +} + +fn registered_fonts() -> Vec { + let db = FontDb::global(); + db.composite_font_names().iter().map(|name| (*db.composite_font(name).unwrap()).clone()).collect() +} + +fn document(session: &Session) -> &Document { + &session.doc().expect("CONTROL: an active document").doc +} + +fn destination(fonts: &[CompositeFont]) -> Session { + let mut session = Session::new(); + session.add_document(Document::new(100.0, 80.0), None); + session.execute("type.compositeFonts.set", &json!({"fonts": fonts})).unwrap(); + session +} + +fn font_document(font: &CompositeFont) -> Document { + let unused = CompositeFont::new(format!("{} Unused", font.name), "Source Sans 3", "Regular"); + let mut session = destination(&[font.clone(), unused]); + session.execute("text.create", &json!({"x": 4, "y": 16, "text": "Ab", "font": font.name})).unwrap(); + let doc = document(&session).clone(); + // Leave the fixture's name cold through an ordinary public edit, not a registry injection. + session.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap(); + doc +} + +fn write_native(path: &Path, source: &Document) -> Document { + let options = vectorcraft_format::SaveOptions { include_linked: true, precision: None, ..Default::default() }; + let bytes = vectorcraft_format::save_with(source, &options).unwrap(); + std::fs::write(path, &bytes).unwrap(); + let loaded = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(loaded.composite_fonts, source.composite_fonts, "CONTROL: native fixture keeps its definitions"); + loaded +} + +fn place(session: &mut Session, path: &Path, linked: bool) -> NodeId { + let reply = session.execute("file.place", &json!({"path": path, "link": linked, "at": [30, 25]})).unwrap(); + assert_eq!(reply["linked"], linked, "CONTROL: the intended public placement route"); + let id = NodeId(reply["ids"][0].as_u64().unwrap()); + if linked { + session.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + } + id +} + +fn placed_family(session: &Session, id: NodeId) -> String { + let root = document(session).node(id).unwrap(); + let mut families = Vec::new(); + root.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + families.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(families.len(), 1, "CONTROL: the one source lettering run remains editable"); + families.pop().unwrap() +} + +fn kept_text(session: &mut Session, font: &CompositeFont) -> (NodeId, Node) { + let reply = session.execute("text.create", &json!({"x": 2, "y": 12, "text": "Destination", "font": font.name})).unwrap(); + let id = NodeId(reply["id"].as_u64().unwrap()); + (id, document(session).node(id).unwrap().clone()) +} + +#[test] +fn native_composite_meanings_survive_editable_and_embedded_placement() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite"); + let path = dir.join("lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionLettering", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + for linked in [false, true] { + // No definition, an exact-name equal definition, and an exact-name conflicting definition. + for state in 0..3 { + let mut existing = incoming.clone(); + if state == 2 { + existing.parts.roman.size = 125.0; + } + let mut fonts = Vec::new(); + if state == 1 { + fonts.push(CompositeFont { name: "NativeAdoptionEquivalentOtherName".into(), ..incoming.clone() }); + } + if state != 0 { + fonts.push(existing.clone()); + } + let mut session = destination(&fonts); + let kept = (state != 0).then(|| kept_text(&mut session, &existing)); + let id = place(&mut session, &path, linked); + let name = placed_family(&session, id); + let imported = CompositeFont::named(&document(&session).composite_fonts, &name) + .expect("REGRESSION: editable native art must retain the meaning of its named composite font"); + assert_eq!((&imported.parts, &imported.custom), (&incoming.parts, &incoming.custom)); + assert_eq!(CompositeFont::same_name(&name, &incoming.name), state != 2); + assert_eq!(document(&session).composite_fonts.len(), if state == 0 { 1 } else { 2 }); + if let Some((id, art)) = kept { + assert_eq!(document(&session).node(id), Some(&art)); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &existing.name), Some(&existing)); + } + } + } +} + +#[test] +fn native_composite_alias_is_reused_without_changing_destination_art() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-repeat"); + let path = dir.join("lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionRepeated", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + for linked in [false, true] { + let mut existing = incoming.clone(); + existing.parts.roman.size = 125.0; + let mut session = destination(std::slice::from_ref(&existing)); + let (kept_id, kept_art) = kept_text(&mut session, &existing); + let first = place(&mut session, &path, linked); + let alias = placed_family(&session, first); + assert!(!CompositeFont::same_name(&alias, &incoming.name), "a real conflict requires an alias"); + let first_definition = CompositeFont::named(&document(&session).composite_fonts, &alias).unwrap().clone(); + let count = document(&session).composite_fonts.len(); + let second = place(&mut session, &path, linked); + assert_eq!(placed_family(&session, second), alias, "repeated art reuses the same meaning, without assuming alias spelling"); + assert_eq!(document(&session).composite_fonts.len(), count); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &alias), Some(&first_definition)); + assert_eq!(document(&session).node(kept_id), Some(&kept_art)); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &existing.name), Some(&existing)); + } +} + +fn snapshot(session: &Session) -> Value { + let state = session.doc().unwrap(); + json!({"document": &*state.doc, "selection": state.selection, + "undo": state.history.undo.len(), "redo": state.history.redo.len(), + "journal": session.journal.iter().cloned().collect::>(), + "journalFirst": session.journal.first_kept(), "journalHeld": session.journal.held()}) +} + +fn plain_text(session: &Session, id: NodeId) -> String { + let NodeKind::Text(text) = &document(session).node(id).unwrap().kind else { + panic!("CONTROL: the live text object remains"); + }; + text.plain_text() +} + +fn select_type_range(session: &mut Session, id: NodeId) -> (vectorcraft_engine::ViewInfo, Value) { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let view = vectorcraft_engine::ViewInfo::default(); + session.select_tool("type", view).unwrap(); + let bounds = document(session).bounds_of(&[id], false).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, bounds.x1 - 1.0, bounds.center().y), view).unwrap(); + } + session.tool_key(ToolKey::Home, Mods::default(), view).unwrap(); + for _ in 0..2 { + session.tool_key(ToolKey::Right, Mods { shift: true, ..Mods::default() }, view).unwrap(); + } + let options = session.tool_options(); + assert_eq!(options["editing"], id.0); + assert_eq!((options["start"].clone(), options["end"].clone()), (json!(0), json!(2))); + assert_eq!(options["typing"], false, "CONTROL: a real selected range, with no pending typing"); + assert!(!session.in_interaction()); + (view, options) +} + +#[test] +fn native_composite_limit_errors_are_atomic_for_place_embed_and_async_replace() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-limit"); + let path = dir.join("one-more-font.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionOneMore", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + let full: Vec<_> = (0..vectorcraft_doc::text::COMPOSITE_FONTS_MAX) + .map(|i| CompositeFont::new(format!("NativeAdoptionHeld{i}"), "Source Sans 3", "Regular")) + .collect(); + for linked in [false, true] { + let mut session = destination(&full); + let command; + let params; + if linked { + let placed = session.execute("file.place", &json!({"path": path, "link": true})).unwrap(); + assert_eq!(placed["linked"], true); + command = "links.embed"; + params = json!({"ids": placed["ids"]}); + } else { + command = "file.place"; + params = json!({"path": path, "link": false}); + } + let before = snapshot(&session); + let registry = registered_fonts(); + let error = session.execute(command, ¶ms).expect_err("REGRESSION: the prospective document exceeds its real composite-font cap"); + assert!(error.to_string().contains("256") && error.to_string().contains("composite"), "the intended cap error: {error}"); + assert_eq!(snapshot(&session), before, "failed adoption preserves art, resources, selection, history and journal"); + assert_eq!(registered_fonts(), registry); + } + // The public async handoff must not leave its provisional reselection behind on this new failure. + let mut session = destination(&full); + let a = session.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 10, "height": 10})).unwrap()["id"].clone(); + let b = NodeId(session.execute("text.create", &json!({"x": 40, "y": 50, "text": "Bravo", "font": "Source Sans 3", "size": 20})) + .unwrap()["id"].as_u64().unwrap()); + session.execute("select.set", &json!({"ids": [a]})).unwrap(); + let read = session.prepare_place(&json!({"path": path, "link": false, "replace": true})).unwrap().read().unwrap(); + let (view, options) = select_type_range(&mut session, b); + let before = snapshot(&session); + let error = session.place_read(read).expect_err("CONTROL: prepared bytes reach the same prospective-font cap"); + assert!(error.to_string().contains("256") && error.to_string().contains("composite")); + assert_eq!(snapshot(&session), before, "failed completion restores the later selection and original replay journal"); + assert_eq!(session.tool_id(), "type"); + assert_eq!(session.tool_options(), options, "provisional reselection must not end the actual Type range/caret"); + assert!(session.tool_wants_text()); + session.tool_text("Z", view).unwrap(); + assert_eq!(plain_text(&session, b), "Zavo", "next typing still replaces the selected Br range"); + session.tool_text("!", view).unwrap(); + assert_eq!(plain_text(&session, b), "Z!avo", "continued typing uses the retained new caret"); + session.keep_typing().unwrap(); + assert_eq!(plain_text(&session, b), "Z!avo"); +} + +#[test] +fn native_composite_import_is_independent_of_unrelated_lent_font_names() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-loan"); + let path = dir.join("lettering.vectorcraft"); + let part = "NativeAdoptionMissingPhysicalFace"; + let incoming = CompositeFont::new("NativeAdoptionWithMissingFace", part, "Regular"); + write_native(&path, &font_document(&incoming)); + let mut session = destination(&[]); + let foreign = CompositeFont::new(part, "Source Sans 3", "Regular"); + let db = FontDb::global(); + let _loan = db.lend_document_composite_fonts(std::slice::from_ref(&foreign)); + assert_eq!(*db.composite_font(part).unwrap(), foreign, "CONTROL: another drawn document lends that name on this thread"); + let id = place(&mut session, &path, false); + let name = placed_family(&session, id); + let imported = CompositeFont::named(&document(&session).composite_fonts, &name).unwrap(); + assert_eq!((&imported.parts, &imported.custom), (&incoming.parts, &incoming.custom)); + assert!(CompositeFont::named(&document(&session).composite_fonts, part).is_none(), "the unrelated loan is not adopted"); + assert_eq!(*db.composite_font(part).unwrap(), foreign, "the caller's loan remains intact"); +} + +fn outline_paths(session: &Session, reply: &Value) -> Vec { + let mut paths = Vec::new(); + for id in reply["ids"].as_array().unwrap() { + document(session).node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |node| { + if let NodeKind::Path { path, .. } = &node.kind { + paths.push(path.clone()); + } + }); + } + assert!(!paths.is_empty(), "CONTROL: real source lettering produced outlines"); + paths +} + +#[test] +fn native_composite_fonts_reach_later_batch_outline_steps() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-batch"); + let path = dir.join("scaled-lettering.vectorcraft"); + let mut incoming = CompositeFont::new("NativeAdoptionBatch", "Source Sans 3", "Regular"); + incoming.parts.roman.size = 125.0; + let source = write_native(&path, &font_document(&incoming)); + let mut text = None; + source.layers[0].walk(&mut |node| { + if let NodeKind::Text(value) = &node.kind { + text = Some((**value).clone()); + } + }); + let text = text.unwrap(); + let db = FontDb::global(); + let intended = { + let _loan = db.lend_document_composite_fonts(std::slice::from_ref(&incoming)); + vectorcraft_text::layout(db, &text) + }; + let fallback = { + let _loan = db.lend_document_composite_fonts(&[]); + vectorcraft_text::layout(db, &text) + }; + assert!((intended.bounds.width() - fallback.bounds.width()).abs() > 0.1, "CONTROL: this source distinguishes intended and fallback glyphs"); + let mut old = incoming.clone(); + old.parts.roman.size = 100.0; + let mut batch = destination(std::slice::from_ref(&old)); + let (kept_id, kept_art) = kept_text(&mut batch, &old); + let reply = batch.execute("command.batch", &json!({"commands": [ + {"command": "file.place", "params": {"path": path, "link": false, "at": [30,25]}}, + {"command": "type.createOutlines", "params": {}} + ]})).unwrap(); + let actual = outline_paths(&batch, &reply["results"][1]); + let imported = document(&batch).composite_fonts.iter().find(|font| font.parts == incoming.parts && font.custom == incoming.custom) + .expect("CONTROL: this batch adopted the distinct 125% meaning"); + assert!(!CompositeFont::same_name(&imported.name, &old.name)); + assert_eq!(document(&batch).node(kept_id), Some(&kept_art)); + assert_eq!(CompositeFont::named(&document(&batch).composite_fonts, &old.name), Some(&old)); + // Run the ordinary control only after the cold batch, so it cannot prewarm the imported alias. + let mut ordinary = destination(std::slice::from_ref(&old)); + place(&mut ordinary, &path, false); + let reply = ordinary.execute("type.createOutlines", &json!({})).unwrap(); + assert_eq!(actual, outline_paths(&ordinary, &reply), "batch layout must see the imported meaning before top-level synchronization"); +} + +fn menu_has(reply: &Value, name: &str) -> bool { + reply["families"].as_array().unwrap().iter().any(|family| family.as_str().is_some_and(|f| f.eq_ignore_ascii_case(name))) +} + +#[test] +fn native_composite_preview_fonts_follow_cancel_replacement_commit_and_undo() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-preview"); + let path = dir.join("lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionPreview", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + let held = CompositeFont::new("NativeAdoptionPreviewHeld", "Source Sans 3", "Regular"); + for boundary in 0..3 { + let mut session = destination(std::slice::from_ref(&held)); + let before = document(&session).clone(); + let registry = registered_fonts(); + assert!(!menu_has(&session.execute("text.fontList", &json!({})).unwrap(), &incoming.name)); + session.begin_interaction("Preview native lettering").unwrap(); + session.preview("command.batch", &json!({"commands": [ + {"command": "file.place", "params": {"path": path, "link": false}} + ]})).unwrap(); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &incoming.name), Some(&incoming)); + assert_eq!(*FontDb::global().composite_font(&incoming.name).unwrap(), incoming); + match boundary { + 0 => { + session.cancel_interaction().unwrap(); + assert_eq!(registered_fonts(), registry, "cancel restores the registry before another command can hide a leak"); + } + 1 => { + let next = session.preview("text.fontList", &json!({})).unwrap(); + assert!(!menu_has(&next, &incoming.name), "the first consumer after replacing a preview must not see its old font"); + assert_eq!(registered_fonts(), registry); + session.cancel_interaction().unwrap(); + } + _ => { + session.commit_interaction().unwrap(); + assert_eq!(*FontDb::global().composite_font(&incoming.name).unwrap(), incoming, "commit keeps the imported meaning"); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(registered_fonts(), registry, "Undo restores the pre-preview font meanings"); + } + } + assert_eq!(document(&session), &before); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &held.name), Some(&held)); + } +} From 2368fccc14a8da09ed0a32db0581a4b9a522ea15 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 16:52:20 -0800 Subject: [PATCH 02/18] fix: preserve composite fonts when adopting native artwork --- crates/engine/src/cmd/clipboard/resources.rs | 4 +- crates/engine/src/cmd/compositefonts.rs | 170 +++++++++++++++++- crates/engine/src/cmd/place.rs | 72 ++++++-- crates/engine/src/cmd/place/adopt.rs | 80 ++++++++- crates/engine/src/cmd/place/document.rs | 2 +- crates/engine/src/session/edit.rs | 2 + crates/engine/src/session/execute.rs | 4 + .../engine/tests/native_composite_adoption.rs | 79 ++++++++ 8 files changed, 396 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 9a5be1fc4f..3a3c981229 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -903,7 +903,7 @@ pub struct SymbolOptions { impl SymbolOptions { /// The options `d` keeps for symbol `name`. - fn of(d: &Document, name: &str) -> Self { + pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self { Self { size: stored_natural_size(d, name), registration: d.symbol_registration(name), @@ -914,7 +914,7 @@ impl SymbolOptions { } /// Make them the options of `d`'s symbol `name`. - fn give(&self, d: &mut Document, name: &str) { + pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) { set_natural_size(d, name, self.size); d.set_symbol_registration(name, self.registration); d.set_symbol_export_type(name, self.export_type); diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index b9f304ddf4..2f57fc1ab7 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -10,9 +10,12 @@ //! custom character sets: //! . +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + use serde_json::{Map, Value, json}; use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX}; -use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet}; +use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind}; use vectorcraft_text::FontDb; use super::fileio::{read_file_head, write_file}; @@ -77,6 +80,171 @@ pub fn specs() -> Vec { ] } +/// Every stored family name, including regeneration settings and retained style defaults. +/// Planning reads a private clone so gathering names never changes the destination. +fn family_names(d: &Document) -> Result> { + let mut view = d.clone(); + let mut names = BTreeSet::new(); + let mut note = |family: &mut String| { + names.insert(family.to_lowercase()); + }; + super::textstyles::each_text_mut(&mut view, &mut |text| { + for run in &mut text.runs { + note(&mut run.style.font_family); + } + Ok(()) + })?; + for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) { + if let Some(Value::String(family)) = style.attrs.get_mut("font_family") { + note(family); + } + } + let mut graphs = Vec::new(); + view.visit_stored(|node, _| { + if node.extras().graph.is_some() { + graphs.push(node.id); + } + }); + for id in graphs { + if let Some(node) = view.stored_node_mut(id) { + graph_families(node, &mut note); + } + } + fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) { + graph_families(node, note); + if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) { + brush_graphs(Arc::make_mut(&mut mask.art), note); + } + for child in node.children_mut().into_iter().flatten() { + brush_graphs(Arc::make_mut(child), note); + } + } + for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) { + brush_graphs(art, &mut note); + } + Ok(names) +} + +fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) { + if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) { + let labels = &mut graph.label_styles; + for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() { + visit(&mut style.font_family); + } + } +} + +/// Family fields held directly by one node; the adoption walker owns tree/resource traversal. +pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) { + if let NodeKind::Text(text) = &mut node.kind { + for run in &mut text.runs { + visit(&mut run.style.font_family); + } + } + graph_families(node, visit); +} + +/// A fully checked incoming-only rename map and the destination's prospective definitions. +pub(super) struct CompositeImport { + names: BTreeMap, + pub(super) combined: Vec, +} + +impl CompositeImport { + pub(super) fn rename(&self, family: &mut String) -> bool { + if let Some(name) = self.names.get(&family.to_lowercase()) { + let changed = family.as_str() != name.as_str(); + *family = name.clone(); + changed + } else { + false + } + } +} + +fn composite_alias(base: &str, reserved: &BTreeSet, cmd: &str) -> Result { + let db = FontDb::global(); + let mut number = 2_u64; + loop { + let suffix = format!(" {number}"); + let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect(); + let name = format!("{}{suffix}", stem.trim_end()); + if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str()) + && !reserved.contains(&name.to_lowercase()) + && !db.has_installed_family(&name) + { + return Ok(name); + } + number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?; + } +} + +/// Plan used incoming definitions before changing either document or the font database. +/// Keep existing meanings even for an uninstalled family that destination art still names. +pub(super) fn plan_import( + source: Vec, + source_families: BTreeSet, + target: &Document, + cmd: &str, +) -> Result { + if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX { + return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); + } + let mut source_names = BTreeSet::new(); + for font in &source { + font.check().map_err(|why| bad(cmd, why))?; + if !source_names.insert(font.name.to_lowercase()) { + return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name))); + } + } + let target_families = family_names(target)?; + let mut target_taken = target_families.clone(); + for font in target.composite_fonts.iter() { + target_taken.insert(font.name.to_lowercase()); + target_taken.extend(font.part_fonts().map(str::to_lowercase)); + } + let mut reserved = source_families; + reserved.extend(target_families); + for font in source.iter().chain(target.composite_fonts.iter()) { + reserved.insert(font.name.to_lowercase()); + reserved.extend(font.part_fonts().map(str::to_lowercase)); + } + let db = FontDb::global(); + let mut names = BTreeMap::new(); + let mut combined = target.composite_fonts.to_vec(); + for font in source { + let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom; + let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent); + let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name)); + if needs_alias { + // A repeated import reuses its already-installed equal alias. + reused = target.composite_fonts.iter().find(equivalent); + } + let name = match reused { + Some(other) => other.name.clone(), + None if needs_alias => composite_alias(&font.name, &reserved, cmd)?, + None => font.name.clone(), + }; + reserved.insert(name.to_lowercase()); + names.insert(font.name.to_lowercase(), name.clone()); + if reused.is_none() { + combined.push(CompositeFont { name, ..font }); + } + } + // A source document may currently lend fonts to the database. Validate the prospective + // document, not composite names temporarily registered by a different document. + if combined.len() > COMPOSITE_FONTS_MAX { + return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); + } + if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) { + return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name))); + } + if CompositeFont::usable(&combined).is_some() { + return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together")); + } + Ok(CompositeImport { names, combined }) +} + /// Register the active document's composite fonts in the font database, and remove the ones the /// other open documents (or an earlier active document) defined. Run after each command and when /// another document takes the front, so an undo, a revert, an opened or closed file or a document diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 3e0a808fd5..93fbf3e637 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -578,7 +578,7 @@ fn art_of<'a>(nodes: impl Iterator>) -> Vec { } /// The art as one object of `d` (its resources added), at its natural size and position. -fn build(d: &mut Document, l: Loaded, link: Option) -> Node { +fn build(d: &mut Document, l: Loaded, link: Option) -> Result { let mut node = match l.art { Art::Image(img, clip) => { let (sx, sy) = pt_per_px(img.ppi); @@ -613,7 +613,7 @@ fn build(d: &mut Document, l: Loaded, link: Option) -> Node { Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))), Art::Document(s, link, bounding) => document::node(d, &s, link, bounding), Art::Vector { src, mut nodes, clip } => { - adopt::adopt(d, &src, &mut nodes); + adopt::adopt(d, &src, &mut nodes, PLACE)?; let mut children: Vec> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect(); if let Some(r) = clip { children.insert(0, Arc::new(clip_path(d.alloc_id(), r))); @@ -622,7 +622,7 @@ fn build(d: &mut Document, l: Loaded, link: Option) -> Node { } }; node.name = Some(l.name); - node + Ok(node) } /// `node` moved and scaled by `m` as a whole: strokes, effects and pattern tiles go along. @@ -764,21 +764,73 @@ impl Session { return Err(bad(PLACE, NOT_ACTIVE)); } let params = read.job.params.clone(); + let mut rollback = None; + let mut reselect = None; if let Some(old) = read.job.old { let st = self.doc()?; - // Deleted, changed, or another object with its id: an undo that removes the object frees - // its id for the next object made. + // Retain the existing asynchronous target checks unchanged. if st.doc.node(old) != read.job.replaced.as_ref() { return Err(bad(PLACE, "replace: the object to replace was changed or deleted")); } if st.selection.objects != [old] || st.selection.symbol_part.is_some() { - self.execute("select.set", &json!({ "ids": [old.0] }))?; + // Adoption may now fail. Its provisional selection must not escape that error. + rollback = Some(( + self.active, + st.clone(), + self.paint.clone(), + self.fill_active, + self.pending_paint.clone(), + self.active_appearance_item.clone(), + self.batch_paint_docs.clone(), + self.journal.len(), + self.journal.held(), + )); + self.journal.hold(Some(self.journal.first_kept())); + reselect = Some(old); } } - self.place_hand_off = Some(read); - let r = self.execute(PLACE, ¶ms); + let outer_tool_actions = self.in_tool_actions; + if reselect.is_some() { + self.in_tool_actions = true; + } + let result = (|| { + if let Some(old) = reselect { + self.execute("select.set", &json!({ "ids": [old.0] }))?; + } + self.place_hand_off = Some(read); + self.execute(PLACE, ¶ms) + })(); self.place_hand_off = None; - r + if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback { + if result.is_err() { + if let Some(st) = self.docs.iter_mut().find(|st| st.uid == before.uid) { + let revision = st.revision.max(before.revision); + *st = before; + st.revision = revision + 1; + } + self.active = active; + self.paint = paint; + self.fill_active = fill_active; + self.pending_paint = pending; + self.active_appearance_item = appearance; + self.batch_paint_docs = paint_docs; + self.journal.truncate(journal); + for group in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) { + group.journal.retain(|&(n, _)| n < journal); + group.steps.retain(|&(n, _)| n < journal); + } + self.clear_deferred_overlay_cache(); + self.decoded_images.empty(); + self.sync_front_profiles(); + super::compositefonts::sync(self); + } + self.journal.hold(held); + } + if reselect.is_some() { + self.in_tool_actions = outer_tool_actions; + self.after_command(result.is_ok().then_some(PLACE)); + } + result } } @@ -892,7 +944,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")), } let (id, size, slice_ids) = s.edit("Place", |d, sel| { - let node = transformed(build(d, loaded, link), m); + let node = transformed(build(d, loaded, link)?, m); let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); let (into, index) = match old { Some(old) => { diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index f64a6a6874..e148e00a96 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -5,13 +5,16 @@ //! defines differently keeps its colour, unlinked. Text styles are left as they are: the art carries //! its own formatting. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use vectorcraft_brush::{Brush, BrushKind}; use vectorcraft_color::Paint; use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol}; +use super::super::clipboard::SymbolOptions; +use super::super::compositefonts::{CompositeImport, node_families, plan_import}; +use super::super::Result; use super::unique_name; /// Visit `n` and every descendant (children and opacity-mask art) mutably. @@ -220,14 +223,64 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> { } } +/// Remap only incoming users before resource equality decides whether to share or copy. +/// A symbol whose new font alias forces a copy keeps its existing pixel/export options. +fn remap_composite_families( + src: &Document, + nodes: &mut [Node], + used: &Used, + brushes: &mut [Brush], + plan: &CompositeImport, +) -> (Document, BTreeSet) { + let mut staged = src.clone(); + for node in nodes.iter_mut() { + each_mut(node, &mut |node| { + node_families(node, &mut |family| { plan.rename(family); }); + }); + } + let mut changed_symbols = BTreeSet::new(); + for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) { + let mut changed = false; + each_mut(Arc::make_mut(&mut symbol.art), &mut |node| { + node_families(node, &mut |family| { changed |= plan.rename(family); }); + }); + if changed { + changed_symbols.insert(symbol.name.clone()); + } + } + for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) { + for art in &mut pattern.art { + each_mut(Arc::make_mut(art), &mut |node| { + node_families(node, &mut |family| { plan.rename(family); }); + }); + } + } + for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) { + for art in brush_art(brush) { + each_mut(art, &mut |node| { + node_families(node, &mut |family| { plan.rename(family); }); + }); + } + } + (staged, changed_symbols) +} + /// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point /// `nodes` at the names they got. -pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { +pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> { let mut used = Used::default(); + let composites = !src.composite_fonts.is_empty(); + let mut families = BTreeSet::new(); + let mut note_family = |name: &mut String| { + families.insert(name.to_lowercase()); + }; for n in nodes.iter_mut() { refs(n, &mut |r| used.note(r)); + if composites { + each_mut(n, &mut |node| node_families(node, &mut note_family)); + } } - let src_brushes = vectorcraft_brush::library(src); + let mut src_brushes = vectorcraft_brush::library(src); // Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while // they are walked). let (mut si, mut pi, mut wi, mut bi) = (0, 0, 0, 0); @@ -254,8 +307,22 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { } for mut a in art { refs(&mut a, &mut |r| used.note(r)); + if composites { + each_mut(&mut a, &mut |node| node_families(node, &mut note_family)); + } } } + let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::>(); + // All representability/validation errors precede incoming or destination mutation. + let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) }; + let staged; + let mut changed_symbols = BTreeSet::new(); + let src = if let Some(plan) = &plan { + (staged, changed_symbols) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan); + &staged + } else { + src + }; let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c)); // Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it @@ -330,6 +397,9 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c)); } + if let Some(plan) = plan { + dst.composite_fonts = plan.combined.into(); + } let mut rename = |r: Ref| { let (map, k) = match r { Ref::Image(k) => (&images, k), @@ -375,6 +445,9 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { // The art takes ids of `dst`: those of `src` may name objects of `dst` already. def.art = Arc::new(dst.reid(&def.art)); dst.symbols.push(def); + if changed_symbols.contains(old) { + SymbolOptions::of(src, old).give(dst, new); + } } } for (old, new) in copies(&patterns) { @@ -406,4 +479,5 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) { dst.swatches.push(w); } } + Ok(()) } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index f24242ed70..6e9a1f242c 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -544,7 +544,7 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> { let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, cmd)?; let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?; let mut nodes = a.nodes; - super::adopt::adopt(d, &a.doc, &mut nodes); + super::adopt::adopt(d, &a.doc, &mut nodes, cmd)?; let mut children: Vec> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect(); if let Some(r) = a.clip { children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r))); diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index d5d62e607c..1975dda20a 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -623,6 +623,7 @@ impl Session { self.pending_paint = None; // The previous preview's Assign Profile is undone with it. self.sync_front_profiles(); + cmd::compositefonts::sync(self); let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params)); let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p)); // A selected object's converted appearance must not replace the current paints while @@ -788,6 +789,7 @@ impl Session { deselect_hidden(&menu, &st.doc, &mut st.selection); // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); + cmd::compositefonts::sync(self); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as // the document has it again, not as a preview left it. An interaction that changed only the // defaults (`defaultsOnly: true`) leaves the defaults it began with. diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 8b8bef8679..a7e0593d42 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -247,6 +247,10 @@ impl Session { // after an undone or redone Assign Profile, a failed or panicked command's documents put // back, and a batch step, before the next step converts through them. self.sync_front_profiles(); + if self.depth != 0 { + // The next batch step can measure/outline definitions this step adopted. + cmd::compositefonts::sync(self); + } if r.is_err() && self.depth == 0 { self.batch_paint_docs.clear(); // A failed or panicked command's documents are put back: type is drawn in their diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index a0f1fa11f7..afbac16bfe 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -379,3 +379,82 @@ fn native_composite_preview_fonts_follow_cancel_replacement_commit_and_undo() { assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &held.name), Some(&held)); } } + +#[test] +fn native_composite_alias_forced_symbol_copy_keeps_all_symbol_options() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-symbol"); + let path = dir.join("symbol-lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionSymbolFont", "Source Sans 3", "Regular"); + let mut builder = Session::new(); + builder.add_document(font_document(&incoming), None); + let mut text_id = None; + document(&builder).layers[0].walk(&mut |node| { + if matches!(&node.kind, NodeKind::Text(_)) { + assert!(text_id.replace(node.id).is_none(), "CONTROL: exactly one source lettering object"); + } + }); + let symbol = "NativeAdoptionLetteringSymbol"; + builder.execute("symbol.new", &json!({ + "name": symbol, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true + })).unwrap(); + let source = write_native(&path, document(&builder)); + let options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); + assert!(options.size.is_some(), "CONTROL: the real symbol constructor recorded its natural size"); + assert_eq!(options.registration, vectorcraft_doc::SymbolRegistration(0)); + assert_eq!(options.export_type, vectorcraft_doc::SymbolExportType::Graphic); + assert_eq!(options.nine_slice, vectorcraft_doc::SymbolNineSlice::new(0.2, 0.3, 0.25, 0.15)); + assert!(options.pixel_aligned); + + for linked in [false, true] { + let mut target = source.clone(); + let index = target.composite_fonts.iter().position(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); + target.composite_fonts[index].parts.roman.size = 125.0; + let held_font = target.composite_fonts[index].clone(); + assert_eq!(target.symbols, source.symbols, "CONTROL: identical symbol names and art before only the font meaning changes"); + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let held_options = Clipboard::from_document(&before).symbol_options.get(symbol).unwrap().clone(); + assert_eq!(held_options, options, "CONTROL: options also match; the font alias alone must force the new copy"); + + let id = place(&mut session, &path, linked); + let mut used_symbols = Vec::new(); + document(&session).node(id).unwrap().walk(&mut |node| { + if let NodeKind::SymbolInstance { symbol, .. } = &node.kind { + used_symbols.push(symbol.clone()); + } + }); + assert_eq!(used_symbols.len(), 1); + let copied_name = &used_symbols[0]; + assert_ne!(copied_name.as_str(), symbol, "the import must not reuse art whose same family name has a different meaning here"); + let copied = document(&session).symbols.iter().find(|definition| &definition.name == copied_name).unwrap(); + let mut families = Vec::new(); + copied.art.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + families.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(families.len(), 1); + assert!(!CompositeFont::same_name(&families[0], &incoming.name)); + let adopted = CompositeFont::named(&document(&session).composite_fonts, &families[0]).unwrap(); + assert_eq!((&adopted.parts, &adopted.custom), (&incoming.parts, &incoming.custom)); + let after = Clipboard::from_document(document(&session)); + assert_eq!(after.symbol_options.get(copied_name), Some(&options), "the alias-forced copy preserves all five option fields"); + assert_eq!(after.symbol_options.get(symbol), Some(&held_options)); + assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &incoming.name), Some(&held_font)); + assert_eq!( + document(&session).symbols.iter().find(|definition| definition.name == symbol), + before.symbols.iter().find(|definition| definition.name == symbol) + ); + for layer in &before.layers { + for child in layer.children().unwrap() { + assert_eq!(document(&session).node(child.id), Some(child.as_ref()), "existing destination art remains exact"); + } + } + assert_eq!(document(&session).symbols.len(), before.symbols.len() + 1); + } +} From c2e83d1d7030292ee237fb8c41f47265bb885924 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 16:55:33 -0800 Subject: [PATCH 03/18] style: format native composite adoption and controls --- crates/engine/src/cmd/compositefonts.rs | 7 +-- crates/engine/src/cmd/place/adopt.rs | 18 +++++-- .../engine/tests/native_composite_adoption.rs | 49 +++++++++++++------ 3 files changed, 49 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index 2f57fc1ab7..bff15c6540 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -181,12 +181,7 @@ fn composite_alias(base: &str, reserved: &BTreeSet, cmd: &str) -> Result /// Plan used incoming definitions before changing either document or the font database. /// Keep existing meanings even for an uninstalled family that destination art still names. -pub(super) fn plan_import( - source: Vec, - source_families: BTreeSet, - target: &Document, - cmd: &str, -) -> Result { +pub(super) fn plan_import(source: Vec, source_families: BTreeSet, target: &Document, cmd: &str) -> Result { if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX { return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); } diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index e148e00a96..8e63e1ae17 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -12,9 +12,9 @@ use vectorcraft_brush::{Brush, BrushKind}; use vectorcraft_color::Paint; use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol}; +use super::super::Result; use super::super::clipboard::SymbolOptions; use super::super::compositefonts::{CompositeImport, node_families, plan_import}; -use super::super::Result; use super::unique_name; /// Visit `n` and every descendant (children and opacity-mask art) mutably. @@ -235,14 +235,18 @@ fn remap_composite_families( let mut staged = src.clone(); for node in nodes.iter_mut() { each_mut(node, &mut |node| { - node_families(node, &mut |family| { plan.rename(family); }); + node_families(node, &mut |family| { + plan.rename(family); + }); }); } let mut changed_symbols = BTreeSet::new(); for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) { let mut changed = false; each_mut(Arc::make_mut(&mut symbol.art), &mut |node| { - node_families(node, &mut |family| { changed |= plan.rename(family); }); + node_families(node, &mut |family| { + changed |= plan.rename(family); + }); }); if changed { changed_symbols.insert(symbol.name.clone()); @@ -251,14 +255,18 @@ fn remap_composite_families( for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) { for art in &mut pattern.art { each_mut(Arc::make_mut(art), &mut |node| { - node_families(node, &mut |family| { plan.rename(family); }); + node_families(node, &mut |family| { + plan.rename(family); + }); }); } } for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) { for art in brush_art(brush) { each_mut(art, &mut |node| { - node_families(node, &mut |family| { plan.rename(family); }); + node_families(node, &mut |family| { + plan.rename(family); + }); }); } } diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index afbac16bfe..2c5d6fe32f 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -234,8 +234,11 @@ fn native_composite_limit_errors_are_atomic_for_place_embed_and_async_replace() // The public async handoff must not leave its provisional reselection behind on this new failure. let mut session = destination(&full); let a = session.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 10, "height": 10})).unwrap()["id"].clone(); - let b = NodeId(session.execute("text.create", &json!({"x": 40, "y": 50, "text": "Bravo", "font": "Source Sans 3", "size": 20})) - .unwrap()["id"].as_u64().unwrap()); + let b = NodeId( + session.execute("text.create", &json!({"x": 40, "y": 50, "text": "Bravo", "font": "Source Sans 3", "size": 20})).unwrap()["id"] + .as_u64() + .unwrap(), + ); session.execute("select.set", &json!({"ids": [a]})).unwrap(); let read = session.prepare_place(&json!({"path": path, "link": false, "replace": true})).unwrap().read().unwrap(); let (view, options) = select_type_range(&mut session, b); @@ -317,12 +320,20 @@ fn native_composite_fonts_reach_later_batch_outline_steps() { old.parts.roman.size = 100.0; let mut batch = destination(std::slice::from_ref(&old)); let (kept_id, kept_art) = kept_text(&mut batch, &old); - let reply = batch.execute("command.batch", &json!({"commands": [ - {"command": "file.place", "params": {"path": path, "link": false, "at": [30,25]}}, - {"command": "type.createOutlines", "params": {}} - ]})).unwrap(); + let reply = batch + .execute( + "command.batch", + &json!({"commands": [ + {"command": "file.place", "params": {"path": path, "link": false, "at": [30,25]}}, + {"command": "type.createOutlines", "params": {}} + ]}), + ) + .unwrap(); let actual = outline_paths(&batch, &reply["results"][1]); - let imported = document(&batch).composite_fonts.iter().find(|font| font.parts == incoming.parts && font.custom == incoming.custom) + let imported = document(&batch) + .composite_fonts + .iter() + .find(|font| font.parts == incoming.parts && font.custom == incoming.custom) .expect("CONTROL: this batch adopted the distinct 125% meaning"); assert!(!CompositeFont::same_name(&imported.name, &old.name)); assert_eq!(document(&batch).node(kept_id), Some(&kept_art)); @@ -352,9 +363,14 @@ fn native_composite_preview_fonts_follow_cancel_replacement_commit_and_undo() { let registry = registered_fonts(); assert!(!menu_has(&session.execute("text.fontList", &json!({})).unwrap(), &incoming.name)); session.begin_interaction("Preview native lettering").unwrap(); - session.preview("command.batch", &json!({"commands": [ - {"command": "file.place", "params": {"path": path, "link": false}} - ]})).unwrap(); + session + .preview( + "command.batch", + &json!({"commands": [ + {"command": "file.place", "params": {"path": path, "link": false}} + ]}), + ) + .unwrap(); assert_eq!(CompositeFont::named(&document(&session).composite_fonts, &incoming.name), Some(&incoming)); assert_eq!(*FontDb::global().composite_font(&incoming.name).unwrap(), incoming); match boundary { @@ -397,10 +413,15 @@ fn native_composite_alias_forced_symbol_copy_keeps_all_symbol_options() { } }); let symbol = "NativeAdoptionLetteringSymbol"; - builder.execute("symbol.new", &json!({ - "name": symbol, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", - "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true - })).unwrap(); + builder + .execute( + "symbol.new", + &json!({ + "name": symbol, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true + }), + ) + .unwrap(); let source = write_native(&path, document(&builder)); let options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); assert!(options.size.is_some(), "CONTROL: the real symbol constructor recorded its natural size"); From 22571b6713ada292066a72444811b6927aa23ad1 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 16:59:05 -0800 Subject: [PATCH 04/18] fix: propagate native adoption errors from thumbnail building --- crates/engine/src/cmd/place.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 93fbf3e637..50aeb9414d 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -1197,7 +1197,7 @@ fn thumbnail_png(l: Loaded, px: f64) -> Result { let natural = l.natural; let mut d = Document::new(natural.width().max(1.0), natural.height().max(1.0)); let layer = d.layers.first().map(|l| l.id); - let node = build(&mut d, l, None); + let node = build(&mut d, l, None)?; d.insert(layer, 0, node)?; let k = px.clamp(1.0, MAX_THUMBNAIL) / natural.width().max(natural.height()).max(1e-9); let png = vectorcraft_render::Renderer::new().render_region(&d, natural, k, false).to_png().map_err(EngineError::Other)?; From f0379dfff93f36f9f9f06940c0aebaa526a908e9 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 17:10:49 -0800 Subject: [PATCH 05/18] refactor: separate native resource discovery from adoption --- crates/engine/src/cmd/place/adopt.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 8e63e1ae17..4a92e808ee 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -273,9 +273,9 @@ fn remap_composite_families( (staged, changed_symbols) } -/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point -/// `nodes` at the names they got. -pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> { +/// Discover the incoming resource frontier and its composite-font users before planning +/// names or changing either document. Resource order and the no-composite fast path stay shared. +fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec, BTreeSet) { let mut used = Used::default(); let composites = !src.composite_fonts.is_empty(); let mut families = BTreeSet::new(); @@ -288,7 +288,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: each_mut(n, &mut |node| node_families(node, &mut note_family)); } } - let mut src_brushes = vectorcraft_brush::library(src); + let src_brushes = vectorcraft_brush::library(src); // Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while // they are walked). let (mut si, mut pi, mut wi, mut bi) = (0, 0, 0, 0); @@ -320,6 +320,13 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: } } } + (used, src_brushes, families) +} + +/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point +/// `nodes` at the names they got. +pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> { + let (used, mut src_brushes, families) = collect_resources(src, nodes); let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::>(); // All representability/validation errors precede incoming or destination mutation. let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) }; From dc225dc52fec0d2fa3272dd923d2eb4ae763075e Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 17:33:56 -0800 Subject: [PATCH 06/18] test: cover repeated native aliases and asynchronous drag isolation --- .../engine/tests/native_composite_adoption.rs | 309 ++++++++++++++++++ 1 file changed, 309 insertions(+) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 2c5d6fe32f..932595a584 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -477,5 +477,314 @@ fn native_composite_alias_forced_symbol_copy_keeps_all_symbol_options() { } } assert_eq!(document(&session).symbols.len(), before.symbols.len() + 1); + let first_symbols = document(&session).symbols.clone(); + let first_fonts = document(&session).composite_fonts.clone(); + let first_resources = native_resource_counts(document(&session)); + let repeated = place(&mut session, &path, linked); + let repeated_name = only_symbol_name(document(&session).node(repeated).unwrap()); + assert_eq!(&repeated_name, copied_name, "repeating the import reuses the actual first symbol alias"); + assert_eq!(symbol_font_family(document(&session), &repeated_name), families[0]); + assert_eq!(native_resource_counts(document(&session)), first_resources, "repetition adds art, not more resources"); + assert_eq!(document(&session).symbols, first_symbols); + assert_eq!(document(&session).composite_fonts, first_fonts); + assert_original_native_art(document(&session), &before); + } +} + +fn only_symbol_name(root: &Node) -> String { + let mut names = Vec::new(); + root.walk(&mut |node| { + if let NodeKind::SymbolInstance { symbol, .. } = &node.kind { + names.push(symbol.clone()); + } + }); + assert_eq!(names.len(), 1, "CONTROL: one instance at this level of the native symbol chain"); + names.pop().unwrap() +} + +fn symbol_font_family(doc: &Document, symbol: &str) -> String { + let art = &doc.symbols.iter().find(|definition| definition.name == symbol).unwrap().art; + let mut names = Vec::new(); + art.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + names.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(names.len(), 1, "CONTROL: the inner symbol retains editable source lettering"); + names.pop().unwrap() +} + +fn native_resource_counts(doc: &Document) -> Value { + json!({"fonts": doc.composite_fonts.len(), "symbols": doc.symbols.len(), "patterns": doc.patterns.len(), + "images": doc.images.len(), "graphicStyles": doc.graphic_styles.len(), "charStyles": doc.char_styles.len(), + "paraStyles": doc.para_styles.len(), "swatches": doc.swatches.len(), "groups": doc.swatch_groups.len(), + "graphDesigns": doc.graph_designs.len(), "brushes": vectorcraft_brush::library(doc).len()}) +} + +fn assert_original_native_art(doc: &Document, before: &Document) { + for symbol in &before.symbols { + assert_eq!(doc.symbols.iter().find(|definition| definition.name == symbol.name), Some(symbol)); + } + for font in &before.composite_fonts { + assert_eq!(CompositeFont::named(&doc.composite_fonts, &font.name), Some(font)); + } + for pattern in &before.patterns { + assert_eq!(doc.pattern(&pattern.name), Some(pattern), "the original destination pattern meaning is unchanged"); + } + for brush in vectorcraft_brush::library(before) { + assert_eq!(vectorcraft_brush::find(doc, &brush.name), Some(brush), "the original stored brush meaning is unchanged"); + } + for layer in &before.layers { + for child in layer.children().unwrap() { + assert_eq!(doc.node(child.id), Some(child.as_ref()), "the pre-existing destination art is unchanged"); + } + } +} + +fn pattern_in_symbol(doc: &Document, symbol: &str) -> String { + let art = &doc.symbols.iter().find(|definition| definition.name == symbol).unwrap().art; + let mut names = Vec::new(); + art.walk(&mut |node| { + if let vectorcraft_color::Paint::Pattern { pattern, .. } = node.appearance.fill_paint() { + names.push(pattern.clone()); + } + }); + assert_eq!(names.len(), 1, "CONTROL: one pattern dependency in the inner symbol"); + names.pop().unwrap() +} + +fn pattern_font_family(doc: &Document, pattern: &str) -> String { + let mut names = Vec::new(); + for root in &doc.pattern(pattern).unwrap().art { + root.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + names.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + } + assert_eq!(names.len(), 1, "CONTROL: the pattern holds the one editable source lettering run"); + names.pop().unwrap() +} + +fn brush_in_symbol(doc: &Document, symbol: &str) -> String { + let art = &doc.symbols.iter().find(|definition| definition.name == symbol).unwrap().art; + let mut names = Vec::new(); + art.walk(&mut |node| { + if let Some(brush) = node.appearance.stroke().and_then(|stroke| stroke.brush.as_ref()) { + names.push(brush.clone()); + } + }); + assert_eq!(names.len(), 1, "CONTROL: one brush dependency in the inner symbol"); + names.pop().unwrap() +} + +fn brush_font_family(doc: &Document, name: &str) -> String { + let brush = vectorcraft_brush::find(doc, name).unwrap(); + let vectorcraft_brush::BrushKind::Art(brush) = &brush.kind else { + panic!("CONTROL: the imported resource remains an art brush"); + }; + assert_eq!(brush.width, 137.0, "the brush retains the non-default width chosen by its creator"); + let mut names = Vec::new(); + brush.art.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + names.extend(text.runs.iter().filter(|run| run.text == "Ab").map(|run| run.style.font_family.clone())); + } + }); + assert_eq!(names.len(), 1, "CONTROL: the brush library, not document art, holds the editable source lettering"); + names.pop().unwrap() +} + +#[test] +fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-nested"); + let incoming = CompositeFont::new("NativeAdoptionNestedFont", "Source Sans 3", "Regular"); + for dependency in 0..3 { + let path = dir.join(format!("nested-lettering-{dependency}.vectorcraft")); + let mut builder = Session::new(); + builder.add_document(font_document(&incoming), None); + let mut text_id = None; + document(&builder).layers[0].walk(&mut |node| { + if matches!(&node.kind, NodeKind::Text(_)) { + assert!(text_id.replace(node.id).is_none()); + } + }); + let pattern_name = "NativeAdoptionPatternText"; + let brush_name = "NativeAdoptionBrushText"; + if dependency != 0 { + if dependency == 1 { + builder.execute("object.pattern.make", &json!({"ids":[text_id.unwrap().0],"name":pattern_name,"edit":false})).unwrap(); + } else { + builder.execute("brush.new", &json!({"type":"art","name":brush_name,"ids":[text_id.unwrap().0], + "params":{"width":137.0}})).unwrap(); + } + let mut doc = document(&builder).clone(); + doc.remove(text_id.unwrap()).unwrap(); + let id = doc.alloc_id(); + let appearance = if dependency == 1 { + vectorcraft_doc::Appearance::basic(vectorcraft_doc::pattern::pattern_paint(pattern_name), vectorcraft_color::Paint::None, 0.0) + } else { + let mut appearance = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0); + appearance.stroke_mut().unwrap().brush = Some(brush_name.into()); + appearance + }; + let rectangle = Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0,0.0,20.0,20.0)), appearance); + std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(rectangle)); + doc.fix_next_id(); + builder = Session::new(); + builder.add_document(doc, None); + text_id = Some(id); + } + let inner = "NativeAdoptionInner"; + let outer = "NativeAdoptionOuter"; + let made = builder.execute("symbol.new", &json!({ + "name": inner, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2,0.3,0.25,0.15], "alignToPixelGrid": true + })).unwrap(); + builder.execute("symbol.new", &json!({ + "name": outer, "ids": [made["id"]], "registration": 8, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.1,0.2,0.3,0.25], "alignToPixelGrid": true + })).unwrap(); + let source = write_native(&path, document(&builder)); + let source_options = Clipboard::from_document(&source).symbol_options; + for (name, registration, guides) in [ + (inner, 0, vectorcraft_doc::SymbolNineSlice::new(0.2,0.3,0.25,0.15)), + (outer, 8, vectorcraft_doc::SymbolNineSlice::new(0.1,0.2,0.3,0.25)), + ] { + let options = source_options.get(name).unwrap(); + assert!(options.size.is_some()); + assert_eq!(options.registration, vectorcraft_doc::SymbolRegistration(registration)); + assert_eq!(options.export_type, vectorcraft_doc::SymbolExportType::Graphic); + assert_eq!(options.nine_slice, guides); + assert!(options.pixel_aligned); + } + for linked in [false, true] { + let mut target = source.clone(); + let font = target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); + font.parts.roman.size = 125.0; + assert_eq!(target.symbols, source.symbols, "CONTROL: only the meaning of the existing font differs"); + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let id = place(&mut session, &path, linked); + let copied_outer = only_symbol_name(document(&session).node(id).unwrap()); + assert_ne!(copied_outer, outer); + let outer_art = &document(&session).symbols.iter().find(|definition| definition.name == copied_outer).unwrap().art; + let copied_inner = only_symbol_name(outer_art); + assert_ne!(copied_inner, inner, "the child follows its aliased composite-font meaning"); + let copied_pattern = (dependency == 1).then(|| pattern_in_symbol(document(&session), &copied_inner)); + let copied_brush = (dependency == 2).then(|| brush_in_symbol(document(&session), &copied_inner)); + let family = if let Some(pattern) = &copied_pattern { + assert_ne!(pattern.as_str(), pattern_name, "the pattern also gets a new meaning under the font alias"); + pattern_font_family(document(&session), pattern) + } else if let Some(brush) = &copied_brush { + assert_ne!(brush.as_str(), brush_name, "the stored brush gets its own aliased font meaning"); + brush_font_family(document(&session), brush) + } else { + symbol_font_family(document(&session), &copied_inner) + }; + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let definition = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&definition.parts, &definition.custom), (&incoming.parts, &incoming.custom)); + let imported_options = Clipboard::from_document(document(&session)).symbol_options; + assert_eq!(imported_options.get(&copied_inner), source_options.get(inner)); + assert_eq!(imported_options.get(&copied_outer), source_options.get(outer), "indirect parent copies keep all five option fields"); + assert_eq!(imported_options.get(inner), source_options.get(inner)); + assert_eq!(imported_options.get(outer), source_options.get(outer)); + assert_original_native_art(document(&session), &before); + assert_eq!(document(&session).symbols.len(), before.symbols.len() + 2); + + let first_symbols = document(&session).symbols.clone(); + let first_fonts = document(&session).composite_fonts.clone(); + let first_resources = native_resource_counts(document(&session)); + let first_brushes = vectorcraft_brush::library(document(&session)); + let repeated = place(&mut session, &path, linked); + let repeated_outer = only_symbol_name(document(&session).node(repeated).unwrap()); + let repeated_art = &document(&session).symbols.iter().find(|definition| definition.name == repeated_outer).unwrap().art; + assert_eq!(repeated_outer, copied_outer); + assert_eq!(only_symbol_name(repeated_art), copied_inner, "repeat also reuses the actual mapped child name"); + if let Some(pattern) = &copied_pattern { + assert_eq!(pattern_in_symbol(document(&session), &copied_inner), *pattern); + assert_eq!(pattern_font_family(document(&session), pattern), family); + } else if let Some(brush) = &copied_brush { + assert_eq!(brush_in_symbol(document(&session), &copied_inner), *brush); + assert_eq!(brush_font_family(document(&session), brush), family); + } else { + assert_eq!(symbol_font_family(document(&session), &copied_inner), family); + } + assert_eq!(native_resource_counts(document(&session)), first_resources); + assert_eq!(document(&session).symbols, first_symbols); + assert_eq!(document(&session).composite_fonts, first_fonts); + assert_eq!(vectorcraft_brush::library(document(&session)), first_brushes); + assert_original_native_art(document(&session), &before); + } + } +} + +#[test] +fn native_composite_async_replace_is_independent_of_an_unrelated_live_tool_drag() { + use vectorcraft_geom::Rect; + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-drag"); + let path = dir.join("replacement.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionDrag", "Source Sans 3", "Regular"); + write_native(&path, &font_document(&incoming)); + let view = vectorcraft_engine::ViewInfo { smart_guides: false, ..Default::default() }; + for cancel in [true, false] { + let mut session = Session::new(); + session.prefs.real_time_drawing = true; + session.add_document(Document::new(400.0, 400.0), None); + let a = session.execute("shape.rectangle", &json!({"x":10,"y":10,"width":20,"height":20})).unwrap(); + let a = NodeId(a["id"].as_u64().unwrap()); + let b = session.execute("shape.rectangle", &json!({"x":100,"y":100,"width":40,"height":40})).unwrap(); + let b = NodeId(b["id"].as_u64().unwrap()); + let old_a = document(&session).node(a).unwrap().clone(); + let old_b = document(&session).node(b).unwrap().clone(); + session.execute("select.set", &json!({"ids":[a.0]})).unwrap(); + let read = session.prepare_place(&json!({"path":path,"link":false,"replace":true})).unwrap().read().unwrap(); + session.execute("select.set", &json!({"ids":[b.0]})).unwrap(); + session.select_tool("selection", view).unwrap(); + let steps = session.doc().unwrap().history.undo.len(); + session.pointer(&PointerEvent::new(PointerKind::Down,120.0,120.0),view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Drag,140.0,130.0),view).unwrap(); + assert!(session.in_interaction(), "CONTROL: actual selection-tool pointer actions began a drag"); + assert_eq!(session.tool_id(), "selection"); + assert_eq!(session.doc().unwrap().selection.objects, vec![b]); + assert_eq!(document(&session).bounds_of(&[b],false), Some(Rect::new(120.0,110.0,160.0,150.0))); + assert_eq!(session.doc().unwrap().history.undo.len(), steps, "CONTROL: this is still an uncommitted tool preview"); + + let reply = session.place_read(read).expect("CONTROL: the native replacement succeeds while a different object is dragged"); + let replacement = NodeId(reply["ids"][0].as_u64().unwrap()); + let published = document(&session).node(replacement).unwrap().clone(); + let completed_steps = session.doc().unwrap().history.undo.len(); + assert_ne!(document(&session).node(a), Some(&old_a)); + assert!(session.in_interaction(), "the unrelated tool drag remains live after external completion"); + session.pointer(&PointerEvent::new(PointerKind::Drag,170.0,150.0),view).unwrap(); + if cancel { + session.tool_key(ToolKey::Escape,Mods::default(),view).unwrap(); + } + session.pointer(&PointerEvent::new(PointerKind::Up,170.0,150.0),view).unwrap(); + assert!(!session.in_interaction()); + assert_eq!(document(&session).node(replacement), Some(&published), "cancel/release of B must keep the published replacement of A"); + assert_eq!(completed_steps, steps + 1, "the completion has its own undo step before the drag ends"); + if cancel { + assert_eq!(document(&session).node(b), Some(&old_b)); + assert_eq!(session.doc().unwrap().history.undo.len(), steps + 1); + } else { + assert_eq!(document(&session).bounds_of(&[b],false), Some(Rect::new(150.0,130.0,190.0,170.0))); + assert_eq!(session.doc().unwrap().history.undo.len(), steps + 2, "commit creates a separate drag step"); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(document(&session).node(b), Some(&old_b)); + assert_eq!(document(&session).node(replacement), Some(&published), "first Undo removes only the drag"); + } + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(document(&session).node(a), Some(&old_a), "the next Undo independently restores the replaced target"); + assert_ne!(document(&session).node(replacement), Some(&published), "Undo removes the replacement meaning even if an id is reused"); + assert_eq!(document(&session).node(b), Some(&old_b)); } } From d2084be08df1cc1b896441c05dbf8f74c32fdf1f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 17:43:41 -0800 Subject: [PATCH 07/18] fix: preserve native resource reuse and external placement isolation --- crates/engine/src/cmd/place.rs | 22 ++- crates/engine/src/cmd/place/adopt.rs | 261 +++++++++++++++++++++++---- crates/engine/src/session/execute.rs | 11 +- 3 files changed, 252 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 50aeb9414d..09116b69f5 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -763,15 +763,27 @@ impl Session { if self.doc()?.uid != read.job.doc { return Err(bad(PLACE, NOT_ACTIVE)); } + if let Some(old) = read.job.old { + // Keep the asynchronous target check against the drawing currently on show. + if self.doc()?.doc.node(old) != read.job.replaced.as_ref() { + return Err(bad(PLACE, "replace: the object to replace was changed or deleted")); + } + } let params = read.job.params.clone(); + // Provisional reselection and placement are one outside command. Deferring their + // notifications must not make an asynchronous handoff part of an unrelated tool drag. + if self.depth == 0 && !self.previewing && !self.in_tool_actions { + self.command_with_settled_warnings(|s| s.outside_interaction(PLACE, ¶ms, |s| s.place_read_handoff(read, ¶ms))) + } else { + self.place_read_handoff(read, ¶ms) + } + } + + fn place_read_handoff(&mut self, read: PlaceRead, params: &Value) -> Result { let mut rollback = None; let mut reselect = None; if let Some(old) = read.job.old { let st = self.doc()?; - // Retain the existing asynchronous target checks unchanged. - if st.doc.node(old) != read.job.replaced.as_ref() { - return Err(bad(PLACE, "replace: the object to replace was changed or deleted")); - } if st.selection.objects != [old] || st.selection.symbol_part.is_some() { // Adoption may now fail. Its provisional selection must not escape that error. rollback = Some(( @@ -798,7 +810,7 @@ impl Session { self.execute("select.set", &json!({ "ids": [old.0] }))?; } self.place_hand_off = Some(read); - self.execute(PLACE, ¶ms) + self.execute(PLACE, params) })(); self.place_hand_off = None; if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback { diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 4a92e808ee..36c67a2ba2 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -223,40 +223,247 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> { } } +/// Apply the final resource-name plan to one incoming reference. +fn rename_ref(r: Ref<'_>, maps: [&Renames; 5]) { + let (map, key) = match r { + Ref::Image(key) => (maps[0], key), + Ref::Symbol(key) => (maps[1], key), + Ref::Pattern(key) => (maps[2], key), + Ref::Brush(key) => (maps[3], key), + Ref::Swatch(link) => { + if let Some((new, _)) = link.as_deref().and_then(|key| maps[4].get(key)) { + *link = new.clone(); + } + return; + } + }; + if let Some((Some(new), _)) = map.get(key.as_str()) { + *key = new.clone(); + } +} + +#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] +enum ResourceKind { + Symbol, + Pattern, + Brush, +} + +type ResourceKey = (ResourceKind, String); + +/// A source definition's dependencies whose planned names have not been finalized yet. +fn pending_dependencies( + key: &ResourceKey, + src: &Document, + brushes: &[Brush], + pending: &BTreeSet, +) -> BTreeSet { + let mut dependencies = BTreeSet::new(); + let mut note = |r: Ref<'_>| { + let key = match r { + Ref::Symbol(name) => (ResourceKind::Symbol, name.clone()), + Ref::Pattern(name) => (ResourceKind::Pattern, name.clone()), + Ref::Brush(name) => (ResourceKind::Brush, name.clone()), + Ref::Image(_) | Ref::Swatch(_) => return, + }; + if pending.contains(&key) { + dependencies.insert(key); + } + }; + match key.0 { + ResourceKind::Symbol => { + if let Some(symbol) = src.symbols.iter().find(|symbol| symbol.name == key.1) { + refs(&mut (*symbol.art).clone(), &mut note); + } + } + ResourceKind::Pattern => { + if let Some(pattern) = src.pattern(&key.1) { + for art in &pattern.art { + refs(&mut (**art).clone(), &mut note); + } + } + } + ResourceKind::Brush => { + if let Some(mut brush) = brushes.iter().find(|brush| brush.name == key.1).cloned() { + for art in brush_art(&mut brush) { + refs(art, &mut note); + } + } + } + } + dependencies +} + +/// Prefer the original name, then only canonical numbered variants from `unique_name`. +/// A free original name keeps its planned copy; another incoming name is never stolen. +fn matching_name( + base: &str, + definitions: &[T], + used: &[String], + name: impl Fn(&T) -> &str, + same: impl Fn(&T) -> bool, +) -> Option { + let original = definitions.iter().find(|definition| name(definition) == base)?; + if same(original) { + return Some(base.to_string()); + } + let prefix = format!("{base} "); + let mut seen = BTreeSet::new(); + let mut aliases: Vec<_> = definitions + .iter() + .filter_map(|definition| { + let candidate = name(definition); + // Match the first definition, as the document name lookups do. + if !seen.insert(candidate.to_string()) { + return None; + } + let suffix = candidate.strip_prefix(&prefix)?; + if suffix.starts_with('0') || !suffix.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let number = suffix.parse::().ok()?; + (number >= 2 && !used.iter().any(|used| used == candidate)).then_some((number, definition)) + }) + .collect(); + aliases.sort_unstable_by_key(|(number, _)| *number); + aliases.into_iter().find_map(|(_, definition)| same(definition).then(|| name(definition).to_string())) +} + +/// Compare final incoming content, not the original references or destination's resource name. +fn reusable_name( + key: &ResourceKey, + dst: &Document, + src: &Document, + src_brushes: &[Brush], + dst_brushes: &[Brush], + used: &Used, + maps: [&Renames; 5], +) -> Option { + match key.0 { + ResourceKind::Symbol => { + let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?; + let mut incoming = source.clone(); + refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps)); + matching_name(&key.1, &dst.symbols, &used.symbols, |symbol| &symbol.name, |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + same_symbol(dst, &normalized, &incoming) + && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name) + }) + } + ResourceKind::Pattern => { + let mut incoming = src.pattern(&key.1)?.clone(); + for art in &mut incoming.art { + refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps)); + } + matching_name(&key.1, &dst.patterns, &used.patterns, |pattern| &pattern.name, |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + same_pattern(dst, &normalized, &incoming) + }) + } + ResourceKind::Brush => { + let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone(); + for art in brush_art(&mut incoming) { + refs(art, &mut |r| rename_ref(r, maps)); + *art = canon(dst, art); + } + matching_name(&key.1, dst_brushes, &used.brushes, |brush| &brush.name, |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + for art in brush_art(&mut normalized) { + *art = canon(dst, art); + } + normalized == incoming + }) + } + } +} + +/// Finalize each copied definition only after its copied dependencies. Each key/edge is +/// processed once; a cycle (and its unresolved parents) conservatively keeps the planned copies. +fn reuse_remapped_resources( + dst: &Document, + src: &Document, + src_brushes: &[Brush], + dst_brushes: &[Brush], + used: &Used, + fixed: [&Renames; 2], + changing: [&mut Renames; 3], +) { + let [symbols, patterns, brushes] = changing; + let mut pending = BTreeSet::new(); + for (kind, map) in [ + (ResourceKind::Symbol, &*symbols), + (ResourceKind::Pattern, &*patterns), + (ResourceKind::Brush, &*brushes), + ] { + pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone()))); + } + let mut waiting = BTreeMap::new(); + let mut parents: BTreeMap> = BTreeMap::new(); + let mut ready = BTreeSet::new(); + for key in &pending { + let dependencies = pending_dependencies(key, src, src_brushes, &pending); + if dependencies.is_empty() { + ready.insert(key.clone()); + } + waiting.insert(key.clone(), dependencies.len()); + for dependency in dependencies { + parents.entry(dependency).or_default().push(key.clone()); + } + } + while let Some(key) = ready.pop_first() { + let maps = [fixed[0], &*symbols, &*patterns, &*brushes, fixed[1]]; + if let Some(name) = reusable_name(&key, dst, src, src_brushes, dst_brushes, used, maps) { + let map = match key.0 { + ResourceKind::Symbol => &mut *symbols, + ResourceKind::Pattern => &mut *patterns, + ResourceKind::Brush => &mut *brushes, + }; + map.insert(key.1.clone(), (Some(name), false)); + } + for parent in parents.remove(&key).into_iter().flatten() { + if let Some(count) = waiting.get_mut(&parent) { + *count -= 1; + if *count == 0 { + ready.insert(parent); + } + } + } + } +} + /// Remap only incoming users before resource equality decides whether to share or copy. -/// A symbol whose new font alias forces a copy keeps its existing pixel/export options. +/// Report actual family renaming so only that case needs the alias reuse phase. fn remap_composite_families( src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport, -) -> (Document, BTreeSet) { +) -> (Document, bool) { let mut staged = src.clone(); + let mut aliased = false; for node in nodes.iter_mut() { each_mut(node, &mut |node| { node_families(node, &mut |family| { - plan.rename(family); + aliased |= plan.rename(family); }); }); } - let mut changed_symbols = BTreeSet::new(); for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) { - let mut changed = false; each_mut(Arc::make_mut(&mut symbol.art), &mut |node| { node_families(node, &mut |family| { - changed |= plan.rename(family); + aliased |= plan.rename(family); }); }); - if changed { - changed_symbols.insert(symbol.name.clone()); - } } for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) { for art in &mut pattern.art { each_mut(Arc::make_mut(art), &mut |node| { node_families(node, &mut |family| { - plan.rename(family); + aliased |= plan.rename(family); }); }); } @@ -265,12 +472,12 @@ fn remap_composite_families( for art in brush_art(brush) { each_mut(art, &mut |node| { node_families(node, &mut |family| { - plan.rename(family); + aliased |= plan.rename(family); }); }); } } - (staged, changed_symbols) + (staged, aliased) } /// Discover the incoming resource frontier and its composite-font users before planning @@ -331,9 +538,9 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: // All representability/validation errors precede incoming or destination mutation. let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) }; let staged; - let mut changed_symbols = BTreeSet::new(); + let mut aliased = false; let src = if let Some(plan) = &plan { - (staged, changed_symbols) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan); + (staged, aliased) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan); &staged } else { src @@ -412,26 +619,14 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c)); } + if aliased { + reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]); + } + if let Some(plan) = plan { dst.composite_fonts = plan.combined.into(); } - let mut rename = |r: Ref| { - let (map, k) = match r { - Ref::Image(k) => (&images, k), - Ref::Symbol(k) => (&symbols, k), - Ref::Pattern(k) => (&patterns, k), - Ref::Brush(k) => (&brushes, k), - Ref::Swatch(link) => { - if let Some((new, _)) = link.as_deref().and_then(|k| swatches.get(k)) { - *link = new.clone(); - } - return; - } - }; - if let Some((Some(new), _)) = map.get(k.as_str()) { - *k = new.clone(); - } - }; + let mut rename = |r: Ref| rename_ref(r, [&images, &symbols, &patterns, &brushes, &swatches]); for n in nodes.iter_mut() { refs(n, &mut rename); } @@ -460,9 +655,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: // The art takes ids of `dst`: those of `src` may name objects of `dst` already. def.art = Arc::new(dst.reid(&def.art)); dst.symbols.push(def); - if changed_symbols.contains(old) { - SymbolOptions::of(src, old).give(dst, new); - } + SymbolOptions::of(src, old).give(dst, new); } } for (old, new) in copies(&patterns) { diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index a7e0593d42..4335b78b73 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -25,6 +25,12 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value { } impl Session { + /// Run a command callback and keep warnings from every preview it settles or restores. + pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result) -> Result { + let (r, settled) = self.collect_settled_warnings(f); + r.map(|v| with_settled_warnings(v, &settled)) + } + /// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back. fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec) -> std::result::Result<(), String> { let Some(d) = self.active_mut() else { return (spec.enabled)(self) }; @@ -121,10 +127,9 @@ impl Session { // A preview that a top-level command applied first (a drag with Real-time Drawing off, kept // before Undo) reports its warning in the command's result. let r = if self.depth == 0 { - let (r, settled) = self.collect_settled_warnings(|s| { + self.command_with_settled_warnings(|s| { if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) } - }); - r.map(|v| with_settled_warnings(v, &settled)) + }) } else { self.execute_spec(spec, id, params) }; From 257be57cb9b0832635cac7a60324a351d6680021 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 17:56:26 -0800 Subject: [PATCH 08/18] style: format native composite adoption and controls --- crates/engine/src/cmd/place/adopt.rs | 84 +++++++++---------- .../engine/tests/native_composite_adoption.rs | 62 +++++++++----- 2 files changed, 80 insertions(+), 66 deletions(-) diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 36c67a2ba2..21834dac34 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -252,12 +252,7 @@ enum ResourceKind { type ResourceKey = (ResourceKind, String); /// A source definition's dependencies whose planned names have not been finalized yet. -fn pending_dependencies( - key: &ResourceKey, - src: &Document, - brushes: &[Brush], - pending: &BTreeSet, -) -> BTreeSet { +fn pending_dependencies(key: &ResourceKey, src: &Document, brushes: &[Brush], pending: &BTreeSet) -> BTreeSet { let mut dependencies = BTreeSet::new(); let mut note = |r: Ref<'_>| { let key = match r { @@ -296,13 +291,7 @@ fn pending_dependencies( /// Prefer the original name, then only canonical numbered variants from `unique_name`. /// A free original name keeps its planned copy; another incoming name is never stolen. -fn matching_name( - base: &str, - definitions: &[T], - used: &[String], - name: impl Fn(&T) -> &str, - same: impl Fn(&T) -> bool, -) -> Option { +fn matching_name(base: &str, definitions: &[T], used: &[String], name: impl Fn(&T) -> &str, same: impl Fn(&T) -> bool) -> Option { let original = definitions.iter().find(|definition| name(definition) == base)?; if same(original) { return Some(base.to_string()); @@ -344,23 +333,34 @@ fn reusable_name( let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?; let mut incoming = source.clone(); refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps)); - matching_name(&key.1, &dst.symbols, &used.symbols, |symbol| &symbol.name, |candidate| { - let mut normalized = candidate.clone(); - normalized.name = incoming.name.clone(); - same_symbol(dst, &normalized, &incoming) - && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name) - }) + matching_name( + &key.1, + &dst.symbols, + &used.symbols, + |symbol| &symbol.name, + |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + same_symbol(dst, &normalized, &incoming) && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name) + }, + ) } ResourceKind::Pattern => { let mut incoming = src.pattern(&key.1)?.clone(); for art in &mut incoming.art { refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps)); } - matching_name(&key.1, &dst.patterns, &used.patterns, |pattern| &pattern.name, |candidate| { - let mut normalized = candidate.clone(); - normalized.name = incoming.name.clone(); - same_pattern(dst, &normalized, &incoming) - }) + matching_name( + &key.1, + &dst.patterns, + &used.patterns, + |pattern| &pattern.name, + |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + same_pattern(dst, &normalized, &incoming) + }, + ) } ResourceKind::Brush => { let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone(); @@ -368,14 +368,20 @@ fn reusable_name( refs(art, &mut |r| rename_ref(r, maps)); *art = canon(dst, art); } - matching_name(&key.1, dst_brushes, &used.brushes, |brush| &brush.name, |candidate| { - let mut normalized = candidate.clone(); - normalized.name = incoming.name.clone(); - for art in brush_art(&mut normalized) { - *art = canon(dst, art); - } - normalized == incoming - }) + matching_name( + &key.1, + dst_brushes, + &used.brushes, + |brush| &brush.name, + |candidate| { + let mut normalized = candidate.clone(); + normalized.name = incoming.name.clone(); + for art in brush_art(&mut normalized) { + *art = canon(dst, art); + } + normalized == incoming + }, + ) } } } @@ -393,11 +399,7 @@ fn reuse_remapped_resources( ) { let [symbols, patterns, brushes] = changing; let mut pending = BTreeSet::new(); - for (kind, map) in [ - (ResourceKind::Symbol, &*symbols), - (ResourceKind::Pattern, &*patterns), - (ResourceKind::Brush, &*brushes), - ] { + for (kind, map) in [(ResourceKind::Symbol, &*symbols), (ResourceKind::Pattern, &*patterns), (ResourceKind::Brush, &*brushes)] { pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone()))); } let mut waiting = BTreeMap::new(); @@ -436,13 +438,7 @@ fn reuse_remapped_resources( /// Remap only incoming users before resource equality decides whether to share or copy. /// Report actual family renaming so only that case needs the alias reuse phase. -fn remap_composite_families( - src: &Document, - nodes: &mut [Node], - used: &Used, - brushes: &mut [Brush], - plan: &CompositeImport, -) -> (Document, bool) { +fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) { let mut staged = src.clone(); let mut aliased = false; for node in nodes.iter_mut() { diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 932595a584..42fd895995 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -617,8 +617,13 @@ fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() if dependency == 1 { builder.execute("object.pattern.make", &json!({"ids":[text_id.unwrap().0],"name":pattern_name,"edit":false})).unwrap(); } else { - builder.execute("brush.new", &json!({"type":"art","name":brush_name,"ids":[text_id.unwrap().0], - "params":{"width":137.0}})).unwrap(); + builder + .execute( + "brush.new", + &json!({"type":"art","name":brush_name,"ids":[text_id.unwrap().0], + "params":{"width":137.0}}), + ) + .unwrap(); } let mut doc = document(&builder).clone(); doc.remove(text_id.unwrap()).unwrap(); @@ -626,12 +631,15 @@ fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() let appearance = if dependency == 1 { vectorcraft_doc::Appearance::basic(vectorcraft_doc::pattern::pattern_paint(pattern_name), vectorcraft_color::Paint::None, 0.0) } else { - let mut appearance = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, - vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0); + let mut appearance = vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::None, + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + 1.0, + ); appearance.stroke_mut().unwrap().brush = Some(brush_name.into()); appearance }; - let rectangle = Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0,0.0,20.0,20.0)), appearance); + let rectangle = Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 20.0)), appearance); std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(rectangle)); doc.fix_next_id(); builder = Session::new(); @@ -640,19 +648,29 @@ fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() } let inner = "NativeAdoptionInner"; let outer = "NativeAdoptionOuter"; - let made = builder.execute("symbol.new", &json!({ - "name": inner, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", - "nineSlice": true, "nineSliceGuides": [0.2,0.3,0.25,0.15], "alignToPixelGrid": true - })).unwrap(); - builder.execute("symbol.new", &json!({ - "name": outer, "ids": [made["id"]], "registration": 8, "exportType": "graphic", - "nineSlice": true, "nineSliceGuides": [0.1,0.2,0.3,0.25], "alignToPixelGrid": true - })).unwrap(); + let made = builder + .execute( + "symbol.new", + &json!({ + "name": inner, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2,0.3,0.25,0.15], "alignToPixelGrid": true + }), + ) + .unwrap(); + builder + .execute( + "symbol.new", + &json!({ + "name": outer, "ids": [made["id"]], "registration": 8, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.1,0.2,0.3,0.25], "alignToPixelGrid": true + }), + ) + .unwrap(); let source = write_native(&path, document(&builder)); let source_options = Clipboard::from_document(&source).symbol_options; for (name, registration, guides) in [ - (inner, 0, vectorcraft_doc::SymbolNineSlice::new(0.2,0.3,0.25,0.15)), - (outer, 8, vectorcraft_doc::SymbolNineSlice::new(0.1,0.2,0.3,0.25)), + (inner, 0, vectorcraft_doc::SymbolNineSlice::new(0.2, 0.3, 0.25, 0.15)), + (outer, 8, vectorcraft_doc::SymbolNineSlice::new(0.1, 0.2, 0.3, 0.25)), ] { let options = source_options.get(name).unwrap(); assert!(options.size.is_some()); @@ -750,12 +768,12 @@ fn native_composite_async_replace_is_independent_of_an_unrelated_live_tool_drag( session.execute("select.set", &json!({"ids":[b.0]})).unwrap(); session.select_tool("selection", view).unwrap(); let steps = session.doc().unwrap().history.undo.len(); - session.pointer(&PointerEvent::new(PointerKind::Down,120.0,120.0),view).unwrap(); - session.pointer(&PointerEvent::new(PointerKind::Drag,140.0,130.0),view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 120.0), view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 130.0), view).unwrap(); assert!(session.in_interaction(), "CONTROL: actual selection-tool pointer actions began a drag"); assert_eq!(session.tool_id(), "selection"); assert_eq!(session.doc().unwrap().selection.objects, vec![b]); - assert_eq!(document(&session).bounds_of(&[b],false), Some(Rect::new(120.0,110.0,160.0,150.0))); + assert_eq!(document(&session).bounds_of(&[b], false), Some(Rect::new(120.0, 110.0, 160.0, 150.0))); assert_eq!(session.doc().unwrap().history.undo.len(), steps, "CONTROL: this is still an uncommitted tool preview"); let reply = session.place_read(read).expect("CONTROL: the native replacement succeeds while a different object is dragged"); @@ -764,11 +782,11 @@ fn native_composite_async_replace_is_independent_of_an_unrelated_live_tool_drag( let completed_steps = session.doc().unwrap().history.undo.len(); assert_ne!(document(&session).node(a), Some(&old_a)); assert!(session.in_interaction(), "the unrelated tool drag remains live after external completion"); - session.pointer(&PointerEvent::new(PointerKind::Drag,170.0,150.0),view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Drag, 170.0, 150.0), view).unwrap(); if cancel { - session.tool_key(ToolKey::Escape,Mods::default(),view).unwrap(); + session.tool_key(ToolKey::Escape, Mods::default(), view).unwrap(); } - session.pointer(&PointerEvent::new(PointerKind::Up,170.0,150.0),view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0), view).unwrap(); assert!(!session.in_interaction()); assert_eq!(document(&session).node(replacement), Some(&published), "cancel/release of B must keep the published replacement of A"); assert_eq!(completed_steps, steps + 1, "the completion has its own undo step before the drag ends"); @@ -776,7 +794,7 @@ fn native_composite_async_replace_is_independent_of_an_unrelated_live_tool_drag( assert_eq!(document(&session).node(b), Some(&old_b)); assert_eq!(session.doc().unwrap().history.undo.len(), steps + 1); } else { - assert_eq!(document(&session).bounds_of(&[b],false), Some(Rect::new(150.0,130.0,190.0,170.0))); + assert_eq!(document(&session).bounds_of(&[b], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0))); assert_eq!(session.doc().unwrap().history.undo.len(), steps + 2, "commit creates a separate drag step"); session.execute("edit.undo", &json!({})).unwrap(); assert_eq!(document(&session).node(b), Some(&old_b)); From 39adcb3ad1836bef6f463f9bef89923c95b4da08 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 18:23:52 -0800 Subject: [PATCH 09/18] fix: compare native symbol metadata before sharing --- crates/engine/src/cmd/place/adopt.rs | 2 +- .../engine/tests/native_composite_adoption.rs | 245 +++++++++++++----- 2 files changed, 174 insertions(+), 73 deletions(-) diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 21834dac34..dd10f08266 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -549,7 +549,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &used.symbols, |n| src.symbols.iter().find(|s| s.name == n), |n| dst.symbols.iter().find(|s| s.name == n), - |a, b| same_symbol(dst, a, b), + |a, b| same_symbol(dst, a, b) && SymbolOptions::of(dst, &a.name) == SymbolOptions::of(src, &b.name), |c| dst.symbols.iter().any(|s| s.name == c), ); let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some()); diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 42fd895995..cf26e9280e 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -213,17 +213,13 @@ fn native_composite_limit_errors_are_atomic_for_place_embed_and_async_replace() .collect(); for linked in [false, true] { let mut session = destination(&full); - let command; - let params; - if linked { + let (command, params) = if linked { let placed = session.execute("file.place", &json!({"path": path, "link": true})).unwrap(); assert_eq!(placed["linked"], true); - command = "links.embed"; - params = json!({"ids": placed["ids"]}); + ("links.embed", json!({"ids": placed["ids"]})) } else { - command = "file.place"; - params = json!({"path": path, "link": false}); - } + ("file.place", json!({"path": path, "link": false})) + }; let before = snapshot(&session); let registry = registered_fonts(); let error = session.execute(command, ¶ms).expect_err("REGRESSION: the prospective document exceeds its real composite-font cap"); @@ -594,6 +590,80 @@ fn brush_font_family(doc: &Document, name: &str) -> String { names.pop().unwrap() } +const NESTED_INNER: &str = "NativeAdoptionInner"; +const NESTED_OUTER: &str = "NativeAdoptionOuter"; +const NESTED_PATTERN: &str = "NativeAdoptionPatternText"; +const NESTED_BRUSH: &str = "NativeAdoptionBrushText"; + +// Build the same nested native artifact for each direct, pattern-backed or brush-backed case. +fn nested_native_source(path: &std::path::Path, incoming: &CompositeFont, dependency: usize) -> (Session, Document) { + let inner = NESTED_INNER; + let outer = NESTED_OUTER; + let mut builder = Session::new(); + builder.add_document(font_document(incoming), None); + let mut text_id = None; + document(&builder).layers[0].walk(&mut |node| { + if matches!(&node.kind, NodeKind::Text(_)) { + assert!(text_id.replace(node.id).is_none()); + } + }); + let pattern_name = NESTED_PATTERN; + let brush_name = NESTED_BRUSH; + if dependency != 0 { + if dependency == 1 { + builder.execute("object.pattern.make", &json!({"ids":[text_id.unwrap().0],"name":pattern_name,"edit":false})).unwrap(); + } else { + builder + .execute( + "brush.new", + &json!({"type":"art","name":brush_name,"ids":[text_id.unwrap().0], + "params":{"width":137.0}}), + ) + .unwrap(); + } + let mut doc = document(&builder).clone(); + doc.remove(text_id.unwrap()).unwrap(); + let id = doc.alloc_id(); + let appearance = if dependency == 1 { + vectorcraft_doc::Appearance::basic(vectorcraft_doc::pattern::pattern_paint(pattern_name), vectorcraft_color::Paint::None, 0.0) + } else { + let mut appearance = vectorcraft_doc::Appearance::basic( + vectorcraft_color::Paint::None, + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), + 1.0, + ); + appearance.stroke_mut().unwrap().brush = Some(brush_name.into()); + appearance + }; + let rectangle = Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 20.0)), appearance); + std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(rectangle)); + doc.fix_next_id(); + builder = Session::new(); + builder.add_document(doc, None); + text_id = Some(id); + } + let made = builder + .execute( + "symbol.new", + &json!({ + "name": inner, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2,0.3,0.25,0.15], "alignToPixelGrid": true + }), + ) + .unwrap(); + builder + .execute( + "symbol.new", + &json!({ + "name": outer, "ids": [made["id"]], "registration": 8, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.1,0.2,0.3,0.25], "alignToPixelGrid": true + }), + ) + .unwrap(); + let source = write_native(path, document(&builder)); + (builder, source) +} + #[test] fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() { use vectorcraft_engine::cmd::clipboard::Clipboard; @@ -603,70 +673,11 @@ fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() let incoming = CompositeFont::new("NativeAdoptionNestedFont", "Source Sans 3", "Regular"); for dependency in 0..3 { let path = dir.join(format!("nested-lettering-{dependency}.vectorcraft")); - let mut builder = Session::new(); - builder.add_document(font_document(&incoming), None); - let mut text_id = None; - document(&builder).layers[0].walk(&mut |node| { - if matches!(&node.kind, NodeKind::Text(_)) { - assert!(text_id.replace(node.id).is_none()); - } - }); - let pattern_name = "NativeAdoptionPatternText"; - let brush_name = "NativeAdoptionBrushText"; - if dependency != 0 { - if dependency == 1 { - builder.execute("object.pattern.make", &json!({"ids":[text_id.unwrap().0],"name":pattern_name,"edit":false})).unwrap(); - } else { - builder - .execute( - "brush.new", - &json!({"type":"art","name":brush_name,"ids":[text_id.unwrap().0], - "params":{"width":137.0}}), - ) - .unwrap(); - } - let mut doc = document(&builder).clone(); - doc.remove(text_id.unwrap()).unwrap(); - let id = doc.alloc_id(); - let appearance = if dependency == 1 { - vectorcraft_doc::Appearance::basic(vectorcraft_doc::pattern::pattern_paint(pattern_name), vectorcraft_color::Paint::None, 0.0) - } else { - let mut appearance = vectorcraft_doc::Appearance::basic( - vectorcraft_color::Paint::None, - vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), - 1.0, - ); - appearance.stroke_mut().unwrap().brush = Some(brush_name.into()); - appearance - }; - let rectangle = Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 20.0)), appearance); - std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(rectangle)); - doc.fix_next_id(); - builder = Session::new(); - builder.add_document(doc, None); - text_id = Some(id); - } - let inner = "NativeAdoptionInner"; - let outer = "NativeAdoptionOuter"; - let made = builder - .execute( - "symbol.new", - &json!({ - "name": inner, "ids": [text_id.unwrap().0], "registration": 0, "exportType": "graphic", - "nineSlice": true, "nineSliceGuides": [0.2,0.3,0.25,0.15], "alignToPixelGrid": true - }), - ) - .unwrap(); - builder - .execute( - "symbol.new", - &json!({ - "name": outer, "ids": [made["id"]], "registration": 8, "exportType": "graphic", - "nineSlice": true, "nineSliceGuides": [0.1,0.2,0.3,0.25], "alignToPixelGrid": true - }), - ) - .unwrap(); - let source = write_native(&path, document(&builder)); + let inner = NESTED_INNER; + let outer = NESTED_OUTER; + let pattern_name = NESTED_PATTERN; + let brush_name = NESTED_BRUSH; + let (_builder, source) = nested_native_source(&path, &incoming, dependency); let source_options = Clipboard::from_document(&source).symbol_options; for (name, registration, guides) in [ (inner, 0, vectorcraft_doc::SymbolNineSlice::new(0.2, 0.3, 0.25, 0.15)), @@ -806,3 +817,93 @@ fn native_composite_async_replace_is_independent_of_an_unrelated_live_tool_drag( assert_eq!(document(&session).node(b), Some(&old_b)); } } + +#[test] +fn native_composite_mapped_symbol_art_shares_only_matching_options() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-composite-mapped-options"); + let path = dir.join("mapped-options.vectorcraft"); + let incoming = CompositeFont::new("NativeAdoptionMappedOptions", "Source Sans 3", "Regular"); + let mut builder = Session::new(); + builder.add_document(font_document(&incoming), None); + let children = document(&builder).layers[0].children().unwrap(); + assert_eq!(children.len(), 1, "CONTROL: the one source lettering object"); + let text_id = children[0].id; + let symbol = "NativeAdoptionMappedOptionsSymbol"; + builder + .execute( + "symbol.new", + &json!({ + "name": symbol, "ids": [text_id.0], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true + }), + ) + .unwrap(); + let source = write_native(&path, document(&builder)); + let source_options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); + for linked in [false, true] { + let mut target = source.clone(); + let font = target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); + font.parts.roman.size = 125.0; + let mut seed = Session::new(); + seed.add_document(target, None); + let first = place(&mut seed, &path, linked); + let alias_symbol = only_symbol_name(document(&seed).node(first).unwrap()); + let alias_family = symbol_font_family(document(&seed), &alias_symbol); + assert_ne!(alias_symbol, symbol); + assert!(!CompositeFont::same_name(&alias_family, &incoming.name)); + for matching_options in [false, true] { + let mut target = document(&seed).clone(); + let definition = target.symbols.iter_mut().find(|definition| definition.name == symbol).unwrap(); + // The original-name art now already uses the equivalent font selected by the import. + std::sync::Arc::make_mut(&mut definition.art).walk_mut(&mut |node| { + if let NodeKind::Text(text) = &mut node.kind { + for run in &mut text.runs { + if CompositeFont::same_name(&run.style.font_family, &incoming.name) { + run.style.font_family = alias_family.clone(); + } + } + } + }); + assert_eq!(symbol_font_family(&target, symbol), alias_family); + if !matching_options { + // Public document storage keeps natural size separately from the symbol's art. + target.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).unwrap().as_object_mut().unwrap().remove(symbol); + target.set_symbol_registration(symbol, vectorcraft_doc::SymbolRegistration(8)); + target.set_symbol_export_type(symbol, vectorcraft_doc::SymbolExportType::default()); + target.set_symbol_nine_slice(symbol, None); + target.set_symbol_pixel_aligned(symbol, false); + } + let held_options = Clipboard::from_document(&target).symbol_options.get(symbol).unwrap().clone(); + if matching_options { + assert_eq!(held_options, source_options, "CONTROL: equal art and options may still share the original name"); + } else { + assert_ne!(held_options.size, source_options.size); + assert_ne!(held_options.registration, source_options.registration); + assert_ne!(held_options.export_type, source_options.export_type); + assert_ne!(held_options.nine_slice, source_options.nine_slice); + assert_ne!(held_options.pixel_aligned, source_options.pixel_aligned); + } + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let resources = native_resource_counts(&before); + let id = place(&mut session, &path, linked); + let imported = only_symbol_name(document(&session).node(id).unwrap()); + let expected = if matching_options { symbol } else { alias_symbol.as_str() }; + assert_eq!(imported, expected, "matching art must not capture different incoming symbol options"); + assert_eq!(symbol_font_family(document(&session), &imported), alias_family); + let options = Clipboard::from_document(document(&session)).symbol_options; + assert_eq!(options.get(&imported), Some(&source_options)); + assert_eq!(options.get(symbol), Some(&held_options)); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); + let repeated = place(&mut session, &path, linked); + assert_eq!(only_symbol_name(document(&session).node(repeated).unwrap()), imported); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); + } + } +} From 4681a68bd418e319ff31d650d3d3800a7973a13b Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 18:32:49 -0800 Subject: [PATCH 10/18] test: access the known native symbol lettering directly --- crates/engine/tests/native_composite_adoption.rs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index cf26e9280e..cbdc2447b2 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -858,15 +858,14 @@ fn native_composite_mapped_symbol_art_shares_only_matching_options() { let mut target = document(&seed).clone(); let definition = target.symbols.iter_mut().find(|definition| definition.name == symbol).unwrap(); // The original-name art now already uses the equivalent font selected by the import. - std::sync::Arc::make_mut(&mut definition.art).walk_mut(&mut |node| { - if let NodeKind::Text(text) = &mut node.kind { - for run in &mut text.runs { - if CompositeFont::same_name(&run.style.font_family, &incoming.name) { - run.style.font_family = alias_family.clone(); - } - } + let NodeKind::Text(text) = &mut std::sync::Arc::make_mut(&mut definition.art).kind else { + panic!("CONTROL: the one source lettering object stays text in its symbol"); + }; + for run in &mut text.runs { + if CompositeFont::same_name(&run.style.font_family, &incoming.name) { + run.style.font_family = alias_family.clone(); } - }); + } assert_eq!(symbol_font_family(&target, symbol), alias_family); if !matching_options { // Public document storage keeps natural size separately from the symbol's art. From f4b7ab862d4120a956a8b27681a52cd72d5f9923 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 18:36:56 -0800 Subject: [PATCH 11/18] test: inspect mapped symbol reuse counterexample locally --- .../engine/tests/native_composite_adoption.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index cbdc2447b2..4b3c05c4b7 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -892,6 +892,32 @@ fn native_composite_mapped_symbol_art_shares_only_matching_options() { let id = place(&mut session, &path, linked); let imported = only_symbol_name(document(&session).node(id).unwrap()); let expected = if matching_options { symbol } else { alias_symbol.as_str() }; + // Temporary: compare the real stored candidates before changing the fixture or reuse policy. + let canonical_art = |doc: &Document, name: &str| { + let definition = doc.symbols.iter().find(|definition| definition.name == name).unwrap(); + Document::new(0.0, 0.0).reid(&definition.art) + }; + let original_art = canonical_art(&before, symbol); + let seeded_art = canonical_art(&before, &alias_symbol); + let imported_art = canonical_art(document(&session), &imported); + let before_options = Clipboard::from_document(&before).symbol_options; + let after_options = Clipboard::from_document(document(&session)).symbol_options; + eprintln!( + "MAPPED_OPTIONS_DIAGNOSTIC {}", + json!({ + "linked": linked, "matchingOptions": matching_options, + "originalName": symbol, "seedName": alias_symbol, "importedName": imported, + "seedFamily": alias_family, "importedFamily": symbol_font_family(document(&session), &imported), + "sourceOptions": format!("{source_options:?}"), + "heldOptions": format!("{held_options:?}"), + "seedOptions": format!("{:?}", before_options.get(&alias_symbol)), + "importedOptions": format!("{:?}", after_options.get(&imported)), + "originalEqualsSeed": original_art == seeded_art, + "seedEqualsImported": seeded_art == imported_art, + "originalEqualsImported": original_art == imported_art, + "originalArt": original_art, "seedArt": seeded_art, "importedArt": imported_art + }) + ); assert_eq!(imported, expected, "matching art must not capture different incoming symbol options"); assert_eq!(symbol_font_family(document(&session), &imported), alias_family); let options = Clipboard::from_document(document(&session)).symbol_options; From 3643ee8b65787004ea1355fe4a7788c08d73be75 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 18:41:07 -0800 Subject: [PATCH 12/18] test: inspect mapped symbol reuse counterexample locally --- .../engine/tests/native_composite_adoption.rs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 4b3c05c4b7..be86feb548 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -918,6 +918,38 @@ fn native_composite_mapped_symbol_art_shares_only_matching_options() { "originalArt": original_art, "seedArt": seeded_art, "importedArt": imported_art }) ); + let layout_cache = |art: &Node| { + let NodeKind::Text(text) = &art.kind else { + panic!("CONTROL: canonical symbol art is the one text object"); + }; + json!({ + "bounds": format!("{:?}", text.cached_bounds), + "baselines": format!("{:?}", text.cached_baselines), + "ink": format!("{:?}", text.cached_ink), + "fileFontIds": text.runs.iter().map(|run| run.style.file_font_id).collect::>() + }) + }; + let without_layout_cache = |art: &Node| { + let mut diagnostic_clone = art.clone(); + let NodeKind::Text(text) = &mut diagnostic_clone.kind else { + panic!("CONTROL: canonical symbol art is the one text object"); + }; + text.cached_bounds = None; + text.cached_baselines.clear(); + text.cached_ink = None; + diagnostic_clone + }; + eprintln!( + "MAPPED_OPTIONS_CACHE_DIAGNOSTIC {}", + json!({ + "originalCache": layout_cache(&original_art), + "seedCache": layout_cache(&seeded_art), + "importedCache": layout_cache(&imported_art), + "originalEqualsSeedWithoutCache": without_layout_cache(&original_art) == without_layout_cache(&seeded_art), + "seedEqualsImportedWithoutCache": without_layout_cache(&seeded_art) == without_layout_cache(&imported_art), + "originalEqualsImportedWithoutCache": without_layout_cache(&original_art) == without_layout_cache(&imported_art) + }) + ); assert_eq!(imported, expected, "matching art must not capture different incoming symbol options"); assert_eq!(symbol_font_family(document(&session), &imported), alias_family); let options = Clipboard::from_document(document(&session)).symbol_options; From 0c93100bb3b02fc7c51bf910e314f6c117297a80 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 18:52:40 -0800 Subject: [PATCH 13/18] fix: measure native artwork in its own composite fonts --- crates/engine/src/cmd/place/adopt.rs | 11 +- crates/engine/src/cmd/place/document.rs | 4 + .../engine/tests/native_composite_adoption.rs | 102 ++++++++---------- 3 files changed, 58 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index dd10f08266..0c9d67c32d 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -165,7 +165,16 @@ fn canon(dst: &Document, n: &Node) -> Node { own.images.insert(k.clone(), blob.clone()); } } - own.reid(n) + let mut canonical = own.reid(n); + // Derived layout caches do not define the stored art's resource identity. + each_mut(&mut canonical, &mut |node| { + if let NodeKind::Text(text) = &mut node.kind { + text.cached_bounds = None; + text.cached_baselines.clear(); + text.cached_ink = None; + } + }); + canonical } /// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])? diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 6e9a1f242c..91f07428cd 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -178,6 +178,10 @@ fn opened_document_art( super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false); } l.doc.drop_edit_modes(); + // Measure and crop in this source's composite fonts, not those of the front document. + // The existing thread-local loan restores its caller's context on every return or unwind. + let source_fonts = l.doc.composite_fonts.clone(); + let _source_fonts = (!source_fonts.is_empty()).then(|| vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts)); // The native file does not store type's layout bounds. Measure them before cropping or // copying the art, so the placed group keeps the positions of aligned point type. for warning in crate::Session::refresh_text_bounds(&mut l.doc) { diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index be86feb548..7d3cf2dda6 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -826,6 +826,7 @@ fn native_composite_mapped_symbol_art_shares_only_matching_options() { let dir = TempDir::new("native-composite-mapped-options"); let path = dir.join("mapped-options.vectorcraft"); let incoming = CompositeFont::new("NativeAdoptionMappedOptions", "Source Sans 3", "Regular"); + assert_native_source_font_geometry(&dir.join("source-geometry.vectorcraft"), &incoming); let mut builder = Session::new(); builder.add_document(font_document(&incoming), None); let children = document(&builder).layers[0].children().unwrap(); @@ -892,64 +893,6 @@ fn native_composite_mapped_symbol_art_shares_only_matching_options() { let id = place(&mut session, &path, linked); let imported = only_symbol_name(document(&session).node(id).unwrap()); let expected = if matching_options { symbol } else { alias_symbol.as_str() }; - // Temporary: compare the real stored candidates before changing the fixture or reuse policy. - let canonical_art = |doc: &Document, name: &str| { - let definition = doc.symbols.iter().find(|definition| definition.name == name).unwrap(); - Document::new(0.0, 0.0).reid(&definition.art) - }; - let original_art = canonical_art(&before, symbol); - let seeded_art = canonical_art(&before, &alias_symbol); - let imported_art = canonical_art(document(&session), &imported); - let before_options = Clipboard::from_document(&before).symbol_options; - let after_options = Clipboard::from_document(document(&session)).symbol_options; - eprintln!( - "MAPPED_OPTIONS_DIAGNOSTIC {}", - json!({ - "linked": linked, "matchingOptions": matching_options, - "originalName": symbol, "seedName": alias_symbol, "importedName": imported, - "seedFamily": alias_family, "importedFamily": symbol_font_family(document(&session), &imported), - "sourceOptions": format!("{source_options:?}"), - "heldOptions": format!("{held_options:?}"), - "seedOptions": format!("{:?}", before_options.get(&alias_symbol)), - "importedOptions": format!("{:?}", after_options.get(&imported)), - "originalEqualsSeed": original_art == seeded_art, - "seedEqualsImported": seeded_art == imported_art, - "originalEqualsImported": original_art == imported_art, - "originalArt": original_art, "seedArt": seeded_art, "importedArt": imported_art - }) - ); - let layout_cache = |art: &Node| { - let NodeKind::Text(text) = &art.kind else { - panic!("CONTROL: canonical symbol art is the one text object"); - }; - json!({ - "bounds": format!("{:?}", text.cached_bounds), - "baselines": format!("{:?}", text.cached_baselines), - "ink": format!("{:?}", text.cached_ink), - "fileFontIds": text.runs.iter().map(|run| run.style.file_font_id).collect::>() - }) - }; - let without_layout_cache = |art: &Node| { - let mut diagnostic_clone = art.clone(); - let NodeKind::Text(text) = &mut diagnostic_clone.kind else { - panic!("CONTROL: canonical symbol art is the one text object"); - }; - text.cached_bounds = None; - text.cached_baselines.clear(); - text.cached_ink = None; - diagnostic_clone - }; - eprintln!( - "MAPPED_OPTIONS_CACHE_DIAGNOSTIC {}", - json!({ - "originalCache": layout_cache(&original_art), - "seedCache": layout_cache(&seeded_art), - "importedCache": layout_cache(&imported_art), - "originalEqualsSeedWithoutCache": without_layout_cache(&original_art) == without_layout_cache(&seeded_art), - "seedEqualsImportedWithoutCache": without_layout_cache(&seeded_art) == without_layout_cache(&imported_art), - "originalEqualsImportedWithoutCache": without_layout_cache(&original_art) == without_layout_cache(&imported_art) - }) - ); assert_eq!(imported, expected, "matching art must not capture different incoming symbol options"); assert_eq!(symbol_font_family(document(&session), &imported), alias_family); let options = Clipboard::from_document(document(&session)).symbol_options; @@ -964,3 +907,46 @@ fn native_composite_mapped_symbol_art_shares_only_matching_options() { } } } + +// The native reader must measure its own composite meanings before cropping, not the front document's. +fn assert_native_source_font_geometry(path: &Path, incoming: &CompositeFont) { + write_native(path, &font_document(incoming)); + for linked in [false, true] { + let mut ordinary_placement = None; + let mut ordinary_destination_width = None; + for scale in [100.0, 125.0] { + let mut existing = incoming.clone(); + existing.parts.roman.size = scale; + let mut session = destination(std::slice::from_ref(&existing)); + let (kept_id, kept_art) = kept_text(&mut session, &existing); + let kept_width = kept_art.geometric_bounds().unwrap().width(); + if let Some(width) = ordinary_destination_width { + assert!(kept_width > width, "CONTROL: the destination really measures this same font family at the larger size"); + } else { + ordinary_destination_width = Some(kept_width); + } + let reply = session + .execute("file.place", &json!({"path": path, "link": linked, "crop": "bounding", "at": [30, 25]})) + .unwrap(); + assert_eq!(reply["linked"], linked); + let id = NodeId(reply["ids"][0].as_u64().unwrap()); + if linked { + session.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + } + let doc = document(&session); + let family = placed_family(&session, id); + let font = CompositeFont::named(&doc.composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + assert_eq!(CompositeFont::same_name(&family, &incoming.name), scale == 100.0); + let bounds = doc.node(id).unwrap().geometric_bounds_with(&doc.symbol_boxes()).unwrap(); + assert!(bounds.width() > 0.0 && bounds.height() > 0.0); + if let Some(expected) = ordinary_placement { + assert_eq!(bounds, expected, "bounding placement keeps source geometry under a conflicting destination font meaning"); + } else { + ordinary_placement = Some(bounds); + } + assert_eq!(doc.node(kept_id), Some(&kept_art), "source measurement does not alter the existing destination artwork"); + assert_eq!(CompositeFont::named(&doc.composite_fonts, &existing.name), Some(&existing)); + } + } +} From db374a4fae90a689daece73d454424751458d08a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 18:54:34 -0800 Subject: [PATCH 14/18] style: format source-font geometry regression --- crates/engine/tests/native_composite_adoption.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 7d3cf2dda6..29cd686c22 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -925,9 +925,7 @@ fn assert_native_source_font_geometry(path: &Path, incoming: &CompositeFont) { } else { ordinary_destination_width = Some(kept_width); } - let reply = session - .execute("file.place", &json!({"path": path, "link": linked, "crop": "bounding", "at": [30, 25]})) - .unwrap(); + let reply = session.execute("file.place", &json!({"path": path, "link": linked, "crop": "bounding", "at": [30, 25]})).unwrap(); assert_eq!(reply["linked"], linked); let id = NodeId(reply["ids"][0].as_u64().unwrap()); if linked { From 907ee89e382a1bbbf269cc5b3c03ba3d67985228 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 19:38:28 -0800 Subject: [PATCH 15/18] fix: retain native resource references and source font context --- crates/engine/src/cmd/place/adopt.rs | 62 ++- crates/engine/src/cmd/place/document.rs | 2 +- .../engine/tests/native_composite_adoption.rs | 506 +++++++++++++++--- 3 files changed, 507 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/cmd/place/adopt.rs b/crates/engine/src/cmd/place/adopt.rs index 0c9d67c32d..483503f190 100644 --- a/crates/engine/src/cmd/place/adopt.rs +++ b/crates/engine/src/cmd/place/adopt.rs @@ -55,9 +55,56 @@ fn paint_refs(p: &mut Paint, f: &mut impl FnMut(Ref)) { }); } +/// Visit only the records the shared reader accepted, in their original order. Consuming +/// each accepted record once also leaves ignored duplicate surfaces and capped records alone. +fn accepted_graphic_refs( + list: &mut serde_json::Value, + accepted: Vec, + parse: impl Fn(&serde_json::Value) -> Option, + f: &mut impl FnMut(Ref), +) { + let Some(list) = list.as_array_mut() else { return }; + let mut accepted = accepted.into_iter().peekable(); + for value in list { + let Some(next) = accepted.peek() else { break }; + if parse(value).as_ref() != Some(next) { + continue; + } + let _ = accepted.next(); + if let Some(serde_json::Value::String(symbol)) = value.get_mut("symbol") { + f(Ref::Symbol(symbol)); + } + } +} + +/// Symbol references in accepted Graphics and Map Art records, including fill/stroke effects. +/// Each stored name is visited once, so a rename cannot feed a second rename in the same map. +fn appearance_graphic_refs(appearance: &mut vectorcraft_doc::Appearance, f: &mut impl FnMut(Ref)) { + use vectorcraft_render::effects as fx; + + if fx::appearance_graphic_symbols(appearance).is_empty() { + return; + } + let (effects, items) = (&mut appearance.effects, &mut appearance.items); + for effect in effects.iter_mut().chain(items.iter_mut().flat_map(|item| item.effects_mut())) { + if fx::takes_graphics(&effect.id) { + let accepted = fx::mapped_graphics(&effect.params); + if let Some(list) = effect.params.get_mut(fx::GRAPHICS) { + accepted_graphic_refs(list, accepted, |value| fx::MappedGraphic::from_value(value).ok(), f); + } + } else if fx::takes_map_art(&effect.id) { + let accepted = fx::surface_maps(&effect.params); + if let Some(list) = effect.params.get_mut(fx::MAP_ART) { + accepted_graphic_refs(list, accepted, |value| fx::SurfaceMap::from_value(value).ok(), f); + } + } + } +} + /// Every resource reference in `n` and its descendants. fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { each_mut(n, &mut |n| { + appearance_graphic_refs(&mut n.appearance, f); for it in &mut n.appearance.items { match it { AppearanceItem::Fill(fl) => paint_refs(&mut fl.paint, f), @@ -74,6 +121,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { for r in &mut t.runs { paint_refs(&mut r.style.fill, f); paint_refs(&mut r.style.stroke, f); + if let Some(inline) = &mut r.inline { + f(Ref::Symbol(&mut inline.symbol)); + } } if let Some(fonts) = &mut t.file_fonts { fonts.map_keys(|key| f(Ref::Image(key))); @@ -84,6 +134,14 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) { NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)), _ => {} } + if let Some(extras) = n.extras_if_any() { + extras + .symbol_overrides + .iter_mut() + .flat_map(|override_| [&mut override_.fill, &mut override_.stroke]) + .flatten() + .for_each(|paint| paint_refs(paint, f)); + } // A color-masked image's masked pixels come along, and the key they were made from // follows the image's. if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) { @@ -446,7 +504,7 @@ fn reuse_remapped_resources( } /// Remap only incoming users before resource equality decides whether to share or copy. -/// Report actual family renaming so only that case needs the alias reuse phase. +/// Report actual family renaming for the final copied-resource reuse phase. fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) { let mut staged = src.clone(); let mut aliased = false; @@ -624,7 +682,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c)); } - if aliased { + if aliased || symbols.values().any(|(_, copy)| *copy) { reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]); } diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 91f07428cd..fe9279ac69 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -181,7 +181,7 @@ fn opened_document_art( // Measure and crop in this source's composite fonts, not those of the front document. // The existing thread-local loan restores its caller's context on every return or unwind. let source_fonts = l.doc.composite_fonts.clone(); - let _source_fonts = (!source_fonts.is_empty()).then(|| vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts)); + let _source_fonts = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts); // The native file does not store type's layout bounds. Measure them before cropping or // copying the art, so the placed group keeps the positions of aligned point type. for warning in crate::Session::refresh_text_bounds(&mut l.doc) { diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 29cd686c22..2c5fbe678f 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -664,6 +664,81 @@ fn nested_native_source(path: &std::path::Path, incoming: &CompositeFont, depend (builder, source) } +// Check one complete inline or embedded import and its repeat against the same source artifact. +fn assert_nested_alias_roundtrip( + source: &Document, + source_options: &std::collections::BTreeMap, + path: &Path, + incoming: &CompositeFont, + dependency: usize, + linked: bool, +) { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let inner = NESTED_INNER; + let outer = NESTED_OUTER; + let pattern_name = NESTED_PATTERN; + let brush_name = NESTED_BRUSH; + let mut target = source.clone(); + let font = target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); + font.parts.roman.size = 125.0; + assert_eq!(target.symbols, source.symbols, "CONTROL: only the meaning of the existing font differs"); + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let id = place(&mut session, path, linked); + let copied_outer = only_symbol_name(document(&session).node(id).unwrap()); + assert_ne!(copied_outer, outer); + let outer_art = &document(&session).symbols.iter().find(|definition| definition.name == copied_outer).unwrap().art; + let copied_inner = only_symbol_name(outer_art); + assert_ne!(copied_inner, inner, "the child follows its aliased composite-font meaning"); + let copied_pattern = (dependency == 1).then(|| pattern_in_symbol(document(&session), &copied_inner)); + let copied_brush = (dependency == 2).then(|| brush_in_symbol(document(&session), &copied_inner)); + let family = if let Some(pattern) = &copied_pattern { + assert_ne!(pattern.as_str(), pattern_name, "the pattern also gets a new meaning under the font alias"); + pattern_font_family(document(&session), pattern) + } else if let Some(brush) = &copied_brush { + assert_ne!(brush.as_str(), brush_name, "the stored brush gets its own aliased font meaning"); + brush_font_family(document(&session), brush) + } else { + symbol_font_family(document(&session), &copied_inner) + }; + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let definition = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&definition.parts, &definition.custom), (&incoming.parts, &incoming.custom)); + let imported_options = Clipboard::from_document(document(&session)).symbol_options; + assert_eq!(imported_options.get(&copied_inner), source_options.get(inner)); + assert_eq!(imported_options.get(&copied_outer), source_options.get(outer), "indirect parent copies keep all five option fields"); + assert_eq!(imported_options.get(inner), source_options.get(inner)); + assert_eq!(imported_options.get(outer), source_options.get(outer)); + assert_original_native_art(document(&session), &before); + assert_eq!(document(&session).symbols.len(), before.symbols.len() + 2); + + let first_symbols = document(&session).symbols.clone(); + let first_fonts = document(&session).composite_fonts.clone(); + let first_resources = native_resource_counts(document(&session)); + let first_brushes = vectorcraft_brush::library(document(&session)); + let repeated = place(&mut session, path, linked); + let repeated_outer = only_symbol_name(document(&session).node(repeated).unwrap()); + let repeated_art = &document(&session).symbols.iter().find(|definition| definition.name == repeated_outer).unwrap().art; + assert_eq!(repeated_outer, copied_outer); + assert_eq!(only_symbol_name(repeated_art), copied_inner, "repeat also reuses the actual mapped child name"); + if let Some(pattern) = &copied_pattern { + assert_eq!(pattern_in_symbol(document(&session), &copied_inner), *pattern); + assert_eq!(pattern_font_family(document(&session), pattern), family); + } else if let Some(brush) = &copied_brush { + assert_eq!(brush_in_symbol(document(&session), &copied_inner), *brush); + assert_eq!(brush_font_family(document(&session), brush), family); + } else { + assert_eq!(symbol_font_family(document(&session), &copied_inner), family); + } + assert_eq!(native_resource_counts(document(&session)), first_resources); + assert_eq!(document(&session).symbols, first_symbols); + assert_eq!(document(&session).composite_fonts, first_fonts); + assert_eq!(vectorcraft_brush::library(document(&session)), first_brushes); + assert_original_native_art(document(&session), &before); +} + #[test] fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() { use vectorcraft_engine::cmd::clipboard::Clipboard; @@ -675,8 +750,6 @@ fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() let path = dir.join(format!("nested-lettering-{dependency}.vectorcraft")); let inner = NESTED_INNER; let outer = NESTED_OUTER; - let pattern_name = NESTED_PATTERN; - let brush_name = NESTED_BRUSH; let (_builder, source) = nested_native_source(&path, &incoming, dependency); let source_options = Clipboard::from_document(&source).symbol_options; for (name, registration, guides) in [ @@ -691,64 +764,7 @@ fn native_composite_nested_alias_copies_keep_outer_and_inner_options_and_reuse() assert!(options.pixel_aligned); } for linked in [false, true] { - let mut target = source.clone(); - let font = target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap(); - font.parts.roman.size = 125.0; - assert_eq!(target.symbols, source.symbols, "CONTROL: only the meaning of the existing font differs"); - let mut session = Session::new(); - session.add_document(target, None); - let before = document(&session).clone(); - let id = place(&mut session, &path, linked); - let copied_outer = only_symbol_name(document(&session).node(id).unwrap()); - assert_ne!(copied_outer, outer); - let outer_art = &document(&session).symbols.iter().find(|definition| definition.name == copied_outer).unwrap().art; - let copied_inner = only_symbol_name(outer_art); - assert_ne!(copied_inner, inner, "the child follows its aliased composite-font meaning"); - let copied_pattern = (dependency == 1).then(|| pattern_in_symbol(document(&session), &copied_inner)); - let copied_brush = (dependency == 2).then(|| brush_in_symbol(document(&session), &copied_inner)); - let family = if let Some(pattern) = &copied_pattern { - assert_ne!(pattern.as_str(), pattern_name, "the pattern also gets a new meaning under the font alias"); - pattern_font_family(document(&session), pattern) - } else if let Some(brush) = &copied_brush { - assert_ne!(brush.as_str(), brush_name, "the stored brush gets its own aliased font meaning"); - brush_font_family(document(&session), brush) - } else { - symbol_font_family(document(&session), &copied_inner) - }; - assert!(!CompositeFont::same_name(&family, &incoming.name)); - let definition = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); - assert_eq!((&definition.parts, &definition.custom), (&incoming.parts, &incoming.custom)); - let imported_options = Clipboard::from_document(document(&session)).symbol_options; - assert_eq!(imported_options.get(&copied_inner), source_options.get(inner)); - assert_eq!(imported_options.get(&copied_outer), source_options.get(outer), "indirect parent copies keep all five option fields"); - assert_eq!(imported_options.get(inner), source_options.get(inner)); - assert_eq!(imported_options.get(outer), source_options.get(outer)); - assert_original_native_art(document(&session), &before); - assert_eq!(document(&session).symbols.len(), before.symbols.len() + 2); - - let first_symbols = document(&session).symbols.clone(); - let first_fonts = document(&session).composite_fonts.clone(); - let first_resources = native_resource_counts(document(&session)); - let first_brushes = vectorcraft_brush::library(document(&session)); - let repeated = place(&mut session, &path, linked); - let repeated_outer = only_symbol_name(document(&session).node(repeated).unwrap()); - let repeated_art = &document(&session).symbols.iter().find(|definition| definition.name == repeated_outer).unwrap().art; - assert_eq!(repeated_outer, copied_outer); - assert_eq!(only_symbol_name(repeated_art), copied_inner, "repeat also reuses the actual mapped child name"); - if let Some(pattern) = &copied_pattern { - assert_eq!(pattern_in_symbol(document(&session), &copied_inner), *pattern); - assert_eq!(pattern_font_family(document(&session), pattern), family); - } else if let Some(brush) = &copied_brush { - assert_eq!(brush_in_symbol(document(&session), &copied_inner), *brush); - assert_eq!(brush_font_family(document(&session), brush), family); - } else { - assert_eq!(symbol_font_family(document(&session), &copied_inner), family); - } - assert_eq!(native_resource_counts(document(&session)), first_resources); - assert_eq!(document(&session).symbols, first_symbols); - assert_eq!(document(&session).composite_fonts, first_fonts); - assert_eq!(vectorcraft_brush::library(document(&session)), first_brushes); - assert_original_native_art(document(&session), &before); + assert_nested_alias_roundtrip(&source, &source_options, &path, &incoming, dependency, linked); } } } @@ -948,3 +964,373 @@ fn assert_native_source_font_geometry(path: &Path, incoming: &CompositeFont) { } } } + +#[test] +fn native_symbol_options_reuse_without_composite_fonts() { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-no-font-options"); + let path = dir.join("plain-symbol.vectorcraft"); + let mut builder = Session::new(); + builder.add_document(Document::new(100.0, 80.0), None); + let text = builder.execute("text.create", &json!({"x": 4, "y": 16, "text": "Ab", "font": "Source Sans 3"})).unwrap(); + let symbol = "NativeNoFontOptionsSymbol"; + builder.execute("symbol.new", &json!({"name": symbol, "ids": [text["id"]], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true})).unwrap(); + let source = write_native(&path, document(&builder)); + assert!(source.composite_fonts.is_empty(), "CONTROL: no font-family alias can enable resource finalization"); + let source_options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); + for linked in [false, true] { + for matching_options in [false, true] { + let mut target = source.clone(); + if !matching_options { + target.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).unwrap().as_object_mut().unwrap().remove(symbol); + target.set_symbol_registration(symbol, vectorcraft_doc::SymbolRegistration(8)); + target.set_symbol_export_type(symbol, vectorcraft_doc::SymbolExportType::default()); + target.set_symbol_nine_slice(symbol, None); + target.set_symbol_pixel_aligned(symbol, false); + } + let held_options = Clipboard::from_document(&target).symbol_options.get(symbol).unwrap().clone(); + if matching_options { + assert_eq!(held_options, source_options); + } else { + assert_ne!(held_options.size, source_options.size); + assert_ne!(held_options.registration, source_options.registration); + assert_ne!(held_options.export_type, source_options.export_type); + assert_ne!(held_options.nine_slice, source_options.nine_slice); + assert_ne!(held_options.pixel_aligned, source_options.pixel_aligned); + } + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let first = place(&mut session, &path, linked); + let name = only_symbol_name(document(&session).node(first).unwrap()); + assert_eq!(name == symbol, matching_options, "equal options share; different options retain a separate definition"); + let options = Clipboard::from_document(document(&session)).symbol_options; + assert_eq!(options.get(&name), Some(&source_options)); + assert_eq!(options.get(symbol), Some(&held_options)); + assert_eq!(document(&session).symbols.len(), before.symbols.len() + usize::from(!matching_options)); + assert!(document(&session).composite_fonts.is_empty()); + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let second = place(&mut session, &path, linked); + assert_eq!(only_symbol_name(document(&session).node(second).unwrap()), name, "repeat reuses the actual first alias"); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); + } + } +} + +#[test] +fn native_source_without_composites_ignores_front_font_meaning() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-empty-source-fonts"); + let path = dir.join("undefined-family.vectorcraft"); + let mut font = CompositeFont::new("NativeEmptySourceFamily", "Source Sans 3", "Regular"); + let mut source = font_document(&font); + source.composite_fonts = Vec::new().into(); + let source = write_native(&path, &source); + assert!(source.composite_fonts.is_empty()); + let params = json!({"path": path, "crop": "bounding"}); + let mut control = destination(&[]); + let expected = control.execute("file.place.info", ¶ms).unwrap(); + assert!(expected["width"].as_f64().unwrap() > 0.0 && expected["height"].as_f64().unwrap() > 0.0); + font.parts.roman.size = 125.0; + let mut front = destination(std::slice::from_ref(&font)); + let (kept, art) = kept_text(&mut front, &font); + let before = document(&front).clone(); + let registered = FontDb::global().composite_font(&font.name).unwrap(); + assert_eq!(&*registered, &font, "CONTROL: the front document really declares the conflicting meaning"); + let actual = front.execute("file.place.info", ¶ms).unwrap(); + assert_eq!(actual["width"], expected["width"], "bounding reads must not borrow a family absent from the source"); + assert_eq!(actual["height"], expected["height"]); + assert_eq!(actual["warnings"], expected["warnings"]); + assert_eq!(document(&front), &before, "a source-size query does not edit the front document"); + assert_eq!(document(&front).node(kept), Some(&art)); + assert_eq!(&*FontDb::global().composite_font(&font.name).unwrap(), &font, "source measurement restores the front meaning"); + // The file's undefined family is not given a new alias or post-adoption policy by this query test. +} + +fn native_mapping_source(path: &Path, incoming: &CompositeFont, location: usize, classic: bool, mixed: bool) -> (Session, Document) { + use vectorcraft_doc::{Appearance, Effect}; + use vectorcraft_color::{Color, Paint}; + use vectorcraft_geom::{Affine, Rect}; + + let (builder, mut source) = nested_native_source(path, incoming, 0); + let outer = only_symbol_name(&source.layers[0]); + let outer_art = &source.symbols.iter().find(|definition| definition.name == outer).unwrap().art; + let symbol = only_symbol_name(outer_art); + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().clear(); + let entry = if classic { json!({"surface": 1, "symbol": symbol}) } else { json!({"symbol": symbol}) }; + let rejected = if classic { + json!({"surface": 2, "symbol": symbol, "scaleX": 0}) + } else { + json!({"symbol": symbol, "scale": 0}) + }; + if classic { + vectorcraft_render::effects::SurfaceMap::from_value(&entry).unwrap(); + assert!(vectorcraft_render::effects::SurfaceMap::from_value(&rejected).is_err()); + } else { + vectorcraft_render::effects::MappedGraphic::from_value(&entry).unwrap(); + assert!(vectorcraft_render::effects::MappedGraphic::from_value(&rejected).is_err()); + } + let effect = Effect { + id: if classic { vectorcraft_render::effects::CLASSIC_EXTRUDE } else { vectorcraft_render::effects::ROTATE }.into(), + params: if classic { + json!({"mapArt": [entry, rejected, {"surface": 1, "symbol": symbol}], "graphics": [{"symbol": symbol}]}) + } else { + json!({"graphics": [entry, rejected], "mapArt": [{"surface": 1, "symbol": symbol}]}) + }, + visible: true, + }; + let mut carrier = Node::path(source.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(2.0, 2.0, 22.0, 22.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0)); + match location { + 0 => carrier.appearance.effects.push(effect), + 1 => carrier.appearance.fill_mut().unwrap().effects.push(effect), + _ => carrier.appearance.stroke_mut().unwrap().effects.push(effect), + } + assert_eq!(vectorcraft_render::effects::appearance_graphic_symbols(&carrier.appearance), vec![symbol.clone()]); + let mut added = vec![std::sync::Arc::new(carrier)]; + if mixed { + let xf = Affine::translate((40.0, 40.0)) * Affine::scale(0.1); + added.push(std::sync::Arc::new(Node::new(source.alloc_id(), NodeKind::SymbolInstance { symbol, xf }))); + } + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().extend(added); + source.fix_next_id(); + (builder, source) +} + +fn one_mapping_effect(root: &Node) -> vectorcraft_doc::Effect { + let mut effects = Vec::new(); + root.walk(&mut |node| { + effects.extend(node.appearance.effects.iter().cloned()); + for item in &node.appearance.items { + effects.extend(item.effects().iter().cloned()); + } + }); + assert_eq!(effects.len(), 1, "CONTROL: one own/fill/stroke mapping effect, not rendered output"); + effects.pop().unwrap() +} + +fn assert_native_mapping_roundtrip(source: &Document, path: &Path, incoming: &CompositeFont, classic: bool, mixed: bool, linked: bool) { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let key = if classic { "mapArt" } else { "graphics" }; + let original_effect = one_mapping_effect(&source.layers[0]); + let original = original_effect.params[key][0]["symbol"].as_str().unwrap(); + let source_options = Clipboard::from_document(source).symbol_options.get(original).unwrap().clone(); + let mut target = source.clone(); + target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap().parts.roman.size = 125.0; + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let first = place(&mut session, path, linked); + let effect = one_mapping_effect(document(&session).node(first).unwrap()); + let mapped = effect.params[key][0]["symbol"].as_str().unwrap(); + assert_ne!(mapped, original, "the accepted mapping must follow incoming art, not the conflicting destination symbol"); + let family = symbol_font_family(document(&session), mapped); + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let font = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + assert_eq!(Clipboard::from_document(document(&session)).symbol_options.get(mapped), Some(&source_options)); + let mut expected = original_effect.clone(); + expected.params[key][0]["symbol"] = json!(mapped); + assert_eq!(effect, expected, "rejected records, duplicate surfaces and inactive keys retain their original fields"); + if mixed { + assert_eq!(only_symbol_name(document(&session).node(first).unwrap()), mapped, "ordinary and mapped users follow the same copy"); + } + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let repeated = place(&mut session, path, linked); + assert_eq!(one_mapping_effect(document(&session).node(repeated).unwrap()), effect); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); +} + +#[test] +fn native_mapped_effect_symbols_keep_incoming_font_and_options() { + let _context = FontContext::hold(); + let dir = TempDir::new("native-mapped-fonts"); + let incoming = CompositeFont::new("NativeMappedFont", "Source Sans 3", "Regular"); + // Three distinct storage seams, rather than an effect/backend matrix. + for (location, classic, mixed) in [(0, false, false), (1, true, false), (2, true, true)] { + let path = dir.join(format!("mapped-{location}.vectorcraft")); + let (_builder, source) = native_mapping_source(&path, &incoming, location, classic, mixed); + let source = write_native(&path, &source); + for linked in [false, true] { + assert_native_mapping_roundtrip(&source, &path, &incoming, classic, mixed, linked); + } + } +} + +fn one_inline_art(root: &Node) -> vectorcraft_doc::InlineArt { + let mut found = Vec::new(); + root.walk(&mut |node| { + if let NodeKind::Text(text) = &node.kind { + found.extend(text.runs.iter().filter_map(|run| run.inline.clone())); + } + }); + assert_eq!(found.len(), 1, "CONTROL: one inline-only symbol reference"); + found.pop().unwrap() +} + +fn assert_inline_native_roundtrip(source: &Document, path: &Path, incoming: &CompositeFont, linked: bool) { + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let original = one_inline_art(&source.layers[0]); + let source_options = Clipboard::from_document(source).symbol_options.get(&original.symbol).unwrap().clone(); + let mut target = source.clone(); + target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap().parts.roman.size = 125.0; + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let id = place(&mut session, path, linked); + let imported = one_inline_art(document(&session).node(id).unwrap()); + assert_ne!(imported.symbol, original.symbol, "inline art must not resolve to the destination's different font meaning"); + assert_eq!((imported.scale, imported.baseline_shift), (original.scale, original.baseline_shift)); + let family = symbol_font_family(document(&session), &imported.symbol); + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let font = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + assert_eq!(Clipboard::from_document(document(&session)).symbol_options.get(&imported.symbol), Some(&source_options)); + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let second = place(&mut session, path, linked); + let repeated = one_inline_art(document(&session).node(second).unwrap()); + assert_eq!(repeated.symbol, imported.symbol); + assert_eq!((repeated.scale, repeated.baseline_shift), (original.scale, original.baseline_shift)); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); +} + +#[test] +fn native_inline_symbol_keeps_incoming_font_and_options() { + use vectorcraft_doc::{InlineArt, TextRun}; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-inline-font"); + let path = dir.join("inline-lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeInlineFont", "Source Sans 3", "Regular"); + let (mut builder, source) = nested_native_source(&path, &incoming, 0); + let outer = only_symbol_name(&source.layers[0]); + let outer_art = &source.symbols.iter().find(|definition| definition.name == outer).unwrap().art; + let inner = only_symbol_name(outer_art); + let ids = document(&builder).layers[0].children().unwrap().iter().map(|node| node.id.0).collect::>(); + builder.execute("edit.clear", &json!({"ids": ids})).unwrap(); + let made = builder.execute("text.create", &json!({"x": 10, "y": 30, "text": "X", "font": "Source Sans 3"})).unwrap(); + let mut source = document(&builder).clone(); + let NodeKind::Text(text) = &mut source.node_mut(NodeId(made["id"].as_u64().unwrap())).unwrap().kind else { + panic!("CONTROL: public text.create produces the inline holder"); + }; + let style = text.runs[0].style.clone(); + assert!(!CompositeFont::same_name(&style.font_family, &incoming.name)); + let mut inline = InlineArt::new(inner); + inline.scale = 1.25; + inline.baseline_shift = 2.0; + text.runs = vec![TextRun::inline(inline, style)]; + let source = write_native(&path, &source); + let mut ordinary = false; + source.layers[0].walk(&mut |node| ordinary |= matches!(node.kind, NodeKind::SymbolInstance { .. })); + assert!(!ordinary, "CONTROL: no ordinary instance seeds the inline symbol dependency"); + for linked in [false, true] { + assert_inline_native_roundtrip(&source, &path, &incoming, linked); + } +} + +fn one_pattern_override(root: &Node) -> vectorcraft_doc::SymbolOverride { + let mut found = Vec::new(); + root.walk(&mut |node| found.extend(node.extras().symbol_overrides.iter().cloned())); + assert_eq!(found.len(), 1, "CONTROL: one stored dynamic override"); + found.pop().unwrap() +} + +fn override_pattern(override_: &vectorcraft_doc::SymbolOverride) -> String { + use vectorcraft_color::Paint; + + let Some(Paint::Pattern { pattern: fill, .. }) = &override_.fill else { panic!("CONTROL: a pattern fill override") }; + let Some(Paint::Pattern { pattern: stroke, .. }) = &override_.stroke else { panic!("CONTROL: a pattern stroke override") }; + assert_eq!(fill, stroke); + fill.clone() +} + +fn assert_override_native_roundtrip(source: &Document, path: &Path, incoming: &CompositeFont, linked: bool) { + use vectorcraft_color::Paint; + use vectorcraft_engine::cmd::clipboard::Clipboard; + + let original = one_pattern_override(&source.layers[0]); + let original_pattern = override_pattern(&original); + let symbol = only_symbol_name(&source.layers[0]); + let options = Clipboard::from_document(source).symbol_options.get(&symbol).unwrap().clone(); + let mut target = source.clone(); + target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap().parts.roman.size = 125.0; + let mut session = Session::new(); + session.add_document(target, None); + let before = document(&session).clone(); + let first = place(&mut session, path, linked); + let imported = one_pattern_override(document(&session).node(first).unwrap()); + let pattern = override_pattern(&imported); + assert_ne!(pattern, original_pattern, "override-only pattern art follows the incoming composite meaning"); + let family = pattern_font_family(document(&session), &pattern); + assert!(!CompositeFont::same_name(&family, &incoming.name)); + let font = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); + assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); + let mut expected = original.clone(); + for paint in [&mut expected.fill, &mut expected.stroke].into_iter().flatten() { + let Paint::Pattern { pattern: name, .. } = paint else { panic!("CONTROL: both override paints are patterns") }; + *name = pattern.clone(); + } + assert_eq!(imported, expected, "override paths, transforms, opacity and blend retain their source values"); + let used_symbol = only_symbol_name(document(&session).node(first).unwrap()); + assert_eq!(used_symbol, symbol, "plain base symbol still shares its unchanged art and options"); + assert_eq!(Clipboard::from_document(document(&session)).symbol_options.get(&used_symbol), Some(&options)); + assert_original_native_art(document(&session), &before); + let resources = native_resource_counts(document(&session)); + let repeated = place(&mut session, path, linked); + assert_eq!(one_pattern_override(document(&session).node(repeated).unwrap()), imported); + assert_eq!(native_resource_counts(document(&session)), resources); + assert_original_native_art(document(&session), &before); +} + +#[test] +fn native_symbol_override_patterns_keep_incoming_font_meaning() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, SymbolOverride}; + use vectorcraft_geom::Affine; + + let _context = FontContext::hold(); + let dir = TempDir::new("native-override-font"); + let path = dir.join("override-lettering.vectorcraft"); + let incoming = CompositeFont::new("NativeOverrideFont", "Source Sans 3", "Regular"); + let (_builder, mut source) = nested_native_source(&path, &incoming, 1); + let outer = only_symbol_name(&source.layers[0]); + let outer_art = &source.symbols.iter().find(|definition| definition.name == outer).unwrap().art; + let inner = only_symbol_name(outer_art); + let pattern = pattern_in_symbol(&source, &inner); + let base = source.symbols.iter_mut().find(|definition| definition.name == inner).unwrap(); + base.dynamic = true; + std::sync::Arc::make_mut(&mut base.art).appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0); + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().clear(); + let mut instance = Node::new(source.alloc_id(), NodeKind::SymbolInstance { + symbol: inner.clone(), xf: Affine::translate((40.0, 40.0)) * Affine::scale(0.1), + }); + instance.appearance = Appearance::basic(Paint::None, Paint::None, 0.0); + instance.extras_mut().symbol_overrides.push(SymbolOverride { + path: vec![], + fill: Some(vectorcraft_doc::pattern::pattern_paint(&pattern)), + stroke: Some(Paint::Pattern { pattern, xf: Affine::scale(2.0) }), + opacity: Some(0.65), blend: None, + }); + let base = &source.symbols.iter().find(|definition| definition.name == inner).unwrap().art; + let effective = vectorcraft_doc::symbol_overrides::instance_art(base, &instance); + let override_ = &instance.extras().symbol_overrides[0]; + assert_eq!(Some(effective.appearance.fill_paint()), override_.fill); + assert_eq!(Some(effective.appearance.stroke().unwrap().paint.clone()), override_.stroke); + std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(instance)); + source.fix_next_id(); + let source = write_native(&path, &source); + for linked in [false, true] { + assert_override_native_roundtrip(&source, &path, &incoming, linked); + } +} From 2f420003c5a5a8d7b3d768020893fdbe0881e73f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 19:45:35 -0800 Subject: [PATCH 16/18] test: convert native fixture appearances to shared storage --- crates/engine/tests/native_composite_adoption.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 2c5fbe678f..522c3cad2f 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -1310,12 +1310,12 @@ fn native_symbol_override_patterns_keep_incoming_font_meaning() { let pattern = pattern_in_symbol(&source, &inner); let base = source.symbols.iter_mut().find(|definition| definition.name == inner).unwrap(); base.dynamic = true; - std::sync::Arc::make_mut(&mut base.art).appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0); + std::sync::Arc::make_mut(&mut base.art).appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0).into(); std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().clear(); let mut instance = Node::new(source.alloc_id(), NodeKind::SymbolInstance { symbol: inner.clone(), xf: Affine::translate((40.0, 40.0)) * Affine::scale(0.1), }); - instance.appearance = Appearance::basic(Paint::None, Paint::None, 0.0); + instance.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); instance.extras_mut().symbol_overrides.push(SymbolOverride { path: vec![], fill: Some(vectorcraft_doc::pattern::pattern_paint(&pattern)), From 8ec2527ee3af1ea23e74ec49b9034e2f7e5bbc34 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 19:48:16 -0800 Subject: [PATCH 17/18] test: inspect stored options for inline-only native imports --- crates/engine/tests/native_composite_adoption.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 522c3cad2f..6b562388b3 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -1177,10 +1177,8 @@ fn one_inline_art(root: &Node) -> vectorcraft_doc::InlineArt { } fn assert_inline_native_roundtrip(source: &Document, path: &Path, incoming: &CompositeFont, linked: bool) { - use vectorcraft_engine::cmd::clipboard::Clipboard; - let original = one_inline_art(&source.layers[0]); - let source_options = Clipboard::from_document(source).symbol_options.get(&original.symbol).unwrap().clone(); + let source_size = source.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|sizes| sizes.get(&original.symbol)); let mut target = source.clone(); target.composite_fonts.iter_mut().find(|font| CompositeFont::same_name(&font.name, &incoming.name)).unwrap().parts.roman.size = 125.0; let mut session = Session::new(); @@ -1194,7 +1192,12 @@ fn assert_inline_native_roundtrip(source: &Document, path: &Path, incoming: &Com assert!(!CompositeFont::same_name(&family, &incoming.name)); let font = CompositeFont::named(&document(&session).composite_fonts, &family).unwrap(); assert_eq!((&font.parts, &font.custom), (&incoming.parts, &incoming.custom)); - assert_eq!(Clipboard::from_document(document(&session)).symbol_options.get(&imported.symbol), Some(&source_options)); + let imported_doc = document(&session); + assert_eq!(imported_doc.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|sizes| sizes.get(&imported.symbol)), source_size); + assert_eq!(imported_doc.symbol_registration(&imported.symbol), source.symbol_registration(&original.symbol)); + assert_eq!(imported_doc.symbol_export_type(&imported.symbol), source.symbol_export_type(&original.symbol)); + assert_eq!(imported_doc.symbol_nine_slice(&imported.symbol), source.symbol_nine_slice(&original.symbol)); + assert_eq!(imported_doc.symbol_pixel_aligned(&imported.symbol), source.symbol_pixel_aligned(&original.symbol)); assert_original_native_art(document(&session), &before); let resources = native_resource_counts(document(&session)); let second = place(&mut session, path, linked); From 1bdc639a85e6b336fd62e5b79dd469f9976b9fff Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 19:56:11 -0800 Subject: [PATCH 18/18] style: format native import regression controls --- .../engine/tests/native_composite_adoption.rs | 32 +++++++++++-------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/engine/tests/native_composite_adoption.rs b/crates/engine/tests/native_composite_adoption.rs index 6b562388b3..55f1f4976f 100644 --- a/crates/engine/tests/native_composite_adoption.rs +++ b/crates/engine/tests/native_composite_adoption.rs @@ -976,8 +976,13 @@ fn native_symbol_options_reuse_without_composite_fonts() { builder.add_document(Document::new(100.0, 80.0), None); let text = builder.execute("text.create", &json!({"x": 4, "y": 16, "text": "Ab", "font": "Source Sans 3"})).unwrap(); let symbol = "NativeNoFontOptionsSymbol"; - builder.execute("symbol.new", &json!({"name": symbol, "ids": [text["id"]], "registration": 0, "exportType": "graphic", - "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true})).unwrap(); + builder + .execute( + "symbol.new", + &json!({"name": symbol, "ids": [text["id"]], "registration": 0, "exportType": "graphic", + "nineSlice": true, "nineSliceGuides": [0.2, 0.3, 0.25, 0.15], "alignToPixelGrid": true}), + ) + .unwrap(); let source = write_native(&path, document(&builder)); assert!(source.composite_fonts.is_empty(), "CONTROL: no font-family alias can enable resource finalization"); let source_options = Clipboard::from_document(&source).symbol_options.get(symbol).unwrap().clone(); @@ -1053,8 +1058,8 @@ fn native_source_without_composites_ignores_front_font_meaning() { } fn native_mapping_source(path: &Path, incoming: &CompositeFont, location: usize, classic: bool, mixed: bool) -> (Session, Document) { - use vectorcraft_doc::{Appearance, Effect}; use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Effect}; use vectorcraft_geom::{Affine, Rect}; let (builder, mut source) = nested_native_source(path, incoming, 0); @@ -1063,11 +1068,7 @@ fn native_mapping_source(path: &Path, incoming: &CompositeFont, location: usize, let symbol = only_symbol_name(outer_art); std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().clear(); let entry = if classic { json!({"surface": 1, "symbol": symbol}) } else { json!({"symbol": symbol}) }; - let rejected = if classic { - json!({"surface": 2, "symbol": symbol, "scaleX": 0}) - } else { - json!({"symbol": symbol, "scale": 0}) - }; + let rejected = if classic { json!({"surface": 2, "symbol": symbol, "scaleX": 0}) } else { json!({"symbol": symbol, "scale": 0}) }; if classic { vectorcraft_render::effects::SurfaceMap::from_value(&entry).unwrap(); assert!(vectorcraft_render::effects::SurfaceMap::from_value(&rejected).is_err()); @@ -1084,8 +1085,11 @@ fn native_mapping_source(path: &Path, incoming: &CompositeFont, location: usize, }, visible: true, }; - let mut carrier = Node::path(source.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(2.0, 2.0, 22.0, 22.0)), - Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0)); + let mut carrier = Node::path( + source.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(2.0, 2.0, 22.0, 22.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0), + ); match location { 0 => carrier.appearance.effects.push(effect), 1 => carrier.appearance.fill_mut().unwrap().effects.push(effect), @@ -1315,15 +1319,15 @@ fn native_symbol_override_patterns_keep_incoming_font_meaning() { base.dynamic = true; std::sync::Arc::make_mut(&mut base.art).appearance = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0).into(); std::sync::Arc::make_mut(&mut source.layers[0]).children_mut().unwrap().clear(); - let mut instance = Node::new(source.alloc_id(), NodeKind::SymbolInstance { - symbol: inner.clone(), xf: Affine::translate((40.0, 40.0)) * Affine::scale(0.1), - }); + let mut instance = + Node::new(source.alloc_id(), NodeKind::SymbolInstance { symbol: inner.clone(), xf: Affine::translate((40.0, 40.0)) * Affine::scale(0.1) }); instance.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); instance.extras_mut().symbol_overrides.push(SymbolOverride { path: vec![], fill: Some(vectorcraft_doc::pattern::pattern_paint(&pattern)), stroke: Some(Paint::Pattern { pattern, xf: Affine::scale(2.0) }), - opacity: Some(0.65), blend: None, + opacity: Some(0.65), + blend: None, }); let base = &source.symbols.iter().find(|definition| definition.name == inner).unwrap().art; let effective = vectorcraft_doc::symbol_overrides::instance_art(base, &instance);