From 4d975416335e18db8ac3f3a28062961406c5b0ff Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 16:22:03 -0800 Subject: [PATCH 01/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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/24] 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); From d40ddddc7c6f4b200fba2e42f03f035f1c3a23a7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 07:23:27 -0800 Subject: [PATCH 19/24] Use the interface language for UI font fallback --- apps/vectorcraft-web/src/web.rs | 3 +- apps/vectorcraft/src/main.rs | 9 ++-- crates/ui-egui/src/app.rs | 3 ++ crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/ui_fonts.rs | 80 ++++++++++++++++++++++++++++++++- 5 files changed, 89 insertions(+), 8 deletions(-) diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 64a596e5ba..519056ba0c 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option std::process::ExitCode { Some(pen) => spec.pen(pen), None => spec, }; - embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?; - egui_extras::install_image_loaders(ctx); let folders = settings.lock().get().ui.last_folders.clone(); let wake = { let ctx = ctx.clone(); @@ -848,7 +846,6 @@ fn main() -> std::process::ExitCode { .settings(Arc::new(settings.clone())) .files(files.clone()) .build(); - host.clone().install(ctx); let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); @@ -873,12 +870,16 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_proof_setups(&mut session); prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(winit_window.clone())); + load_prefs(&mut app, &settings); + let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None); + embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?; + egui_extras::install_image_loaders(ctx); + host.clone().install(ctx); app.host = Arc::new(host); app.adopt_context(&cc.egui_ctx); // A nightly is updated by the Launcher: it never checks for a stable release, which // would install this program's own updater over the nightly build. app.set_startup_update_check(!nightly); - load_prefs(&mut app, &settings); safe_mode::after_start(&mut app, stopped); // Loads started later (a preference change, the end of Safe Mode) are waited for, // after the launch's own. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 228a01b2f6..2fe54745e7 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -410,6 +410,9 @@ impl VectorcraftApp { let lang = self.ui_language(); if self.host.lang() != lang { self.host = Arc::new(self.host.with_lang(lang)); + if let Some(ctx) = &self.ui_ctx { + crate::ui_fonts::follow_language(ctx, lang); + } } let native_ppp = self.ui_ctx.as_ref().map_or(1.0, |ctx| ctx.pixels_per_point() / ctx.zoom_factor()); // The canvas steps through the zoom stops of the current window's display. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3cd948fce0..8b24682035 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -129,7 +129,7 @@ pub use caches::{CacheKey, CanvasCache, LivePaintGapsCache, Perf, PlacedKey, Pri #[cfg(test)] pub(crate) use services::browsable_url; pub use services::{DownloadFn, ExistsFn, Inbox, ReadFn, SaveStreamFn, SaveWriteFn, ScreenDensity, ScreenPpi, Services, WriteFn}; -pub use ui_fonts::ui_fonts; +pub use ui_fonts::{configure_ui_fonts, ui_fonts}; pub struct VectorcraftApp { pub session: Session, diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 0e00238ab4..f01e7dbcb8 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -1,10 +1,12 @@ //! The app's interface font stack: the craft faces it embeds (Japanese, Georgian, Devanagari, //! Gujarati), JetBrains Mono for monospace, and the framework's loader for every other script. -//! The stack is installed once by the shell (`embed::install`). +//! The shell installs the stack at startup and refreshes it when the interface language changes. use std::sync::Arc; -use craft::ui::fonts::{Family, I18nScripts, SEMIBOLD, UiFonts}; +use craft::ui::fonts::{Family, FontFetcher, I18nScripts, SEMIBOLD, UiFonts}; + +use crate::i18n::{Lang, LangExt}; /// The interface fonts configuration. Characters no face covers are looked up in the installed /// system fonts on native; the web build has the faces its server offers instead. @@ -22,6 +24,49 @@ pub fn ui_fonts() -> UiFonts<'static> { } } +#[derive(Clone)] +struct FontSelection { + language: Lang, + fetcher: Option>, +} + +impl FontSelection { + fn fonts(&self) -> UiFonts<'static> { + let fonts = ui_fonts().ui_language(self.language.code()); + match &self.fetcher { + Some(fetcher) => fonts.fetcher(Arc::clone(fetcher)), + None => fonts, + } + } +} + +fn font_selection_id() -> egui::Id { + egui::Id::new("vectorcraft-interface-font-selection") +} + +/// Builds the shell's initial font configuration and keeps its language and font fetcher with +/// this context so they can be reused when the interface language changes. +pub fn configure_ui_fonts(ctx: &egui::Context, language: Lang, fetcher: Option>) -> UiFonts<'static> { + let selection = FontSelection { language, fetcher }; + let fonts = selection.fonts(); + ctx.data_mut(|data| data.insert_temp(font_selection_id(), Some(selection))); + fonts +} + +pub(crate) fn follow_language(ctx: &egui::Context, language: Lang) { + let changed = ctx.data_mut(|data| { + let selection = data.get_temp_mut_or_default::>(font_selection_id()).as_mut()?; + if selection.language == language { + return None; + } + selection.language = language; + Some(selection.clone()) + }); + if let Some(selection) = changed { + selection.fonts().install(ctx); + } +} + #[cfg(test)] mod tests { use craft::ui::fonts::{FontRef, Sample, UiFonts, assert_covers, missing_glyphs}; @@ -53,6 +98,37 @@ mod tests { assert_covers(&ui_fonts().stack(), [Sample::new("ja", "japanese", JAPANESE)]); } + #[test] + fn han_fonts_follow_the_interface_language() { + if !embeds("Hans") || !embeds("Jpan") { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + app.session.prefs.interface_language = "zh-hans".into(); + configure_ui_fonts(&ctx, app.ui_language(), None).install(&ctx); + + for (language, preferred, alternate) in [ + (None, "Noto Sans CJK SC", "BIZ UDPGothic"), + (Some("ja"), "BIZ UDPGothic", "Noto Sans CJK SC"), + (Some("zh-hans"), "Noto Sans CJK SC", "BIZ UDPGothic"), + ] { + if let Some(language) = language { + crate::menus::run_ui_command(&mut app, "app.language", &serde_json::json!({"lang": language})).unwrap().unwrap(); + } + crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |_, ui| { + ui.ctx().fonts(|fonts| { + let chain = &fonts.definitions().families[&egui::FontFamily::Proportional]; + let index = |family: &str| { + chain.iter().position(|face| face.starts_with(family)).unwrap_or_else(|| panic!("missing {family} in {chain:?}")) + }; + assert!(index(preferred) < index(alternate), "expected {preferred} before {alternate} in {chain:?}"); + }); + }); + } + } + #[test] fn the_ui_works_without_the_craft_fonts() { let stack = UiFonts::new(&I18nScripts).stack(); From f7e35d15bc2f6c8b637d68a7d6df633a3f47545a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 30 Nov 2026 07:42:23 -0800 Subject: [PATCH 20/24] Use the supported egui context data key constructor --- crates/ui-egui/src/ui_fonts.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index f01e7dbcb8..77520c39dd 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -41,7 +41,7 @@ impl FontSelection { } fn font_selection_id() -> egui::Id { - egui::Id::new("vectorcraft-interface-font-selection") + egui::Id::unique("vectorcraft-interface-font-selection") } /// Builds the shell's initial font configuration and keeps its language and font fetcher with From 7dad97e83699740a05ccc0c09aa314027a9323c9 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 2 Dec 2026 02:09:23 +0800 Subject: [PATCH 21/24] fix(ai): normalize and outline incompatible dash patterns --- crates/eps/src/ai_editing/tests.rs | 163 +++++++++++++++++++- crates/eps/src/ai_editing/writer.rs | 2 +- crates/eps/src/ai_editing/writer/blends.rs | 2 +- crates/eps/src/ai_editing/writer/brushes.rs | 4 +- crates/eps/src/ai_editing/writer/paints.rs | 3 +- crates/eps/src/ai_editing/writer/styles.rs | 12 +- crates/eps/src/ai_editing/writer/texts.rs | 4 +- crates/eps/src/ai_ops.rs | 25 ++- crates/eps/src/legacy_ai.rs | 3 +- crates/eps/src/legacy_ai/encoding.rs | 7 +- 10 files changed, 209 insertions(+), 16 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 8c3b4ad12d..e1c2efd046 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -8,7 +8,7 @@ use vectorcraft_doc::{ Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, OpacityMask, StrokeLayer, Symbol, }; -use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; +use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, shapes}; use super::*; @@ -1020,6 +1020,167 @@ fn hidden_layers_open_hidden() { assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}"); } +fn dash_painted_nodes(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push((**n).clone()), + _ => { + if let Some(children) = n.children() { + dash_painted_nodes(children, out); + } + } + } + } +} + +/// Original synthetic rectangle, independent of the artwork in #10476. +fn dash_compat_document(pattern: Vec) -> Document { + let mut doc = Document::new(200.0, 100.0); + let mut stroke = StrokeLayer::new(solid(Color::BLACK), 4.0); + stroke.dash = Some(Dash { pattern, offset: 2.5, align_corners: false }); + stroke.overprint = true; + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))), AppearanceItem::Stroke(stroke)], + ..Appearance::default() + }; + let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 180.0, 80.0)), ap); + doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap(); + doc +} + +fn ai_dash_outputs(doc: &Document) -> Vec<(String, Vec, Document)> { + let out = export_ai_editing(doc, &opts()).unwrap(); + let legacy = crate::export_legacy_ai(doc, &crate::LegacyAiOptions::default()).unwrap(); + let legacy_back = crate::import(&legacy.bytes).unwrap().document; + vec![ + (String::from_utf8(out.program).unwrap().replace("\r\n", "\n"), out.warnings, read_back(doc)), + (String::from_utf8(legacy.bytes).unwrap().replace("\r\n", "\n"), legacy.warnings, legacy_back), + ] +} + +#[test] +fn ai_dash_lists_reduce_repetitions_and_keep_small_patterns_editable() { + for (pattern, emitted) in [ + (vec![33.5673; 5], "[33.5673] 2.5 d"), + (vec![33.5673; 10], "[33.5673] 2.5 d"), + (vec![3.0, 2.0, 1.0, 3.0, 2.0, 1.0, 3.0, 2.0, 1.0], "[3 2 1] 2.5 d"), + (vec![0.25], "[0.25] 2.5 d"), + (vec![0.25, 0.5], "[0.25 0.5] 2.5 d"), + (vec![3.0, 2.0, 1.0], "[3 2 1] 2.5 d"), + (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0], "[3 2 1 2 3 4] 2.5 d"), + ] { + let doc = dash_compat_document(pattern.clone()); + for (text, warnings, back) in ai_dash_outputs(&doc) { + assert!(text.contains(emitted), "{pattern:?}: missing {emitted}: {text}"); + assert!(warnings.is_empty(), "{pattern:?}: {warnings:?}"); + let mut art = vec![]; + dash_painted_nodes(&back.layers, &mut art); + assert_eq!(art.len(), 1); + let st = art[0].appearance.stroke().unwrap(); + assert_eq!(st.width, 4.0); + assert!(st.overprint); + assert_eq!(st.dash.as_ref().unwrap().offset, 2.5); + let got = &st.dash.as_ref().unwrap().pattern; + for i in 0..pattern.len() * got.len() * 2 { + assert_eq!(pattern[i % pattern.len()], got[i % got.len()]); + } + assert!(art[0].appearance.fill().is_some()); + } + assert_eq!(doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap().dash.as_ref().unwrap().pattern, pattern); + } +} + +#[test] +fn ai_dash_lists_that_exceed_six_effective_lengths_are_outlined_with_a_warning() { + for pattern in [vec![3.0, 2.0, 1.0, 2.0, 3.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]] { + let doc = dash_compat_document(pattern); + let original = &doc.layers[0].children().unwrap()[0]; + let path = original.path_data().unwrap(); + let expected = vectorcraft_effects::stroke::outline_region(path, FillRule::NonZero, original.appearance.stroke().unwrap()).to_bezpath(); + for (text, warnings, back) in ai_dash_outputs(&doc) { + assert!(warnings.iter().any(|w| w.contains("filled outlines")), "{warnings:?}"); + assert!( + !text.lines().filter(|l| l.ends_with(" d")).any(|l| { + let array = l.rsplit_once('[').unwrap().1.split(']').next().unwrap(); + let n = array.split_whitespace().count(); + n > 6 || (n % 2 == 1 && n * 2 > 6) + }), + "{text}" + ); + let mut art = vec![]; + dash_painted_nodes(&back.layers, &mut art); + assert!(art.iter().all(|n| n.appearance.stroke().is_none()), "{art:?}"); + assert_eq!(art.len(), 2, "fill and outlined stroke keep their paint order"); + assert_eq!(art[0].appearance.fill().unwrap().paint, solid(Color::rgb(0.0, 1.0, 0.0))); + let fill = art[1].appearance.fill().unwrap(); + assert_eq!(fill.paint, solid(Color::BLACK)); + assert!(fill.overprint); + let got = art[1].stroke_path().unwrap(); + for y in 5..85 { + for x in 5..185 { + let p = vectorcraft_geom::Point::new(f64::from(x) + 0.123, f64::from(y) + 0.123); + assert_eq!(got.winding(p) != 0, expected.winding(p) != 0, "at {p:?}"); + } + } + } + } +} + +#[test] +fn ai_dash_lists_in_linked_styles_also_respect_the_reader_limit() { + for (pattern, live) in [(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false), (vec![33.5673; 5], true)] { + let mut doc = dash_compat_document(pattern); + let n = Arc::make_mut(&mut Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap()[0]); + n.appearance.stroke_mut().unwrap().overprint = false; + n.extras_mut().graphic_style = Some(7); + let mut style = vectorcraft_doc::GraphicStyle::new("Dashed", (*n.appearance).clone()); + style.id = 7; + doc.graphic_styles.push(style); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let text = String::from_utf8(out.program).unwrap(); + assert!(!text.contains("[3 2 1 2 3 4 5 6]"), "a style dictionary must not keep an incompatible dash list"); + if live { + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert!(text.contains("1 (Dashed) XW"), "an equivalent dash representation keeps the style link"); + assert!(text.contains("[33.5673] 2.5 d")); + } else { + assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings); + } + } +} + +#[test] +fn ai_dash_lists_in_legacy_text_reduce_or_outline_without_becoming_solid() { + use vectorcraft_doc::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + // Existing licensed test face, with original single-letter artwork. + vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()); + for (pattern, live) in [(vec![33.5673; 5], true), (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false)] { + let mut doc = Document::new(200.0, 100.0); + let st = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 48.0, + fill: solid(Color::rgb(0.0, 1.0, 0.0)), + stroke: solid(Color::BLACK), + stroke_width: 2.0, + stroke_dash: Some(Dash { pattern, offset: 2.5, align_corners: false }), + ..CharStyle::default() + }; + let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "T", st); + let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap(); + let out = crate::export_legacy_ai(&doc, &crate::LegacyAiOptions::default()).unwrap(); + let text = String::from_utf8(out.bytes).unwrap().replace("\r\n", "\n"); + assert_eq!(text.contains("0 To\n"), live, "irreducible type strokes must take the outline fallback"); + if live { + assert!(text.contains("[33.5673] 2.5 d")); + } else { + assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings); + assert!(text.matches("\nf\n").count() >= 2, "the glyph's fill and dashed stroke are both painted"); + } + } +} + /// A 200 × 100 document of a gradient fill, a compound path, an image and a symbol instance, and /// what the data holds as plain paths: type. fn unsupported() -> Document { diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index b8ea88a1fd..1a6f0243cb 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -71,7 +71,7 @@ pub(super) const LIVE: &str = "repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps"; pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; -pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; +pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = "the opacity and blending modes of single fills and strokes are left out of the editing data for other apps"; pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps"; diff --git a/crates/eps/src/ai_editing/writer/blends.rs b/crates/eps/src/ai_editing/writer/blends.rs index b73749b214..11dad18d4c 100644 --- a/crates/eps/src/ai_editing/writer/blends.rs +++ b/crates/eps/src/ai_editing/writer/blends.rs @@ -364,7 +364,7 @@ fn plain_key(k: &Node) -> bool { && i.effects().is_empty() && i.opacity() >= 1.0 && i.blend() == BlendMode::Normal - && !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s)) + && !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s) || !dash_read_back(s)) }); plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none(); }); diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index c24dbdf1d7..9bd9457de5 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -258,7 +258,7 @@ fn plain_within(art: &Node, masks: u32) -> bool { && i.opacity() >= 1.0 && i.blend() == BlendMode::Normal && matches!(i.paint(), Paint::Solid { .. } | Paint::None) - && !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s)) + && !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s)) }); // A group's own fills and strokes aren't written. let group_paint = matches!(n.kind, NodeKind::Group { .. }) && items.iter().any(|i| !i.paint().is_none()); @@ -519,7 +519,7 @@ impl Writer<'_> { let name = st.brush.as_deref()?; self.brush_set(); let (plugin, kind) = self.live_brush(name).map(|b| (b.plugin, b.brush.kind.clone()))?; - if !matches!(st.paint, Paint::Solid { .. }) || st.overprint { + if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) { return None; } let ops = self.color_ops(&st.paint, true); diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index f1573c39ba..b97dd593cb 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -8,7 +8,6 @@ use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType}; -use vectorcraft_effects::stroke; use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; use super::{MAX_NEST, Writer, Xy}; @@ -367,7 +366,7 @@ impl Writer<'_> { /// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can /// write it)? pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool { - self.direct(&s.paint) && stroke::is_plain(s) + self.direct(&s.paint) && crate::ai_ops::plain_stroke(s) } /// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 27ddf48be0..03f7e4b0e1 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -404,7 +404,7 @@ impl Writer<'_> { if st.brush.is_some() { return self.brush_filter(s, st, visible); } - if !matches!(st.paint, Paint::Solid { .. }) || st.overprint { + if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) { return None; } let ops = self.color_ops(&st.paint, true); @@ -1077,6 +1077,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) -> let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count(); ap.items.retain(|i| !i.paint().is_none()); ap.contents_index = (below > 0).then_some(below); + // The writer shortens repeated dash lists without changing their painted period. + // Compare those representations equally so a linked style can stay live. + for i in &mut ap.items { + if let AppearanceItem::Stroke(st) = i + && let Some(d) = st.dash.as_mut().filter(|d| d.is_dashed()) + && let Some(pattern) = ai_ops::dash_pattern(&d.pattern) + { + d.pattern = pattern.to_vec(); + } + } for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { e.params = normalized_params(e); } diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index b6941e4730..8255a3447a 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -425,8 +425,8 @@ fn plain_wrap_art(n: &Node, styled: &HashMap>) -> bool { let painted = || match super::visible_items(n).as_slice() { [] => true, [AppearanceItem::Fill(f)] => solid(&f.paint), - [AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), - [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + [AppearanceItem::Stroke(s)] => solid(&s.paint) && crate::ai_ops::plain_stroke(s), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && crate::ai_ops::plain_stroke(s), _ => false, }; let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2); diff --git a/crates/eps/src/ai_ops.rs b/crates/eps/src/ai_ops.rs index 9d0ff5ddc0..afc0d2ae71 100644 --- a/crates/eps/src/ai_ops.rs +++ b/crates/eps/src/ai_ops.rs @@ -179,7 +179,28 @@ pub(crate) fn window_samples(samples: &[u8], w: u32, channels: usize, [x0, y0, x out } -/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. +/// The shortest equivalent dash list the AI reader can hold. Odd lists repeat twice before +/// dash/gap parity repeats. Keep at most six effective lengths: longer lists can make the +/// reader reject the entire file (#10476). Compare exactly, so no dash or gap changes length. +pub(crate) fn dash_pattern(pattern: &[f64]) -> Option<&[f64]> { + (1..=pattern.len().min(6)) + .filter(|n| n % 2 == 0 || *n <= 3) + .find(|n| pattern.len().is_multiple_of(*n) && pattern.iter().enumerate().all(|(i, v)| *v == pattern[i % n])) + .map(|n| &pattern[..n]) +} + +/// Invalid or empty dashes already draw solid; valid dashes need an exact short representation. +pub(crate) fn dash_fits(st: &StrokeLayer) -> bool { + st.dash.as_ref().filter(|d| d.is_dashed()).is_none_or(|d| dash_pattern(&d.pattern).is_some()) +} + +/// A plain AI stroke, including the reader's dash-list limit. Other strokes use filled outlines. +pub(crate) fn plain_stroke(st: &StrokeLayer) -> bool { + vectorcraft_effects::stroke::is_plain(st) && dash_fits(st) +} + +/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. Callers check +/// [`dash_fits`] first; irreducible longer patterns belong in their outline fallback. pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) { let cap = match st.cap { LineCap::Butt => ps::LineCap::Butt, @@ -191,6 +212,6 @@ pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) { LineJoin::Round => ps::LineJoin::Round, LineJoin::Bevel => ps::LineJoin::Bevel, }; - let dash = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| (d.pattern.as_slice(), d.offset)); + let dash = st.dash.as_ref().filter(|d| d.is_dashed()).and_then(|d| dash_pattern(&d.pattern).map(|p| (p, d.offset))); ps::push_line_style(s, st.width, cap, join, st.miter_limit, dash); } diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 8fbfcf3e83..a41c7dc442 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -125,8 +125,7 @@ const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in pro const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGES: usize = 360; -const STROKES: &str = - "strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines"; +const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, gradients, brushes, arrowheads) are written as filled outlines"; const IMAGE_ALPHA: &str = "transparent image pixels are written over white"; const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art"; const DEEP_DISTORTED: &str = diff --git a/crates/eps/src/legacy_ai/encoding.rs b/crates/eps/src/legacy_ai/encoding.rs index a1c40ca28f..65825a6b2e 100644 --- a/crates/eps/src/legacy_ai/encoding.rs +++ b/crates/eps/src/legacy_ai/encoding.rs @@ -1,7 +1,7 @@ use super::writer::Writer; use super::{ Affine, AreaOptions, BezPath, CharPosition, CharStyle, CompositeFont, Document, Gradient, GradientKind, Paint, ParaStyle, PathAlign, PathEffect, - StrokeLayer, TextKind, TextObject, Write, latin, ps, stroke, + StrokeLayer, TextKind, TextObject, Write, latin, ps, }; /// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd`, `[`, the stops @@ -111,6 +111,9 @@ pub(super) fn holds_as_text(t: &TextObject) -> bool { r.inline.is_none() && solid(&r.style.fill) && solid(&r.style.stroke) + // Long dash lists can reject the entire AI file. Keep their glyph paint by + // taking the existing type-outline path instead of writing a solid stroke. + && (!r.style.has_stroke() || crate::ai_ops::dash_fits(&r.style.stroke_layer())) && (if r.style.all_caps { r.text.to_uppercase() } else { r.text.clone() }).chars().all(|c| latin::encode(c).is_some()) }) } @@ -221,5 +224,5 @@ pub(super) fn direct_fill(p: &Paint) -> bool { /// Can stroke `s` be written as the stroke of a path object (a plain line of a colour)? pub(super) fn direct_stroke(s: &StrokeLayer) -> bool { - matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s) + matches!(s.paint, Paint::Solid { .. }) && crate::ai_ops::plain_stroke(s) } From 750bf94b597209ee6b6bedd3d98a9a10252ba962 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 2 Dec 2026 19:33:51 +0530 Subject: [PATCH 22/24] Web: Gujarati can be chosen as the interface language The web build had no Gujarati face, so it never offered Gujarati: the language gate looked only at embedded craft-fonts faces, and web builds embed only BIZ UDPGothic. - crates/text/web-fonts.txt lists Noto Sans Gujarati Regular as a `demand` face, like Noto Sans Devanagari for Hindi: served beside the wasm under fonts/ui/ and fetched by the interface font stack when its text needs Gujarati, never at startup or in the background queue. - The Gujarati gate counts an embedded Gujarati face, or on the web a served one (SERVED_FONTS); desktop behaviour is unchanged. - Tests: web_fonts_follow_the_list expects the new demand face; web_offers_gujarati_with_the_served_gujarati_face checks that a web build with only the served face offers `gu`; web_gujarati_face_covers_the_gujarati_catalog checks that the served face alone draws every Gujarati character of the catalog. Docs: gaps.md (G16), localization-parity.md, roadmap.md, target-app-parity.md. --- crates/text/src/craft_fonts.rs | 9 ++++++--- crates/text/web-fonts.txt | 3 ++- crates/ui-egui/src/i18n.rs | 22 +++++++++++++++++++--- crates/ui-egui/src/i18n/tests.rs | 17 +++++++++++++++++ crates/ui-egui/src/ui_fonts.rs | 22 ++++++++++++++++++++++ docs/gaps.md | 4 +++- docs/localization-parity.md | 5 +++-- docs/roadmap.md | 7 ++++--- docs/target-app-parity.md | 5 +++-- 9 files changed, 79 insertions(+), 15 deletions(-) diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 28b2dc2662..0714822b7b 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -171,10 +171,13 @@ mod tests { let expected: Vec<_> = ["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); assert_eq!(startup, expected); - // Korean and Devanagari faces are fetched only on demand, never at startup or in the - // background queue every session runs. + // Korean, Devanagari and Gujarati faces are fetched only on demand, never at startup or in + // the background queue every session runs. let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect(); - let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); + let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari", "Noto Sans Gujarati"] + .into_iter() + .filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)) + .collect(); assert_eq!(demand, expected); assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand))); } diff --git a/crates/text/web-fonts.txt b/crates/text/web-fonts.txt index d46cfe41c5..67144e95ad 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -3,10 +3,11 @@ # startup = fetched before the app starts (fallbacks the first frame needs) # background = fetched after the app starts (fonts users pick by name) # demand = fetched only when the interface language or the interface's own text needs one of -# the face's scripts (Korean, Hindi) +# the face's scripts (Korean, Hindi, Gujarati) # Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook). startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular startup | Noto Sans Georgian | Regular demand | NanumGothic | Regular demand | Noto Sans Devanagari | Regular +demand | Noto Sans Gujarati | Regular diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 5ea3433c56..b515cb802e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -74,17 +74,33 @@ static EMBEDDED: &Embedded = &[ /// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font /// fallback, so on the web a language whose text would be missing-glyph boxes (Gujarati without a -/// bundled Gujarati face) is not offered, including when restoring a preference. Arabic is kept -/// unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed. +/// Gujarati face, see [`has_gujarati_face`]) is not offered, including when restoring a preference. +/// Arabic is kept unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed. fn offered_codes(web: bool, gujarati_font: bool) -> Vec<&'static str> { EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect() } +/// Whether the interface has a Gujarati face: an embedded craft-fonts face, or on the web a face +/// the interface font stack serves (`SERVED_FONTS`, the `startup` and `demand` lines of +/// `crates/text/web-fonts.txt`) and fetches when Gujarati text needs it. +fn has_gujarati_face() -> bool { + #[cfg(target_arch = "wasm32")] + let served = vectorcraft_text::SERVED_FONTS.iter().map(|f| f.scripts); + #[cfg(not(target_arch = "wasm32"))] + let served = std::iter::empty(); + has_gujarati_face_in(vectorcraft_text::CRAFT_FONTS, served) +} + +/// [`has_gujarati_face`] for the given embedded faces and the scripts of each served face. +fn has_gujarati_face_in<'a>(embedded: &[vectorcraft_text::EmbeddedFace], mut served: impl Iterator) -> bool { + embedded.iter().any(|f| f.has_script("Gujr")) || served.any(|scripts| scripts.contains(&"Gujr")) +} + /// The one catalog set of the process, built on first use. fn shared_cell() -> &'static Arc { static SHARED: OnceLock> = OnceLock::new(); SHARED.get_or_init(|| { - let offered = offered_codes(cfg!(target_arch = "wasm32"), vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr"))); + let offered = offered_codes(cfg!(target_arch = "wasm32"), has_gujarati_face()); let (i18n, problems) = I18n::new(EMBEDDED, &offered); for problem in problems { log::warn!("vectorcraft: interface language catalog: {problem}"); diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 3dca49857f..cd2edc0e73 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -159,6 +159,23 @@ fn gujarati_web_selection_requires_a_bundled_interface_font() { assert!(codes(true, false).contains(&"hi".to_string())); } +/// The web build embeds no Gujarati face, but serves Noto Sans Gujarati on demand: the web's +/// served faces are the `startup` and `demand` lines of `crates/text/web-fonts.txt`, so the web +/// offers Gujarati. Checked where the craft-fonts checkout has the face. +#[test] +fn web_offers_gujarati_with_the_served_gujarati_face() { + if !vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr")) { + eprintln!("skipped: built without craft-fonts, or one without a Gujarati face"); + return; + } + let served = || vectorcraft_text::WEB_FONTS.iter().filter(|w| w.startup || w.demand).map(|w| w.scripts); + let web_embedded: Vec<_> = vectorcraft_text::CRAFT_FONTS.iter().filter(|f| !f.has_script("Gujr")).copied().collect(); + let font = has_gujarati_face_in(&web_embedded, served()); + assert!(font, "a served Gujarati face counts on the web"); + assert!(offered_codes(true, font).contains(&"gu")); + assert!(!has_gujarati_face_in(&web_embedded, std::iter::empty()), "without it, nothing draws Gujarati on the web"); +} + /// A numbered built-in name shows its name before the number translated and the number as it /// is; a name with a row of its own uses that row, and any other name comes back unchanged. #[test] diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 0e00238ab4..51ba07f094 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -44,6 +44,28 @@ mod tests { assert_covers(&ui_fonts().stack(), [Sample::new("hi", "hindi", HINDI)]); } + /// The face the web serves for Gujarati (a `demand` line of `crates/text/web-fonts.txt`) draws + /// every Gujarati character of the Gujarati catalog on its own, as on the web, which has no + /// other Gujarati face. + #[test] + fn web_gujarati_face_covers_the_gujarati_catalog() { + if !embeds("Gujr") { + eprintln!("skipped: built without craft-fonts, or one without a Gujarati face"); + return; + } + let served: Vec<_> = vectorcraft_text::CRAFT_FONTS + .iter() + .filter(|f| { + vectorcraft_text::WEB_FONTS.iter().any(|w| w.demand && w.scripts.contains(&"Gujr") && w.family == f.family && w.style == f.style) + }) + .copied() + .collect(); + assert!(!served.is_empty(), "the web serves a Gujarati face (a `demand` line of web-fonts.txt)"); + let gujarati: String = include_str!("i18n/gu.tsv").chars().filter(|c| ('\u{0A80}'..='\u{0AFF}').contains(c)).collect(); + assert!(!gujarati.is_empty()); + assert_covers(&UiFonts::new(&I18nScripts).craft_faces(&served).stack(), [Sample::new("gu", "gu.tsv", &gujarati)]); + } + #[test] fn japanese_renders_with_the_craft_fonts_without_installed_fonts() { if !embeds("Jpan") { diff --git a/docs/gaps.md b/docs/gaps.md index 671283d648..b256618e77 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -948,7 +948,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** Arabic catalog and right-to-left layout; current gaps in other catalogs and native review; Hindi wording/layout review. The web build fetches NanumGothic for Korean and Noto Sans - Devanagari for Hindi when the interface needs them (`crates/text/web-fonts.txt`, `demand`). + Devanagari for Hindi and Noto Sans Gujarati for Gujarati when the interface needs them + (`crates/text/web-fonts.txt`, `demand`). Hindi now has a catalog and the pinned egui fork shapes Devanagari. Indonesian already has a catalog (see [localization-parity.md](localization-parity.md)); it is not an absent language. - **Estimate:** 50–85 h plus human review (Brazilian Portuguese completed 2026-10-14). @@ -1049,6 +1050,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | G16: Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-27 | minor | G4 type: Language packs (#4936): spelling and hyphenation read the packs installed in the Craft apps' shared font store, and `proof.packs`, `proof.installPack` and `proof.removePack` list, install and remove them (installs need downloading on, which only the person turns on); a Preferences page to install them and the missing-pack bar remain; scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index fe10d21a97..428fbec0f6 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -24,7 +24,7 @@ English) in-app help, and the docs are English. (`bflatastic`), with community contributors adding or correcting (German by `dwetscher`, Japanese and Traditional Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded as reviewed by native speakers; the contributor approved all 387 later Gujarati additions on 2026-11-14. -> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, but the web startup list contains no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. +> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged. ## The thirteen key languages @@ -34,7 +34,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | Simplified Chinese (Mandarin) | `zh-hans` | 9,625 rows, 3,735 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`) | all (the untranslated report lists 237 messages without a row for it) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) | | Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | -| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); not in the web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | +| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); the web fetches Noto Sans Gujarati when the interface needs it | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages | | Arabic | `ar` | preparatory registration (native name العربية) and 6-form CLDR plural probe only; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) and not yet consumed | none (UI not exposed pending shared catalog) | document text: existing bidirectional layout and paragraph direction; interface UI: not exposed pending shared catalog, with full shell mirroring pending STD-I18N-001 | — (preparatory) | preparatory (not exposed) | 15–20 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | @@ -101,6 +101,7 @@ font for the web build. | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-25 | patch | Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; kept unavailable to users pending upstream `storytold/craft-i18n` catalog | | 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. | | 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) | diff --git a/docs/roadmap.md b/docs/roadmap.md index f669559fd2..3a2b13abda 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -28,7 +28,7 @@ > Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. -> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. +> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged. ## Feature submission evidence @@ -169,7 +169,7 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V Hindi interface follow-up (2026-11-06): the catalog and zero/one plural rule are implemented; native wording review, layout checks and a web Devanagari font remain. [Notes](localization-hi.md). -Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule are implemented. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and a bundled Gujarati web font remains to be supplied. +Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule are implemented. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so Gujarati can be selected on the web. ## Current focus @@ -214,7 +214,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | -| M14 follow-up | Gujarati interface (#6613) | 🟡 Zero/one singular plurals and desktop font fallback; 4,673 contributor-reviewed rows, including 387 approved additions with 11 wording corrections; status/error messages remain partial and pinned fonts lack a Gujarati face | Included above | +| M14 follow-up | Gujarati interface (#6613) | 🟡 Zero/one singular plurals and desktop font fallback; 4,673 contributor-reviewed rows, including 387 approved additions with 11 wording corrections; status/error messages remain partial; the web fetches Noto Sans Gujarati on demand | Included above | | | **Total to full parity** (one agent; from [target-app-parity.md](target-app-parity.md)) | | **~360–590** | Milestone estimates predate the 2026-10-10 re-measure for M1–M14; the area table in @@ -254,6 +254,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a2d5bcd1..1cd0e83cb5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -37,7 +37,7 @@ Native saves on Unix flush the destination directory after writing or replacing > Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged. -> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged. +> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged. ## Feature submission evidence @@ -1267,7 +1267,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Swedish messages (2026-11-13): the Swedish (`sv`) catalog has an `@msg` row for 464 of the 628 status and error messages the untranslated report listed for it; 162 messages that no complete-message catalog translates, 36 composite font errors among them, are not translated yet, and two unknown-parameter errors that start with the `{within}` placeholder stay in English, as does `{name} must be {lo}–{hi}{unit} (got {v})`, whose existing row can't match because two of its placeholders sit side by side; the rows keep their placeholders, backticked names, quoted values and command ids; native review remains; scores and estimates unchanged. - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and workspaces keep the setting. A floating Tools panel dropped on the canvas's left edge, right of panels docked on the left, docks there and turns the setting on, and one dropped on the window's left edge docks there and turns it off; with no panels docked on the left, a drop leaves the setting as it is (#7837). Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows`, `tools_dropped_where_the_left_edges_overlap_keep_the_setting`, `tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial; the pinned fonts and web startup list have no Gujarati face, so web selection remains unavailable until one is bundled. Current-head validation is recorded in the PR; scores and estimates unchanged. + - Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so Gujarati can be selected on the web. Current-head validation is recorded in the PR; scores and estimates unchanged. - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged. - Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged. @@ -3425,6 +3425,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. | | 2026-11-26 | minor | #8744: native-canvas sampler-owned release/Zoom regression source, retaining ordinary navigation, dock rejection, accepted sampling, document/selection/paint/history controls and no idle replay. Runtime pending; scores, gaps and hours unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. | From 4fd3d9f22d83ec1aeb72268bd714bb7a7ab4904c Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 3 Dec 2026 21:32:54 +0530 Subject: [PATCH 23/24] xtask: a test packages the real web-font list and checks every served face, Gujarati included With a craft-fonts checkout in CRAFT_FONTS_DIR, the Trunk hook runs on crates/text/web-fonts.txt into a temporary site, and every startup and demand face must be under fonts/ui/ with the bytes the craft-fonts manifest hashes. It skips without a checkout unless CRAFT_FONTS_REQUIRED=1. --- xtask/src/web_fonts.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/xtask/src/web_fonts.rs b/xtask/src/web_fonts.rs index d30ef58c8e..8ce093bd2b 100644 --- a/xtask/src/web_fonts.rs +++ b/xtask/src/web_fonts.rs @@ -218,6 +218,39 @@ mod tests { assert!(at.join("LICENSE.txt").exists() && !at.join("LICENSE.html").exists()); } + /// The real hook on the real list: every `startup` and `demand` face (Gujarati included) lands + /// in the packaged site under `fonts/ui/`, byte for byte the file the craft-fonts manifest + /// hashes. Needs a craft-fonts checkout in `CRAFT_FONTS_DIR`; skips without one unless + /// `CRAFT_FONTS_REQUIRED=1`. + #[test] + fn the_packaged_site_serves_every_interface_face_as_the_manifest_hashes_it() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); + let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|v| !v.is_empty()).map(PathBuf::from) else { + assert!(std::env::var("CRAFT_FONTS_REQUIRED").as_deref() != Ok("1"), "CRAFT_FONTS_REQUIRED=1 but CRAFT_FONTS_DIR is unset"); + eprintln!("skipping: set CRAFT_FONTS_DIR to a craft-fonts checkout"); + return; + }; + let dir = if dir.is_absolute() { dir } else { root.join(dir) }; + let site = tempfile::tempdir().unwrap(); + run_with(root, Some(dir.clone()), Some(site.path().to_path_buf())).unwrap(); + + let list = std::fs::read_to_string(root.join("crates/text/web-fonts.txt")).unwrap(); + let manifest = std::fs::read_to_string(dir.join("fonts/manifest.txt")).unwrap(); + let mut checked = Vec::new(); + for e in list::parse_list(&list).unwrap().into_iter().filter(|e| e.startup || e.demand) { + let row = manifest + .lines() + .map(|l| l.split(" | ").map(str::trim).collect::>()) + .find(|r| r.first() == Some(&e.family) && r.get(1) == Some(&e.style)); + let Some(row) = row else { continue }; // an older craft-fonts lacks it; build.rs skips it too + let file = row[2].strip_prefix("fonts/").unwrap(); + let bytes = std::fs::read(site.path().join(SERVED_URL).join(file)).unwrap_or_else(|err| panic!("{SERVED_URL}{file}: {err}")); + assert_eq!(sha256::hex(&bytes), row[6], "{SERVED_URL}{file} differs from the manifest"); + checked.push(e.family.to_owned()); + } + assert!(checked.iter().any(|f| f == "Noto Sans Gujarati"), "the Gujarati face was not published: {checked:?}"); + } + #[test] fn without_craft_fonts_the_hook_does_nothing() { let (_, _, site, _) = fixture("noop", None); From 2ec410834b816d79600b94c80fc3eca781d4beaf Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 3 Dec 2026 21:37:52 +0530 Subject: [PATCH 24/24] xtask: the packaged-site test requires the Gujarati face only when craft-fonts has it --- xtask/src/web_fonts.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/xtask/src/web_fonts.rs b/xtask/src/web_fonts.rs index 8ce093bd2b..391a3ee819 100644 --- a/xtask/src/web_fonts.rs +++ b/xtask/src/web_fonts.rs @@ -248,7 +248,10 @@ mod tests { assert_eq!(sha256::hex(&bytes), row[6], "{SERVED_URL}{file} differs from the manifest"); checked.push(e.family.to_owned()); } - assert!(checked.iter().any(|f| f == "Noto Sans Gujarati"), "the Gujarati face was not published: {checked:?}"); + // An older craft-fonts without the Gujarati face stays valid; one that has it must publish it. + if manifest.lines().any(|l| l.starts_with("Noto Sans Gujarati | Regular |")) { + assert!(checked.iter().any(|f| f == "Noto Sans Gujarati"), "the Gujarati face was not published: {checked:?}"); + } } #[test]