From 4d975416335e18db8ac3f3a28062961406c5b0ff Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 28 Nov 2026 16:22:03 -0800 Subject: [PATCH 01/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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/65] 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 7dad97e83699740a05ccc0c09aa314027a9323c9 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 2 Dec 2026 02:09:23 +0800 Subject: [PATCH 19/65] 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 a157987fb75d5d5232bd46f4f6282e516ad3a01e Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:55:38 +0530 Subject: [PATCH 20/65] Script Console: copy output lines from the row menu --- crates/ui-egui/src/panels/script_console.rs | 29 +++++++-- .../src/panels/tests_script_console.rs | 64 +++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 91 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/script_console.rs b/crates/ui-egui/src/panels/script_console.rs index 27925a9ed0..e1adf9473f 100644 --- a/crates/ui-egui/src/panels/script_console.rs +++ b/crates/ui-egui/src/panels/script_console.rs @@ -14,15 +14,15 @@ use serde_json::{Value, json}; use vectorcraft_engine::script::console::{Console, ConsoleLine, Ending, Entry}; // PLAN: assumed paths of the framework items below, re-exported by craft-ui (behavior, theme and keymap types) -use craft::behavior::{DisplayOrder, IconId, ItemSource}; +use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection}; use craft::keymap::CommandRef; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, LeastWidth, Props as _, ScrollAnchor, Show, ShowCollection, ShowContainer, Sizing, clicked}; +use craft::ui::contract::{Bind, CollectionEvent, LeastWidth, Props as _, ScrollAnchor, Show, ShowCollection, ShowContainer, Sizing, clicked}; use craft::ui::layout::RowAlign; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, RowInk}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandState, CommandStates}; @@ -209,11 +209,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { selection.anchor = selection.anchor.take().filter(held); let buttons = buttons(count > 0, !selection.items.is_empty()); let mut picked = None; + let mut menu_command = None; Stack::new().fill().footer(|ui, _| picked = footer(ui, buttons).or(picked)).show(ui, |ui, _| { if let Some(n) = notice(c) { Notice::new(Tone::Info, n).show(ui); } - List::::new(tl!("Script Console")) + let out = List::::new(tl!("Script Console")) + .id(ui.scope_id().with("console-lines")) + .row_menu() .sizing(Sizing::Fill) .scroll_anchor(ScrollAnchor::End) .selection(Bind::bound(&mut *selection)) @@ -227,9 +230,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Entry::Output(_) | Entry::Log(_) => row, } }); + if let Some(line) = out.menu.map(|request| request.key).filter(held) { + // The row's More button can open the menu without a selection gesture. + if out.events.iter().any(|event| matches!(event, CollectionEvent::ContextMenu(_))) && !selection.items.contains(&line) { + *selection = Selection::single(line); + } + Menu::context(tl!("Script Console"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Copy Line")).show(ui).ran { + menu_command = Some((COMMANDS[2], json!({"first": line, "last": line}))); + } + if MenuItem::new(tl!("Copy Selected")).enabled(!selection.items.is_empty()).show(ui).ran { + menu_command = Some((COMMANDS[1], json!({}))); + } + }); + } }); - if let Some(id) = picked { - run_ui(app, id, json!({})); + if let Some((id, params)) = menu_command.or_else(|| picked.map(|id| (id, json!({})))) { + run_ui(app, id, params); } } diff --git a/crates/ui-egui/src/panels/tests_script_console.rs b/crates/ui-egui/src/panels/tests_script_console.rs index 71766dce0a..706b2b965a 100644 --- a/crates/ui-egui/src/panels/tests_script_console.rs +++ b/crates/ui-egui/src/panels/tests_script_console.rs @@ -77,6 +77,70 @@ fn the_console_footer_buttons_run_their_commands_at_minimum_width() { assert!(!panel.enabled("Copy All")); } +#[test] +fn the_row_menu_copies_its_line_or_the_selected_range_while_output_arrives() { + let mut app = app(); + run(&mut app, "$.writeln('one'); $.writeln('two'); $.writeln('three')"); + let mut panel = Panel::new(app, show); + panel.click("#1 c.js: one"); + panel.click_with("#1 c.js: three", egui::Modifiers::SHIFT); + panel.secondary_click("#1 c.js: two"); + run(&mut panel.app(), "$.writeln('later')"); + panel.frame(); + panel.click_menu_item("Copy Line"); + assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: two")); + + panel.secondary_click("#1 c.js: two"); + panel.click_menu_item("Copy Selected"); + assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: one\n#1 c.js: two\n#1 c.js: three")); + + panel.secondary_click("#2 c.js: later"); + panel.click_menu_item("Copy Selected"); + assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#2 c.js: later")); + + panel.secondary_click("#1 c.js: two"); + panel.app().run("script.console.clear", json!({})).unwrap(); + run(&mut panel.app(), "$.writeln('replacement')"); + panel.frame(); + assert!(!panel.shows("Copy Line"), "a replacement at the same row cannot inherit the menu"); +} + +#[test] +fn copy_line_follows_its_number_when_older_output_is_dropped() { + let mut app = app(); + run(&mut app, "$.writeln('first'); $.writeln('target'); $.writeln('next')"); + let mut panel = Panel::new(app, show); + panel.secondary_click("#1 c.js: target"); + + // Fill the console and evict its first line while the menu is open. + let free = vectorcraft_engine::script::console::MAX_CONSOLE_LINES - panel.app().session.script_console().lines().len(); + // Each run also writes a start, an end and a report. + run(&mut panel.app(), &format!("for (var i = 0; i < {}; i++) $.writeln(i)", free - 2)); + assert_eq!(panel.app().session.script_console().first_number(), 1); + panel.frame(); + panel.click_menu_item("Copy Line"); + assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: target")); +} + +#[test] +fn the_focused_console_row_opens_its_menu_from_the_keyboard() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + let mut app = app(); + run(&mut app, "$.writeln('one')"); + let mut panel = Panel::new(app, show); + panel.click("#1 c.js: one"); + let list_focus = panel.ctx().memory(|memory| memory.focused()).expect("the console list has focus"); + + panel.key(Key::F10, Modifiers::SHIFT); + assert!(panel.menu_item_enabled("Copy Line")); + assert!(panel.menu_item_enabled("Copy Selected")); + panel.key(Key::Escape, Modifiers::NONE); + assert!(!panel.shows_role("Copy Line", Role::MENU_ITEM)); + assert_eq!(panel.ctx().memory(|memory| memory.focused()), Some(list_focus)); +} + #[test] fn clear_works_during_a_run_and_the_run_goes_on_writing() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 9a6f721b93..71424b1638 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4315,7 +4315,9 @@ carriage returns and the two together break lines, and other control characters Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. When the console has dropped or cut any lines, a note at the top counts them. The panel lays out only the rows in view. Click a line to select it and Shift-click to extend the selection. Clear, Copy Selected and Copy All are -at the bottom of the panel and in its menu. Output goes on while the panel is closed. +at the bottom of the panel and in its menu. Right-click a selected line to keep the range. Choose Copy Line +to copy just that line, or Copy Selected to copy from the first selected line through the last. Right-clicking +an unselected line selects it. Output goes on while the panel is closed. - `script.console {}` returns `{lines: [{run, name, kind, text}], droppedLines, truncatedLines}`. `run` is the run's number in the session, and `kind` is `start`, `output`, `log`, `error`, `end` or `report`. An end line's text diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index aa49d934ac..6999765821 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1130,7 +1130,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. + - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. A line's menu copies that line or the selected range. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 750bf94b597209ee6b6bedd3d98a9a10252ba962 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 2 Dec 2026 19:33:51 +0530 Subject: [PATCH 21/65] 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 54f19989bcfc27177f8359a321b0575c2143c3af Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 2 Dec 2026 21:27:10 +0530 Subject: [PATCH 22/65] SVG Interactivity: add a context menu to event rows A right-click on an event row, or Shift+F10 on the focused row, picks that event and offers Remove Event, Clear Events and Link JavaScript Files..., the same commands as the footer and the panel menu (G12). --- .../ui-egui/src/panels/svg_interactivity.rs | 163 +++++++++++++++++- docs/gaps.md | 5 +- docs/ui-parity.md | 4 +- 3 files changed, 164 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index 6fe9232bb6..58fadc85a6 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -4,6 +4,9 @@ //! objects' events, and a click on one picks it to edit. Remove Selected Entry //! (`svgInteractivity.removeEvent`) and the panel menu's Clear Events (`svgInteractivity.clearEvents`) //! remove them; Link JavaScript Files… opens the JavaScript Files dialog (`ui.javascriptFilesDialog`). +//! A right-click on an event row (or Shift+F10 on the focused row) picks that event and opens its +//! menu: Remove Event, Clear Events and Link JavaScript Files…, the same commands as the footer and +//! the panel menu. //! Everything reads `svgInteractivity.info`. use std::hash::{DefaultHasher, Hash, Hasher}; @@ -17,7 +20,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Stack; use craft::ui::list::{List, ListRow}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::pickers::Select; use craft::ui::primitives::SubmitKey; use craft::ui::runtime::commands::{CommandState, CommandStates}; @@ -35,6 +38,13 @@ pub const ID: &str = "svgInteractivity"; /// The engine command of the panel menu's one row. const CLEAR_EVENTS: &str = "svgInteractivity.clearEvents"; +/// What the footer or a row's menu picked, run once the list is drawn. +#[derive(Clone, Copy)] +enum RowAction { + Clear, + LinkFiles, +} + /// The SVG Interactivity panel's own state, kept while the app runs. #[derive(Clone, Debug, Default)] pub(crate) struct SvgInteractivityPanel { @@ -134,7 +144,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let rows_stamp = stamp.finish(); let mut remove = None; let mut footer_pick = None; - let has_doc = app.session.active().is_some(); + let mut row_action = None; + let document = app.session.active().map(|st| st.uid); + let has_doc = document.is_some(); + let can_clear = clearable(&info); let listed = events.iter().any(|(e, _)| e == event); Stack::new() .fill() @@ -155,9 +168,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } let selection = if listed { Selection::single(event.to_string()) } else { Default::default() }; let mut list = List::::new(tl!("Events")) + // Each document gets its own list, so a row menu left open closes with the old one. + .id(ui.scope_id().with(("svg-events", document))) .select(SelectMode::Single) .arrows_select(true) .deletable(true) + .row_menu() .rows_stamp(rows_stamp) .selection(Bind::given(selection)) .sizing(Sizing::Fill); @@ -180,12 +196,29 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } CollectionEvent::Activate(key) => pick = Some(key), + // The menu acts on the row it opened on, so that row becomes the picked event. + CollectionEvent::ContextMenu(request) => pick = Some(request.key), CollectionEvent::Delete(_) => { remove = pick.as_deref().or(listed.then_some(event)).map(str::to_owned); } _ => {} } } + // `list.menu` is `None` once its row leaves the list. + if let Some(request) = list.menu { + let key = request.key.clone(); + Menu::context(request.key, &list.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Remove Event")).show(ui).ran { + remove = Some(key.clone()); + } + if MenuItem::new(tl!("Clear Events")).enabled(can_clear).show(ui).ran { + row_action = Some(RowAction::Clear); + } + if MenuItem::new(tl!("Link JavaScript Files…")).enabled(has_doc).show(ui).ran { + row_action = Some(RowAction::LinkFiles); + } + }); + } }); if let Some(e) = pick { let state = &mut app.ui.svg_interactivity_panel; @@ -200,10 +233,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } match footer_pick { Some(0) => remove = Some(event.to_string()), - Some(1) => { + Some(1) => row_action = Some(RowAction::LinkFiles), + _ => {} + } + match row_action { + Some(RowAction::Clear) => { + app.run(CLEAR_EVENTS, json!({})).ok(); + } + Some(RowAction::LinkFiles) => { crate::menus::invoke(app, "ui.javascriptFilesDialog", json!({})); } - _ => {} + None => {} } if let Some(event) = remove && app.run("svgInteractivity.removeEvent", json!({ "event": event })).is_ok_and(|out| out["changed"].as_u64().unwrap_or(0) > 0) @@ -221,11 +261,16 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { /// Clear Events is on while the objects have events. The panel reads the events each frame it shows; a /// panel that is not shown leaves the row off. pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { - // (Where the objects' events differ, some of them have events.) - let any = cached(app).is_some_and(|info| info.has && info.events.as_ref().is_none_or(|l| !l.is_empty())); + let any = cached(app).is_some_and(clearable); states.set(CommandRef::new(CLEAR_EVENTS), CommandState::new().enabled(any)); } +/// Clear Events has something to clear: the objects have events. (Where their events differ, some +/// of them have events.) +fn clearable(info: &Info) -> bool { + info.has && info.events.as_ref().is_none_or(|l| !l.is_empty()) +} + /// The panel's own `ui.svgInteractivity.*` commands: it has none, because its menu row is the engine /// command `svgInteractivity.clearEvents`. pub(crate) fn run(_app: &mut VectorcraftApp, _id: &str, _params: &Value) -> Option> { @@ -481,4 +526,110 @@ mod tests { assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some(script.as_str())); assert!(panel.in_view(&last), "the picker scrolls the selected event into view"); } + + /// A rectangle with two events, `onclick: 1;` and `onmouseover: 2;`, in the panel. + fn two_events() -> Panel { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})); + run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"})); + run(&mut app, "svgInteractivity.setEvent", json!({"event": "onmouseover", "script": "2;"})); + Panel::new(app, show) + } + + fn undo_len(panel: &Panel) -> usize { + panel.app().session.active().unwrap().history.undo.len() + } + + #[test] + fn row_menu_picks_its_row_and_removes_that_event_in_one_undo_step() { + let mut panel = two_events(); + panel.click("onclick: 1;"); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("1;")); + + panel.secondary_click("onmouseover: 2;"); + assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;"), "the right-clicked row is picked"); + let undo = undo_len(&panel); + panel.click_menu_item(tl!("Remove Event")); + panel.frame(); + assert!(!panel.shows("onmouseover: 2;"), "the right-clicked event is removed"); + assert!(panel.shows("onclick: 1;"), "the event picked before the right-click stays"); + assert_eq!(undo_len(&panel), undo + 1); + + panel.app().run("edit.undo", json!({})).unwrap(); + panel.frame(); + assert!(panel.shows("onmouseover: 2;"), "one undo brings it back"); + } + + #[test] + fn row_menu_offers_the_panel_menu_and_footer_commands() { + let mut panel = two_events(); + panel.secondary_click("onclick: 1;"); + let mut states = CommandStates::default(); + menu_states(&panel.app(), &mut states); + let panel_menu_clear = states.remove(&CommandRef::new(CLEAR_EVENTS)).is_some_and(|s| s.is_enabled()); + assert_eq!(panel.menu_item_enabled(tl!("Clear Events")), panel_menu_clear, "Clear Events follows the panel menu"); + assert!(panel.menu_item_enabled(tl!("Link JavaScript Files…")), "a document is open"); + + let undo = undo_len(&panel); + panel.click_menu_item(tl!("Clear Events")); + panel.frame(); + assert!(!panel.shows("onclick: 1;") && !panel.shows("onmouseover: 2;")); + assert_eq!(undo_len(&panel), undo + 1); + } + + #[test] + fn keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus() { + let mut panel = two_events(); + panel.click("onclick: 1;"); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + assert!(panel.menu_item_enabled(tl!("Remove Event"))); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM)); + assert!(panel.focused("onmouseover: 2;"), "Escape gives focus back to the row"); + + // Enter runs the menu's first row, Remove Event, announced in that frame like the footer's. + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + let enter = + |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + panel.frame_with(vec![enter(true)]); + let removed = crate::i18n::fmt(tl!("Removed SVG event {event}"), &[("event", "onmouseover")]); + let announced = panel.announces(&removed); + panel.frame_with(vec![enter(false)]); + panel.frame(); + assert!(announced, "the removal is announced like the footer's"); + assert!(!panel.shows("onmouseover: 2;")); + assert!(panel.shows("onclick: 1;")); + } + + #[test] + fn row_menu_closes_when_its_row_disappears_or_the_document_changes() { + let mut panel = two_events(); + panel.secondary_click("onmouseover: 2;"); + assert!(panel.menu_item_enabled(tl!("Remove Event"))); + run(&mut panel.app(), "svgInteractivity.removeEvent", json!({"event": "onmouseover"})); + panel.frame(); + assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM)); + + // A second document whose object has the same event: switching to it shows a row of the same + // name, which the menu must not carry over to. + { + let mut app = panel.app(); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})); + run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"})); + app.run("window.nextDocument", json!({})).unwrap(); + } + panel.frame(); + panel.secondary_click("onclick: 1;"); + assert!(panel.menu_item_enabled(tl!("Remove Event"))); + panel.app().run("window.nextDocument", json!({})).unwrap(); + panel.frame(); + assert!(panel.shows("onclick: 1;"), "the other document lists the same event"); + assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM)); + } } diff --git a/docs/gaps.md b/docs/gaps.md index 671283d648..e83177a93c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,7 +1,7 @@ # Gaps > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: SVG Interactivity event rows have an item menu (Remove Event, Clear Events, Link JavaScript Files…); scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. @@ -81,6 +81,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | G12: SVG Interactivity event rows have an item menu: a right-click (or Shift+F10 on the focused row) picks that event and offers Remove Event (`svgInteractivity.removeEvent` for that row, one undo step), Clear Events (`svgInteractivity.clearEvents`, enabled like the panel menu row) and Link JavaScript Files… (`ui.javascriptFilesDialog`). Headless regressions: `panels::svg_interactivity::tests`. Scores and estimates unchanged. | | 2026-11-25 | minor | Document Info › Objects: total enclosed area (`pathArea` in pt²) for closed and compound paths (holes subtracted per fill rule; guides and open paths left out) and formatted Path Area in document units, beyond reference panel (#6965). Worked out only when the request covers Objects (`pathArea` null otherwise or with `pathArea: false`); the panel asks for it only while Objects or All Categories is shown. Tests: `info_gives_the_paths_total_area`, `info_works_out_the_path_area_only_for_the_objects_category`, `the_path_area_is_worked_out_only_while_objects_is_shown`, `format_area_formats_and_trims_cleanly`. 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-21 | minor | G12: Document Info › Selection Only (`ui.docInfo.selectionOnly`) counts objects in the selection through `document.info`; with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show. Headless regressions: `panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`. Scores and estimates unchanged. | @@ -559,6 +560,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Done (2026-12-02):** SVG Interactivity event rows have an item context menu. A right-click on an event row, or Shift+F10 on the focused row, picks that event and offers **Remove Event** (`svgInteractivity.removeEvent` for that row, one undo step, announced like the footer's Remove Selected Entry), **Clear Events** (`svgInteractivity.clearEvents`, enabled under the same rule as the panel menu row) and **Link JavaScript Files…** (`ui.javascriptFilesDialog`). The menu closes when its row leaves the list or the document changes. Headless regressions: `panels::svg_interactivity::tests::row_menu_picks_its_row_and_removes_that_event_in_one_undo_step`, `row_menu_offers_the_panel_menu_and_footer_commands`, `keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus` and `row_menu_closes_when_its_row_disappears_or_the_document_changes`. Other G12 gaps remain; scores and estimates unchanged. + - Glyphs cells have an item context menu. A character offers **Insert Glyph** at the Type caret or in selected text. A glyph without a mapped character offers **Apply Alternate** for the character selected with the Type tool. The menu uses the same actions as Enter and double-click and disables the item when its text target cannot accept the glyph. - **Implemented and tested (2026-11-21):** Properties panel Quick Actions follow every selected object. Ungroup (`object.ungroup`) is offered when any selected object is a group, including several groups, a group selected after a path, and a group that holds another group. Isolate Group (`object.isolate`) is offered only when that one group is the whole selection. Unite (`object.pathfinder.unite`) appears only for selections of at least two objects, each a non-guide path or a compound path. It appears alongside Group and Make Clipping Mask. Headless regressions: `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group` and `several_paths_offer_group_clipping_mask_and_unite`. Other G12 gaps remain; scores and estimates unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 001ff1141c..ac057f7afb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,7 +1,7 @@ # UI and interaction parity > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-29 · **Change:** minor (Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged; previously: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: SVG Interactivity event rows have an item menu; scores and estimates unchanged; previously: Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged; previously: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. > @@ -546,6 +546,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | | Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | +| SVG Interactivity event row item menu (G12) | done | Right-clicking an event row (or Shift+F10 on the focused row) picks that event and offers Remove Event, Clear Events and Link JavaScript Files…, the same commands as the footer and the panel menu; the menu closes when its row leaves the list or the document changes. `panels::svg_interactivity::tests::row_menu_picks_its_row_and_removes_that_event_in_one_undo_step`, `row_menu_offers_the_panel_menu_and_footer_commands`, `keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus`, `row_menu_closes_when_its_row_disappears_or_the_document_changes` | | Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | | Comments, Version History panels | missing | cloud features (out of scope) | | Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | @@ -674,6 +675,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | G12: SVG Interactivity event rows have an item menu (Remove Event, Clear Events, Link JavaScript Files…) using the footer and panel menu commands; `panels::svg_interactivity::tests`. Scores and estimates unchanged. | | 2026-11-27 | minor | 3D effect options: unchanged approval and equivalent validated `effect.setParams` preserve the effect, document revision and Undo, including defaults. Changed options still save once. 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. | From 18445cbda357c46db25c07b83ea0585f37fbba0a Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 3 Dec 2026 00:50:24 +0530 Subject: [PATCH 23/65] Keep SVG event menus with their artwork selection --- .../ui-egui/src/panels/svg_interactivity.rs | 50 ++++++++++++++----- 1 file changed, 37 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index 58fadc85a6..781cedc46e 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -61,8 +61,8 @@ pub(crate) struct Info { script_target: Option, } -/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selection size and ends. -pub(crate) type SelKey = ((u64, u64), u64, usize, Option, Option); +/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selected objects. +pub(crate) type SelKey = ((u64, u64), u64, Vec); /// A side label's text without its colon: the label draws the colon itself /// (`CommonWords::caption`), so the catalog's "Event:" keeps its translation here. @@ -71,16 +71,11 @@ pub(crate) fn caption(label: &'static str) -> &'static str { crate::i18n::t(label).trim_end_matches(':') } -fn sel_key(app: &VectorcraftApp) -> Option { - let st = app.session.active()?; - let sel = &st.selection.objects; - Some(((st.uid, st.reverts), st.revision, sel.len(), sel.first().copied(), sel.last().copied())) -} - /// The memoized [`Info`] when it was read for the current document and selection. fn cached(app: &VectorcraftApp) -> Option<&Info> { - let key = sel_key(app)?; - app.canvas.svg_info.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v) + let st = app.session.active()?; + let (((uid, reverts), revision, selection), info) = app.canvas.svg_info.as_ref()?; + (*uid == st.uid && *reverts == st.reverts && *revision == st.revision && selection == &st.selection.objects).then_some(info) } /// `svgInteractivity.info`, read again only when the document or the selection changes. @@ -88,7 +83,8 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Info { if let Some(v) = cached(app) { return v.clone(); } - let Some(key) = sel_key(app) else { return Info::default() }; + let Some(st) = app.session.active() else { return Info::default() }; + let key = ((st.uid, st.reverts), st.revision, st.selection.objects.clone()); let r = app.session.execute("svgInteractivity.info", &json!({})).unwrap_or_default(); let events = r["events"] .as_array() @@ -168,8 +164,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } let selection = if listed { Selection::single(event.to_string()) } else { Default::default() }; let mut list = List::::new(tl!("Events")) - // Each document gets its own list, so a row menu left open closes with the old one. - .id(ui.scope_id().with(("svg-events", document))) + // Keep each row menu with the drawing and artwork it was opened for. + .id(ui.scope_id().with(("svg-events", document, info.script_target))) .select(SelectMode::Single) .arrows_select(true) .deletable(true) @@ -606,6 +602,34 @@ mod tests { assert!(panel.shows("onclick: 1;")); } + #[test] + fn row_menu_closes_when_artwork_selection_changes_in_the_same_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let ids = [0, 20, 40, 60].map(|x| run(&mut app, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].clone()); + run(&mut app, "svgInteractivity.setEvent", json!({"ids": ids, "event": "onclick", "script": "1;"})); + let first = json!({"ids": [ids[0], ids[1], ids[3]]}); + let second = json!({"ids": [ids[0], ids[2], ids[3]]}); + run(&mut app, "select.set", first.clone()); + let mut panel = Panel::new(app, show); + let item = tl!("Remove Event"); + let role = craft::ui::contract::Role::MENU_ITEM; + panel.secondary_click("onclick: 1;"); + assert!(panel.menu_item_enabled(item)); + + // Only the middle object changes, and both selections display the exact same row. + run(&mut panel.app(), "select.set", second); + panel.frame(); + assert!(panel.shows("onclick: 1;")); + assert!(!panel.shows_role(item, role)); + + run(&mut panel.app(), "select.set", first); + panel.frame(); + assert!(!panel.shows_role(item, role), "the old menu stays closed on return"); + panel.secondary_click("onclick: 1;"); + assert!(panel.menu_item_enabled(item), "the row can open a fresh menu"); + } + #[test] fn row_menu_closes_when_its_row_disappears_or_the_document_changes() { let mut panel = two_events(); From 13488c3103a4d3fd7aa6d34ec09db4e3734071e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:10:09 -0800 Subject: [PATCH 24/65] Scripts: document pathItems.removeAll refuses to delete a clipping path Document.pathItems.removeAll() deleted every path of the document even when one was the clipping path of a group or layer that keeps other objects, so the next object became the clipping path. The scoped collections already refuse this. The document's collection now runs the same check before anything is deleted, and also refuses when it would empty a compound path or group that clips other objects. edit.clear removes an emptied compound path and keeps an emptied group, and the check follows it. The fault came with #9041, which added Document.pathItems. --- crates/engine/src/script/dom/paths.rs | 54 ++++++++- crates/engine/src/tests/script_dom.rs | 165 ++++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 216 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index a164dd93fc..00758409bc 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -495,18 +495,56 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before -/// anything is deleted, as `PageItems.removeAll()` does. +/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or +/// layer that keeps other objects, or a compound path or group that clips one and would be left +/// empty. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; - let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - let locks = st.doc.locked_artboards(); + let d = &st.doc; + let refused: Vec = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect(); + let locks = d.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + let mut next: Vec<_> = d.layers.iter().collect(); + let mut nodes = Vec::new(); + while let Some(n) = next.pop() { + nodes.push(n); + next.extend(n.children().into_iter().flatten()); + } + let mut going: std::collections::HashSet = ids.iter().copied().collect(); + let mut affected: std::collections::HashSet = ids.iter().copied().collect(); + let mut geometry = std::collections::HashSet::new(); + let mut masks = Vec::new(); + for n in nodes.into_iter().rev() { + let kids = n.children().map_or(&[][..], Vec::as_slice); + // Clear removes compound paths emptied of direct members, but keeps empty groups. + if matches!(n.kind, NodeKind::Compound { .. }) + && !kids.is_empty() + && kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id)) + { + going.insert(n.id); + } + if kids.iter().any(|k| affected.contains(&k.id)) { + affected.insert(n.id); + } + if (matches!(n.kind, NodeKind::Path { .. }) && !going.contains(&n.id)) || kids.iter().any(|k| geometry.contains(&k.id)) { + geometry.insert(n.id); + } + if n.clips() + && let Some(mask) = kids.first() + && affected.contains(&mask.id) + && !geometry.contains(&mask.id) + && kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + && masks.len() < 20 + { + masks.push(mask.id.0); + } + } + Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -516,6 +554,12 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if !masks.is_empty() { + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 73e44c2af7..2ebc3b3d44 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3312,6 +3312,171 @@ fn scoped_remove_all_refuses_a_clipping_compound_path() { assert_eq!(undo_steps(&s), steps); } +/// Runs the document's `pathItems.removeAll()`, then logs its error message and the number of paths. +const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m = '';\ + try { p.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length);"; + +/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the +/// group keeps other art, and deletes nothing, as the scoped collections do. +#[test] +fn document_path_items_remove_all_refuses_a_clipping_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(a)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + // The script catches the error and counts the paths before the run ends, so the run's own + // rollback cannot hide a deletion. + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&a.0.to_string()), "{out:?}"); + assert!(!e.contains(&b.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// The document's `pathItems.removeAll()` would empty a compound path that clips a group keeping +/// other art, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_compound_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&compound.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping mask made of a group of paths, as an imported SVG mask with several shapes is, would +/// be left empty by the document's `pathItems.removeAll()`, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let empty = NodeId(s.execute("object.newGroup", &json!({"parent": mask.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + assert!(d.node(empty).unwrap().children().unwrap().is_empty()); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!( + out[0], + json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0)) + ); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() { + for compound in [false, true] { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute(if compound { "object.compoundPath.make" } else { "object.group" }, &json!({})).unwrap(); + let sibling = s.active().unwrap().doc.parent_of(b).unwrap(); + let layer = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(layer).unwrap().clips()); + assert_eq!(d.node(layer).and_then(|n| n.children()).map(|k| k[0].id), Some(a)); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + if compound { + assert_eq!(out, [json!(""), json!(0)]); + let d = &s.active().unwrap().doc; + assert!(d.node(sibling).is_none()); + assert!(!d.node(layer).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + } else { + assert_eq!( + out[0], + json!(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", + a.0 + )) + ); + assert_eq!(out[1], json!(3)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); + } + } +} + /// A path that leaves a compound path for a layer is drawn as it was: it takes the compound /// path's paint and pixel alignment, as Release Compound Path gives them. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..242678381f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3233,7 +3233,7 @@ through `$`: `Stale page item`. Layer objects also become stale after their document is reverted, and so do the `pageItems`, `groupItems` and `compoundPathItems` of a layer or group, the `pathItems` of a compound path (`Stale page item`) and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document. - `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's + `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`, `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b5bad4ebc..f4bf5a74ff 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1116,7 +1116,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard, or when it would delete or empty the clipping path of a group or layer that keeps other objects. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. From 4ada69770b9bc19a49775c9414058454070c4b1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 00:34:07 -0800 Subject: [PATCH 25/65] Scripts: pathItems.removeAll deletes a clipping path when visible text still clips A group that clips by a mask holding a path and a text object keeps clipping by the text's outlines after the path is deleted, so Document.pathItems.removeAll() no longer refuses that case. Hidden text and hidden subgroups do not clip, so a mask left with only those still refuses. docs/mcp.md describes the rule. --- crates/engine/src/script/dom/paths.rs | 6 ++- crates/engine/src/tests/script_dom.rs | 63 +++++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 7a1929aa43..40db503d05 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -540,7 +540,7 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or /// layer that keeps other objects, or a compound path or group that clips one and would be left -/// empty. +/// with no visible path or text. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); @@ -579,7 +579,9 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if kids.iter().any(|k| affected.contains(&k.id)) { affected.insert(n.id); } - if (matches!(n.kind, NodeKind::Path { .. }) && !going.contains(&n.id)) || kids.iter().any(|k| geometry.contains(&k.id)) { + if (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Text(_)) && n.visible && !going.contains(&n.id)) + || kids.iter().any(|k| k.visible && geometry.contains(&k.id)) + { geometry.insert(n.id); } if n.clips() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 042adfd88f..ab0772e2ea 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3421,6 +3421,69 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { assert_eq!(undo_steps(&s), steps); } +/// A clipping group of a path and text keeps the text's glyph outlines when the document's +/// `pathItems.removeAll()` deletes the path, so the paths are deleted. +#[test] +fn document_path_items_remove_all_deletes_a_path_from_a_clipping_group_that_keeps_text() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out, [json!(""), json!(0)]); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none()); + assert!(d.node(t).is_some()); + assert!(d.node(kept).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// Hidden text in a clipping group does not clip, so the document's `pathItems.removeAll()` +/// refuses to delete the group's only visible clipping path. +#[test] +fn document_path_items_remove_all_refuses_when_only_hidden_text_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + if let Some(n) = d.node_mut(t) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c71bb57245..8eb344964e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3235,7 +3235,8 @@ through `$`: and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document. `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`, `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group - or layer that keeps other objects. `remove()` on an object that + or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that + clips when a text object in that group stays, because the text then clips. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` From 164a9ec05f916140c06d0d1a0c768738f954f1e5 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:22:02 +0530 Subject: [PATCH 26/65] Artboards: avoid duplicate lock submenu rows --- crates/ui-egui/src/menus/context.rs | 5 +++- crates/ui-egui/src/panels/artboards/tests.rs | 4 +-- crates/ui-egui/src/tests/contextmenu.rs | 27 ++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index d94e4feef4..3ecff4863f 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -252,7 +252,10 @@ fn artboard_items(app: &VectorcraftApp) -> Vec { .collect(); let unlock: Vec = [entry("Unlock Selected", sel.clone(), false), entry("Unlock All", (0..n).collect(), false)].into_iter().flatten().collect(); - for (label, items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] { + for (label, mut items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] { + // The selected and unselected targets are disjoint. If All matches a narrower row, it + // is adjacent to it after empty rows are removed. Keep the narrower row for that command key. + items.dedup_by(|a, b| matches!((a, b), (Node::Item(a), Node::Item(b)) if a.command == b.command)); if !items.is_empty() { v.push(sub(label, items)); } diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index 2359a17bae..32fb3d451f 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -1176,8 +1176,8 @@ fn the_artboard_tools_lock_entries_have_something_to_change() { Some(sub) => menu_labels(children_of(sub)), None => vec![], }; - assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected", "Lock All"], "the selected artboard is locked already"); - assert_eq!(subs("Unlock Artboards"), ["Unlock Selected", "Unlock All"]); + assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected"], "only the unselected artboard can be locked"); + assert_eq!(subs("Unlock Artboards"), ["Unlock Selected"], "only the selected artboard can be unlocked"); } /// A right-click on an artboard that isn't selected selects it alone; on a selected one the selection diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index ad11b25441..24d06187c5 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -614,12 +614,17 @@ fn every_context_label_is_a_menu_string() { app.ui.context_spelling = None; // The Lock Artboards and Unlock Artboards submenus of the Artboard tool. app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 80})).unwrap(); + app.run("artboard.new", json!({"x": 520, "y": 0, "width": 100, "height": 80})).unwrap(); app.run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap(); app.select_tool("artboard"); shown.extend(labels(&app)); // Lock Selected with the artboard that isn't locked active. crate::panels::artboards::select(&mut app, 1); shown.extend(labels(&app)); + // Unlock All has its own target when another locked artboard is outside the selection. + app.run("artboard.setProps", json!({"index": 2, "locked": true})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + shown.extend(labels(&app)); let missing: Vec<_> = shown.iter().filter(|l| !strings.contains(l.as_str())).collect(); assert!(missing.is_empty(), "context menu labels missing from menu_strings: {missing:?}"); for label in menus::CONTEXT_LABELS { @@ -681,6 +686,28 @@ impl CanvasMenu { } } +#[test] +fn single_artboard_lock_submenus_open_and_apply_the_available_action() { + let mut app = app(); + app.select_tool("artboard"); + let mut canvas = CanvasMenu::new(app); + for (submenu, action, equivalent, locked) in + [("Lock Artboards", "Lock Selected", "Lock All", true), ("Unlock Artboards", "Unlock Selected", "Unlock All", false)] + { + canvas.right_click(100.0, 100.0); + let row = canvas.fixture.by_label(submenu).expect("the canvas offers the artboard submenu"); + canvas.frame(vec![Event::PointerMoved(row.center())]); + canvas.fixture.advance(1.0); + canvas.frame(vec![]); + + let row = canvas.fixture.by_label(action).expect("the submenu shows the action for the selected artboard"); + assert!(canvas.fixture.by_label(equivalent).is_none(), "the same action has only one row"); + canvas.fixture.click(&row); + canvas.frame(vec![]); + assert_eq!(canvas.app.borrow().session.active().unwrap().doc.artboards[0].locked, locked); + } +} + #[test] fn create_outlines_from_the_canvas_menu_converts_selected_text_in_one_undo_step() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..7bca51829f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11700,7 +11700,8 @@ every artboard, and Lock All Except Selected acts on the artboards that are not that is not selected first selects it alone. An entry that cannot run is left out: Cut with a locked artboard or every artboard selected, Delete Artboards with no artboard to delete, Select All Artboards with every artboard selected, Fit to Artwork Bounds with no art on a selected unlocked artboard, Switch Orientation with no selected artboard to change, -and a lock entry with no artboard to change. The menu measures the art for Delete Empty Artboards and +and a lock entry with no artboard to change. When two lock or unlock entries would change the same artboards, the +menu shows the more specific action. The menu measures the art for Delete Empty Artboards and Fit to Artwork Bounds once, at the right-click. Paste centers copied artboards on the right-click's point (`edit.paste {artboardsAt: [x, y]}`) and centers copied objects there too (`center`). Chosen from a menu or the command palette with the tool in use, `artboard.new` makes the new artboard active, `artboard.duplicate` selects the copies, From ec943eebf7dfa14576e4589991e8b2f84ca2e4b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 01:02:12 -0800 Subject: [PATCH 27/65] Tabs: an unentered X, Leader or Align On value stays with its stop A value typed in the Tabs panel's X, Leader or Align On field and not yet entered was kept when the selection changed to other text, or the ruler picked another stop, whose stop held the same value. Enter then set the stop of the new target. Each field now has an edit target made of the document, the selection, the Type tool's range, the text and paragraph shown and the picked stop, so the typed value is dropped when any of them changes. --- crates/ui-egui/src/panels/tabs.rs | 24 +++++- crates/ui-egui/src/panels/tabs/tests.rs | 101 ++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index fbea360c43..56c1362911 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -344,6 +344,19 @@ fn shown_paragraph(app: &VectorcraftApp, t: &TextObject) -> usize { super::character::text_editing(app).map_or(0, |(_, a, _)| t.paragraphs_in(a, a).start) } +/// The edit target of the panel's fields for text `n`: the active document and its reverts, the +/// selected objects, the Type tool's range, and the text and paragraph whose stops the panel shows. +/// A value typed in a field is dropped when this changes before it is entered, so it does not set +/// the stops of other text, even text whose stop holds the same values. +fn edited_paragraph(app: &VectorcraftApp, n: &Node) -> egui::IdSalt { + let para = match &n.kind { + NodeKind::Text(t) => shown_paragraph(app, t), + _ => 0, + }; + let document = app.session.active().map(|st| (st.uid, st.reverts, &st.selection.objects)); + egui::IdSalt::new((document, super::character::text_editing(app), n.id, para)) +} + /// [`above_text`], then note the active document and text `n`. A floating panel is /// at least [`crate::panel_docking::PANEL_MIN_WIDTH`] wide, so for narrow text at a low zoom the /// panel comes out wider than asked; the ruler then draws text `n` at [`screen_scale`] and runs @@ -722,6 +735,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let vertical = matches!(&node.kind, NodeKind::Text(text) if text.vertical); + let edited = edited_paragraph(app, &node); let targets = indent_targets(app, &node); let mixed_left = targets.iter().any(|p| p.left != para.left_indent); let panel = &mut app.ui.tabs_panel; @@ -763,7 +777,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let label = if vertical { tl!("Y:") } else { tl!("X:") }; let x = marker.map_or_else(|| stops.get(stop).map(|s| s.position), |item| picked_position(item, ¶, span)); let typed = Field::new(label) - .show(ui, |ui, _| NumberField::length(label, Bind::given(x), lengths).range(0.0..=MAX_STOP).show(ui)) + .show(ui, |ui, _| NumberField::length(label, Bind::given(x), lengths).range(0.0..=MAX_STOP).edit_target((edited, stop, marker)).show(ui)) .inner .and_then(|out| out.edit.events.committed().copied().flatten()); if let Some(value) = typed { @@ -773,7 +787,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let on_stop = marker.is_none() && stop < stops.len(); let leader = stops.get(stop).filter(|_| marker.is_none()).map(|s| s.leader.clone()).unwrap_or_default(); let typed = Field::new(tl!("Leader:")) - .show(ui, |ui, _| TextField::new(tl!("Leader:"), Bind::given(leader.clone())).limit(8_usize).enabled(on_stop).show(ui)) + .show(ui, |ui, _| { + TextField::new(tl!("Leader:"), Bind::given(leader.clone())).limit(8_usize).enabled(on_stop).edit_target((edited, stop)).show(ui) + }) .inner .and_then(|out| out.events.committed().cloned()); if let (Some(leader), Some(s)) = (typed, stops.get_mut(stop)) { @@ -784,7 +800,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let decimal = marker.is_none() && stops.get(stop).is_some_and(|s| s.align == TabAlign::Decimal); let on = stops.get(stop).map_or_else(|| ".".to_string(), |s| s.align_on.to_string()); let typed = Field::new(tl!("Align On:")) - .show(ui, |ui, _| TextField::new(tl!("Align On:"), Bind::given(on.clone())).limit(1_usize).enabled(decimal).show(ui)) + .show(ui, |ui, _| { + TextField::new(tl!("Align On:"), Bind::given(on.clone())).limit(1_usize).enabled(decimal).edit_target((edited, stop)).show(ui) + }) .inner .and_then(|out| out.events.committed().and_then(|text| text.chars().next())); if let (Some(c), Some(s)) = (typed, stops.get_mut(stop)) { diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index a30cf7b559..e0afadbd66 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1094,3 +1094,104 @@ fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() { assert_eq!(top, 0.0, "view centered at y {center_y}: panel top {top}, canvas {canvas:?}"); } } + +/// An app with area texts that each have decimal stops, aligned on a period with no leader, at +/// `positions`, and the first text selected. → the app and the texts' ids. +fn decimal_stops_app(texts: usize, positions: &[f64]) -> (VectorcraftApp, Vec) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let stops: Vec<_> = positions.iter().map(|p| json!({"position": p, "align": "decimal"})).collect(); + let ids: Vec = (0..texts) + .map(|i| { + let y = 20.0 + 80.0 * i as f64; + let id = app.run("text.create", json!({"x": 10, "y": y, "text": "a\t1.5", "area": {"width": 300, "height": 60}})).unwrap(); + let id = id["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.tabs.set", json!({"stops": stops})).unwrap(); + id + }) + .collect(); + app.run("select.set", json!({"ids": [ids[0]]})).unwrap(); + (app, ids) +} + +/// The stops of the first paragraph of text `id` as (position, leader, align on). +fn stops_of(app: &VectorcraftApp, id: u64) -> Vec<(f64, String, char)> { + text_of(app, id).para_at(0).tabs.iter().map(|s| (s.position, s.leader.clone(), s.align_on)).collect() +} + +/// Selects all of the focused field's text, types `text` and leaves it unentered. +fn draft(panel: &mut crate::tests::panel_harness::Panel, label: &str, role: craft::ui::contract::Role, text: &str) { + panel.click_role(label, role); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); +} + +/// A value typed in the X, Leader or Align On field and not yet entered is dropped when the +/// selection moves to another text whose stop holds the same values: Enter then leaves both texts' +/// stops as they were. A value typed for the newly selected text still sets its stop. +#[test] +fn a_field_value_typed_before_the_selection_changes_does_not_reach_the_new_text() { + use craft::ui::contract::Role; + for (label, role, typed) in [("X:", Role::SPIN_BUTTON, "70"), ("Leader:", Role::TEXT_INPUT, "-"), ("Align On:", Role::TEXT_INPUT, ",")] { + let (app, ids) = decimal_stops_app(2, &[40.0]); + let (a, b) = (ids[0], ids[1]); + let before = stops_of(&app, a); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, label, role, typed); + panel.app().run("select.set", json!({"ids": [b]})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + for id in [a, b] { + assert_eq!(stops_of(&panel.app(), id), before, "{label} {typed:?} typed for text {a}, entered after selecting text {b}: text {id}"); + } + draft(&mut panel, label, role, typed); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(stops_of(&panel.app(), a), before, "{label} {typed:?} typed for text {b}: text {a}"); + assert_ne!(stops_of(&panel.app(), b), before, "{label} {typed:?} typed for text {b} sets its stop"); + } +} + +/// A Leader value typed with two texts selected and not yet entered is dropped when the selection +/// changes to the first text and a third one: the panel still shows the first text, but Enter +/// would set every selected text's stops. +#[test] +fn a_field_value_typed_before_other_texts_join_the_selection_does_not_reach_them() { + let (app, ids) = decimal_stops_app(3, &[40.0]); + let before = stops_of(&app, ids[0]); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + panel.app().run("select.set", json!({"ids": [ids[0], ids[1]]})).unwrap(); + draft(&mut panel, "Leader:", craft::ui::contract::Role::TEXT_INPUT, "-"); + panel.app().run("select.set", json!({"ids": [ids[0], ids[2]]})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + for &id in &ids { + assert_eq!( + stops_of(&panel.app(), id), + before, + "Leader typed for texts {} and {}, entered after selecting {} and {}: text {id}", + ids[0], + ids[1], + ids[0], + ids[2] + ); + } +} + +/// A Leader or Align On value typed for one stop and not yet entered is dropped when the ruler +/// picks another stop of the paragraph with the same leader and alignment character. +#[test] +fn a_field_value_typed_before_another_stop_is_picked_does_not_reach_that_stop() { + use craft::ui::contract::Role; + for (label, typed) in [("Leader:", "-"), ("Align On:", ",")] { + let (app, ids) = decimal_stops_app(1, &[30.0, 60.0]); + let before = stops_of(&app, ids[0]); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + panel.app().ui.tabs_panel.stop = 0; + draft(&mut panel, label, Role::TEXT_INPUT, typed); + panel.app().ui.tabs_panel.stop = 1; + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(stops_of(&panel.app(), ids[0]), before, "{label} {typed:?} typed for the first stop, entered after picking the second"); + } +} From 4bbfb2d4aff9a1614856560221982cbeb138684f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:01:46 -0800 Subject: [PATCH 28/65] Scripts: pathItems.removeAll counts only type that draws glyphs as a clip outline The document's pathItems.removeAll() counted any visible text object as geometry that keeps a clipping mask clipping. Blank type and area type too short for its first line lay out no glyphs, so the clip renderer clips by nothing for them; deleting the mask's last path then hid the clipped art. - Text counts only when it is visible and its layout gives glyph outlines. - A clipping group nested in the mask counts only its first member. - Hidden objects and members of hidden groups do not count. - Tests cover blank, overset, hidden and nested-clipped type, and type with glyphs that still allows the delete. - docs/mcp.md states the rule. --- crates/engine/src/script/dom/paths.rs | 20 +++- crates/engine/src/tests/script_dom.rs | 140 ++++++++++++++++++++++---- docs/mcp.md | 4 +- 3 files changed, 141 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 40db503d05..4ae9d65dc0 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -540,7 +540,7 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or /// layer that keeps other objects, or a compound path or group that clips one and would be left -/// with no visible path or text. +/// with no visible path or visible type that lays out glyphs to clip by. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); @@ -579,9 +579,21 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if kids.iter().any(|k| affected.contains(&k.id)) { affected.insert(n.id); } - if (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Text(_)) && n.visible && !going.contains(&n.id)) - || kids.iter().any(|k| k.visible && geometry.contains(&k.id)) - { + // A clip outline takes in visible paths and the glyphs of visible type, as + // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no outline. + let shape = n.visible + && match &n.kind { + NodeKind::Path { .. } => true, + NodeKind::Text(t) => { + t.runs.iter().any(|r| !r.text.trim().is_empty()) + && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() + } + _ => false, + }; + // A clipping group's outline is its first member's alone. + let inner = + if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) }; + if n.visible && ((shape && !going.contains(&n.id)) || inner) { geometry.insert(n.id); } if n.clips() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ab0772e2ea..222c40cf21 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3421,16 +3421,16 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { assert_eq!(undo_steps(&s), steps); } -/// A clipping group of a path and text keeps the text's glyph outlines when the document's -/// `pathItems.removeAll()` deletes the path, so the paths are deleted. +/// Type clips by its glyph outlines, so a clipping group that keeps type after its paths go still +/// clips, and the document's `pathItems.removeAll()` deletes every path. #[test] -fn document_path_items_remove_all_deletes_a_path_from_a_clipping_group_that_keeps_text() { - let (mut s, a, _) = doc(); +fn document_path_items_remove_all_keeps_a_clipping_group_that_holds_type() { + let (mut s, a, b) = doc(); let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); - let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); s.edit("Clip", |d, _| { if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { @@ -3445,33 +3445,33 @@ fn document_path_items_remove_all_deletes_a_path_from_a_clipping_group_that_keep assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); let steps = undo_steps(&s); let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); - assert_eq!(out, [json!(""), json!(0)]); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); let d = &s.active().unwrap().doc; - assert!(d.node(a).is_none()); - assert!(d.node(t).is_some()); - assert!(d.node(kept).is_some()); + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); assert_eq!(undo_steps(&s), steps + 1); } -/// Hidden text in a clipping group does not clip, so the document's `pathItems.removeAll()` -/// refuses to delete the group's only visible clipping path. +/// Type with no characters to draw gives no clip outline, so a clipping group whose paths would +/// leave only such type makes the document's `pathItems.removeAll()` throw and delete nothing. #[test] -fn document_path_items_remove_all_refuses_when_only_hidden_text_would_clip() { +fn document_path_items_remove_all_refuses_when_only_blank_type_would_clip() { let (mut s, a, _) = doc(); let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); - let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + } if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { children.sort_by_key(|c| c.id != mask); *clip = true; } - if let Some(n) = d.node_mut(t) { - n.visible = false; - } Ok(()) }) .unwrap(); @@ -3480,6 +3480,110 @@ fn document_path_items_remove_all_refuses_when_only_hidden_text_would_clip() { let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); let e = out[0].as_str().unwrap_or_default(); assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping group nested in a clipping mask clips by its first member only, so type it clips does +/// not keep the outer mask's outline, and the document's `pathItems.removeAll()` names the outer +/// mask too. +#[test] +fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, t.0]})).unwrap(); + let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, nested.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + for (g, first) in [(nested, b), (outer, mask)] { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(g).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != first); + *clip = true; + } + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.split(": ").last().unwrap_or_default().split(", ").any(|id| id == mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Area type too short for its first line lays out no glyphs and gives no clip outline, so a +/// clipping group whose paths would leave only such type makes the document's +/// `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_overset_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 250, "size": 12, "area": {"width": 100, "height": 1}, "text": "hi"})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Hidden type does not clip, so a clipping group whose paths would leave only hidden type makes +/// the document's `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_hidden_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(n) = d.node_mut(t) { + n.visible = false; + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); assert_eq!(s.active().unwrap().doc, before); assert_eq!(undo_steps(&s), steps); } diff --git a/docs/mcp.md b/docs/mcp.md index 8eb344964e..d6fd6b06fa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3236,7 +3236,9 @@ through `$`: `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`, `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that - clips when a text object in that group stays, because the text then clips. `remove()` on an object that + clips when a visible text object that lays out glyphs stays in it, because the text then clips. Hidden text, text + in a hidden group, blank text, area text too short for its first line, and text that a clipping group nested in + the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` From 1c23ee86380e4f8f0c433d6ff8ceb7d6b0d7bfab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:49:01 -0800 Subject: [PATCH 29/65] Tabs: test each part of the fields' edit target Four panel tests cover the parts of the edit target that no test covered: another document whose text has the same id and stops, the Type tool's insertion point moved to the next paragraph or its selection grown over both, the left indent's box picked after the first-line marker at the same position, and File > Revert followed by selecting the restored text again. Each one fails when its part is left out of the edit target. --- crates/ui-egui/src/panels/tabs/tests.rs | 108 ++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index e0afadbd66..f10afe5c98 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1195,3 +1195,111 @@ fn a_field_value_typed_before_another_stop_is_picked_does_not_reach_that_stop() assert_eq!(stops_of(&panel.app(), ids[0]), before, "{label} {typed:?} typed for the first stop, entered after picking the second"); } } + +/// An X value typed in one document and not yet entered is dropped when another document becomes +/// active, also when the text selected there has the same id and the same stops. +#[test] +fn an_x_value_typed_before_another_document_is_activated_does_not_reach_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ids: Vec = (0..2) + .map(|_| { + app.run("file.new", json!({})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 20, "text": "a\t1.5", "area": {"width": 300, "height": 60}})).unwrap(); + let id = id["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap(); + id + }) + .collect(); + assert_eq!(ids[0], ids[1], "the two documents' texts have the same id"); + let id = ids[0]; + let before = stops_of(&app, id); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70"); + panel.app().run("document.activate", json!({"index": 0})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + for index in [0, 1] { + panel.app().run("document.activate", json!({"index": index})).unwrap(); + assert_eq!(stops_of(&panel.app(), id), before, "X typed in the second document, entered after activating the first: document {index}"); + } +} + +/// The stops of every paragraph of text `id` as (position, leader, align on). +fn paragraph_stops(app: &VectorcraftApp, id: u64) -> Vec> { + let t = text_of(app, id); + (0..t.paragraph_count()).map(|i| t.para_at(i).tabs.iter().map(|s| (s.position, s.leader.clone(), s.align_on)).collect()).collect() +} + +/// An X value typed with the Type tool's insertion point in the first paragraph and not yet +/// entered is dropped when the insertion point moves to the second paragraph, or the selection +/// grows over both, though both paragraphs hold the same stops. +#[test] +fn an_x_value_typed_before_the_type_tool_selection_changes_does_not_reach_other_paragraphs() { + for (anchor, caret) in [(6, 6), (0, 9)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 20, "text": "a\t1.5\nb\t2.5", "area": {"width": 300, "height": 80}})).unwrap(); + let id = id["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap(); + let before = paragraph_stops(&app, id); + assert_eq!(before.len(), 2); + assert_eq!(before[0], before[1], "both paragraphs hold the same stops"); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 0})); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70"); + panel.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": anchor, "caret": caret})); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!( + paragraph_stops(&panel.app(), id), + before, + "X typed at the start of the text, entered with the Type tool's selection at {anchor}..{caret}" + ); + } +} + +/// An X value typed for the first-line marker and not yet entered is dropped when the ruler picks +/// the left indent's box at the same position. +#[test] +fn an_x_value_typed_before_another_indent_marker_is_picked_does_not_move_it() { + let mut app = indent_app(0.0, 0.0); + app.ui.tabs_panel.marker = Some(RulerItem::FirstLine); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "20"); + panel.app().ui.tabs_panel.marker = Some(RulerItem::LeftBox); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(indent_values(&panel.app(), 0), (0.0, 0.0), "X typed for the first-line marker, entered after picking the left indent's box"); +} + +/// An X value typed and not yet entered is dropped when File › Revert restores the document, also +/// when the restored text is selected again and holds the same stops. +#[test] +fn an_x_value_typed_before_file_revert_does_not_reach_the_restored_text() { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let (mut app, ids) = decimal_stops_app(1, &[40.0]); + let id = ids[0]; + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-tabs-draft-revert-{}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let before = stops_of(&app, id); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({"ids": [id]})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(stops_of(&panel.app(), id), before, "X typed before File › Revert, entered after selecting the restored text"); +} From fc9d77032f4af9cb25b836b1216676fe0ae03789 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 03:19:03 -0800 Subject: [PATCH 30/65] Scripts: pathItems.removeAll counts a list marker as a clip outline The document's pathItems.removeAll() skipped text whose characters are all whitespace before laying it out, so a numbered paragraph holding a single space did not count, although its number clips. The deletion was then refused while the mask would still clip. - Whitespace-only text is laid out like other text. - Text is laid out only inside a mask that loses a path, so documents with text outside such masks do no layout for the check. - A test covers a mask left with only a list number. - docs/mcp.md says blank text without a list marker does not count. --- crates/engine/src/script/dom/paths.rs | 29 +++++++++++++++----- crates/engine/src/tests/script_dom.rs | 39 +++++++++++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 4ae9d65dc0..1a8fb3087b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -565,6 +565,26 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { } let mut going: std::collections::HashSet = ids.iter().copied().collect(); let mut affected: std::collections::HashSet = ids.iter().copied().collect(); + for n in nodes.iter().rev() { + if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) { + affected.insert(n.id); + } + } + // Type is laid out only inside a mask that loses a path; no other outline decides a refusal. + let mut in_mask = std::collections::HashSet::new(); + for n in &nodes { + if n.clips() + && let Some(mask) = n.children().and_then(|k| k.first()) + && affected.contains(&mask.id) + { + let mut stack = vec![mask]; + while let Some(m) = stack.pop() { + if in_mask.insert(m.id) { + stack.extend(m.children().into_iter().flatten()); + } + } + } + } let mut geometry = std::collections::HashSet::new(); let mut masks = Vec::new(); for n in nodes.into_iter().rev() { @@ -576,17 +596,14 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { { going.insert(n.id); } - if kids.iter().any(|k| affected.contains(&k.id)) { - affected.insert(n.id); - } // A clip outline takes in visible paths and the glyphs of visible type, as - // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no outline. + // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no + // outline. A list marker is a glyph too, so whitespace-only type is laid out as well. let shape = n.visible && match &n.kind { NodeKind::Path { .. } => true, NodeKind::Text(t) => { - t.runs.iter().any(|r| !r.text.trim().is_empty()) - && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() + in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() } _ => false, }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 222c40cf21..62c47de128 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3519,6 +3519,45 @@ fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() { assert_eq!(s.active().unwrap().doc, before); } +/// A numbered paragraph whose text is a single space still draws its number, which clips, so the +/// document's `pathItems.removeAll()` deletes the paths of a clipping group that keeps it. +#[test] +fn document_path_items_remove_all_keeps_a_clipping_group_whose_type_draws_only_a_list_number() { + use vectorcraft_doc::text::{NumberStyle, ParaList}; + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + let mut styles = tx.paragraph_styles(); + styles.iter_mut().for_each(|p| p.list = Some(ParaList::numbered(NumberStyle::Arabic))); + tx.set_paragraph_styles(styles); + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + /// Area type too short for its first line lays out no glyphs and gives no clip outline, so a /// clipping group whose paths would leave only such type makes the document's /// `pathItems.removeAll()` throw and delete nothing. diff --git a/docs/mcp.md b/docs/mcp.md index d6fd6b06fa..3c2ac4f459 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3237,7 +3237,7 @@ through `$`: `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that clips when a visible text object that lays out glyphs stays in it, because the text then clips. Hidden text, text - in a hidden group, blank text, area text too short for its first line, and text that a clipping group nested in + in a hidden group, blank text without a list marker, area text too short for its first line, and text that a clipping group nested in the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on From 45a5c495961d63c8cc56bdb62d9eadf41406496f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:24:25 -0800 Subject: [PATCH 31/65] Tabs: Select All on a threaded story drops an unentered field value The fields' edit target read only the Type tool's frame and range. Select All on a frame whose text was already fully selected keeps that range but makes Enter set the stops of every frame of the story, so an unentered X, Leader or Align On value survived and reached the other frames. The target now also includes whether Select All took the story. --- crates/ui-egui/src/panels/tabs.rs | 6 +++-- crates/ui-egui/src/panels/tabs/tests.rs | 31 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 56c1362911..423223d4a8 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -345,7 +345,8 @@ fn shown_paragraph(app: &VectorcraftApp, t: &TextObject) -> usize { } /// The edit target of the panel's fields for text `n`: the active document and its reverts, the -/// selected objects, the Type tool's range, and the text and paragraph whose stops the panel shows. +/// selected objects, the Type tool's range and whether Select All took the threaded story, and the +/// text and paragraph whose stops the panel shows. /// A value typed in a field is dropped when this changes before it is entered, so it does not set /// the stops of other text, even text whose stop holds the same values. fn edited_paragraph(app: &VectorcraftApp, n: &Node) -> egui::IdSalt { @@ -354,7 +355,8 @@ fn edited_paragraph(app: &VectorcraftApp, n: &Node) -> egui::IdSalt { _ => 0, }; let document = app.session.active().map(|st| (st.uid, st.reverts, &st.selection.objects)); - egui::IdSalt::new((document, super::character::text_editing(app), n.id, para)) + let typed = (super::character::text_editing(app), super::character::text_story(app)); + egui::IdSalt::new((document, typed, n.id, para)) } /// [`above_text`], then note the active document and text `n`. A floating panel is diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index f10afe5c98..39cb56fd33 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1303,3 +1303,34 @@ fn an_x_value_typed_before_file_revert_does_not_reach_the_restored_text() { panel.key(egui::Key::Enter, egui::Modifiers::NONE); assert_eq!(stops_of(&panel.app(), id), before, "X typed before File › Revert, entered after selecting the restored text"); } + +/// A Leader value typed with the Type tool's selection over all of a threaded frame's text and not +/// yet entered is dropped when Select All takes the whole story, though the frame's range stays +/// the same: Enter would set the stops of every frame of the story. +#[test] +fn a_field_value_typed_before_select_all_takes_the_story_does_not_reach_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let story = (1..=8).map(|i| format!("{i}\t1.5")).collect::>().join("\n"); + let a = app.run("text.create", json!({"x": 10, "y": 20, "text": story, "area": {"width": 300, "height": 50}})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [10, 300, 300, 200]})).unwrap()["id"].as_u64().unwrap(); + assert!(!text_of(&app, a).plain_text().is_empty() && !text_of(&app, b).plain_text().is_empty(), "the story runs through both frames"); + let before = (paragraph_stops(&app, a), paragraph_stops(&app, b)); + let len = text_of(&app, a).plain_text().len(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": len})); + let range = super::super::character::text_editing(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "Leader:", craft::ui::contract::Role::TEXT_INPUT, "-"); + panel.app().run("select.all", json!({})).unwrap(); + assert_eq!(super::super::character::text_editing(&panel.app()), range, "Select All leaves the frame's range as it was"); + assert!(super::super::character::text_story(&panel.app()).is_some(), "Select All takes the story"); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + let after_a = paragraph_stops(&panel.app(), a); + let after_b = paragraph_stops(&panel.app(), b); + assert_eq!((after_a, after_b), before, "Leader typed for frame {a}'s text, entered after Select All took the story"); +} From 4fd3d9f22d83ec1aeb72268bd714bb7a7ab4904c Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 3 Dec 2026 21:32:54 +0530 Subject: [PATCH 32/65] 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 33/65] 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] From bf13038b8d41cc4c860645df491ca9a0a79ea97d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:36:45 -0800 Subject: [PATCH 34/65] Docs: pathItems.removeAll keeps a clip that visible text holds The progress line for Document.pathItems now says that removeAll() still deletes the paths of a clipping group when visible text that lays out glyphs stays in it, as docs/mcp.md describes. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b896e0ac48..67c053ee0e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a clipping group when a visible text object that lays out glyphs stays in the group, because the text then clips. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 9c11c47f75cf870de92b7f8883fc8f89aab43793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:51:28 -0800 Subject: [PATCH 35/65] Doc tests: unsafe code is denied in doc tests too Rustdoc builds each doc test as its own crate, without the workspace's `unsafe_code = "deny"` and without a library's `#![forbid(unsafe_code)]`, so a doc test holding an `unsafe` block passed `cargo test --doc`. - Every library root now carries `#![doc(test(attr(forbid(unsafe_code))))]`, or `deny` in cad, eps and metafile, which rely on the workspace lint. - `cargo xtask layers` reports a library whose doc tests are missing the attribute, or use `deny` where the library forbids unsafe code. - AGENTS.md names the rule next to the `unsafe` allowlist. --- AGENTS.md | 2 +- crates/affinity/src/lib.rs | 1 + crates/apischema/src/lib.rs | 1 + crates/brush/src/lib.rs | 1 + crates/cad/src/lib.rs | 1 + crates/color/src/lib.rs | 1 + crates/doc/src/lib.rs | 1 + crates/effects/src/lib.rs | 1 + crates/engine/src/lib.rs | 1 + crates/eps/src/lib.rs | 1 + crates/format/src/lib.rs | 1 + crates/geom/src/lib.rs | 1 + crates/js/src/lib.rs | 1 + crates/mcp/src/lib.rs | 1 + crates/metafile/src/lib.rs | 1 + crates/pathops/src/lib.rs | 1 + crates/pdf/src/lib.rs | 1 + crates/plugins/src/lib.rs | 1 + crates/render/src/lib.rs | 1 + crates/scriptcheck/src/lib.rs | 1 + crates/svg/src/lib.rs | 1 + crates/testkit/src/lib.rs | 1 + crates/text/src/lib.rs | 1 + crates/three-d/src/lib.rs | 1 + crates/tools/src/lib.rs | 1 + crates/trace/src/lib.rs | 1 + crates/ui-egui/src/lib.rs | 1 + xtask/src/doc_tests.rs | 98 +++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 11 ++-- 29 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 xtask/src/doc_tests.rs diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..5f2d41d538 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -21,6 +21,7 @@ //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; #[cfg(test)] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8f077dae..8fe1cef218 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..c2be1804db 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 16e1e7f5a5..d5c30cd89b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and //! reduce to commands, so every gesture is journaled and replayable. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod cmd; pub mod file_access; diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index d8b9a96295..6813b300aa 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -34,6 +34,7 @@ //! - `ai_graph`: the records of a live graph those two write around its group. //! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. +#![doc(test(attr(deny(unsafe_code))))] mod ai_editing; mod ai_graph; diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9975527f78..c7157df94d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,6 +37,7 @@ //! already; [`save_with`] writes a version 1 document with them negated back for an older file //! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #[cfg(not(target_arch = "wasm32"))] mod atomic; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3f11c71062..8a4cb4f7fb 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -6,6 +6,7 @@ //! //! Coordinates are document points (1/72 in), y pointing down. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod anchors; pub mod arc; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a720940b06..77b3e00856 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -131,6 +131,7 @@ //! `await` (ECMA-262 2017 section 25.5, ). //! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ast; mod builtins; diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index efc9d44830..7e104e85f2 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -13,6 +13,7 @@ //! //! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod backend; mod headless; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index df23cbb073..66f3c4327b 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -26,6 +26,7 @@ //! formats. //! //! The app walks its document and maps its drawing operations to the shared writers. +#![doc(test(attr(deny(unsafe_code))))] #[cfg(test)] mod bytes; diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index da7960af0f..0190233191 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -5,6 +5,7 @@ //! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few //! anchors. See the crate README for the API overview. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod boolean; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 2dc6f1ec0a..a7118fd37a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -42,6 +42,7 @@ //! security handler, the algorithm following the compatibility ([`Encryption`]); either password //! opens an encrypted file. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod editing; mod encrypt; diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index c9c0e89521..4f79939c62 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -42,6 +42,7 @@ //! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each //! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod deferred; pub mod dialog; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4358cc180d..f2b76c525d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,6 +5,7 @@ //! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups, //! gradients, images and text (via `vectorcraft-text` glyph outlines). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod brush_fx; diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 9075c53517..f0c8528919 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -22,6 +22,7 @@ //! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the //! input's size, and no input can overflow the stack. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod analyze; mod catalog; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 222b90b25c..109b3a938a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -100,6 +100,7 @@ //! letter and word spacing become character attributes (line breaks, kerning, baseline shift, //! rotation and style names). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use craft_svg::tree::usvg; mod css; diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index fa7b39aa9d..fd86ad3c89 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -22,6 +22,7 @@ // apply here. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ai; pub mod ase; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 25e44392d6..4723f1ffcd 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -9,6 +9,7 @@ //! //! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod bitmap; mod colr; diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f561c0b7c6..37768ea651 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -7,6 +7,7 @@ //! //! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod fold; mod solid; diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..5adcecd679 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -6,6 +6,7 @@ //! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable //! by the control channel and MCP, and keeps tools testable without a UI. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; pub mod bbox; diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 7bb59c79b1..02acf76de0 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -46,6 +46,7 @@ //! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color //! left out stays a hole. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod centerline; mod contour; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a51817a7f1..948f1ad279 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4,6 +4,7 @@ //! (view/window) here and everything else to the engine. The same entry point serves menus, //! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] /// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update /// prompt shows both, and an AppImage's menu entry gets the icon. diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs new file mode 100644 index 0000000000..9ba395136c --- /dev/null +++ b/xtask/src/doc_tests.rs @@ -0,0 +1,98 @@ +//! Every library's doc tests deny unsafe code. +//! +//! Rustdoc compiles each doc test as a crate of its own, without the workspace's `[lints]` table +//! and without the library's own `#![forbid(unsafe_code)]`, so an `unsafe` block in a doc comment +//! passes `cargo test --doc`. Rustdoc adds the attributes in `#![doc(test(attr(...)))]` to every +//! doc test, so each library root carries `#![doc(test(attr(forbid(unsafe_code))))]`, or +//! `deny` where the library itself relies on the workspace's `deny`. `cargo xtask layers` runs +//! this check. + +use serde_json::Value; +use std::path::Path; + +/// Crate roots larger than this are reported instead of read. +const MAX_ROOT_BYTES: u64 = 8 * 1024 * 1024; + +/// The problems found in the workspace's library roots, one line each. +pub fn check(meta: &Value) -> Result, String> { + let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?; + let root = Path::new(meta["workspace_root"].as_str().unwrap_or_default()); + let mut out = Vec::new(); + for p in pkgs { + let name = p["name"].as_str().ok_or("package without name")?; + for t in p["targets"].as_array().into_iter().flatten() { + let kinds: Vec<&str> = t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let doc_tested = t["doctest"].as_bool() == Some(true) && kinds.iter().any(|k| matches!(*k, "lib" | "rlib" | "proc-macro")); + if !doc_tested { + continue; + } + let path = t["src_path"].as_str().ok_or_else(|| format!("{name}: library target without src_path"))?; + if let Some(problem) = check_root(name, root, Path::new(path))? { + out.push(problem); + } + } + } + out.sort(); + Ok(out) +} + +fn check_root(name: &str, root: &Path, path: &Path) -> Result, String> { + let shown = path.strip_prefix(root).unwrap_or(path).display(); + let len = std::fs::metadata(path).map_err(|e| format!("{shown}: {e}"))?.len(); + if len > MAX_ROOT_BYTES { + return Ok(Some(format!("{name}: {shown} is larger than {MAX_ROOT_BYTES} bytes"))); + } + let src = std::fs::read_to_string(path).map_err(|e| format!("{shown}: {e}"))?; + Ok(problem(&src).map(|p| format!("{name}: {shown}: {p}"))) +} + +/// What a library root is missing, or `None` when its doc tests deny unsafe code at least as +/// strictly as the library does. +fn problem(src: &str) -> Option<&'static str> { + let attrs: Vec = + src.lines().map(|l| l.chars().filter(|c| !c.is_whitespace()).collect::()).filter(|l| l.starts_with("#![")).collect(); + let forbids = attrs.iter().any(|a| a == "#![forbid(unsafe_code)]"); + let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("#![doc(test(") && a.contains(&format!("{level}(unsafe_code)"))); + if doc_test("forbid") { + None + } else if forbids { + Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]") + } else if doc_test("deny") { + None + } else { + Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]") + } +} + +#[cfg(test)] +mod tests { + use super::problem; + + #[test] + fn a_forbidding_library_needs_forbid_in_its_doc_tests() { + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert!(problem("#![forbid(unsafe_code)]\n").is_some_and(|p| p.contains("forbid(unsafe_code))))"))); + assert!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_some_and(|p| p.contains("forbid"))); + } + + #[test] + fn a_library_on_the_workspace_deny_needs_deny_or_forbid() { + assert_eq!(problem("//! Docs.\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert!(problem("//! Docs.\npub fn f() {}\n").is_some_and(|p| p.contains("deny(unsafe_code))))"))); + } + + #[test] + fn comments_other_lints_and_allow_do_not_count() { + assert!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n").is_some()); + assert!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n").is_some()); + assert!(problem("#![doc(test(attr(allow(unsafe_code))))]\n").is_some()); + assert!(problem("#![doc(test(attr(deny(warnings))))]\n").is_some()); + assert!(problem("#![deny(unsafe_code)]\n").is_some()); + } + + #[test] + fn spacing_and_other_attributes_in_the_list_are_accepted() { + assert_eq!(problem("#![doc(test(attr(deny(warnings), forbid( unsafe_code ))))]\n#![forbid(unsafe_code)]\n"), None); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2152369254..a09949f548 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -9,6 +9,7 @@ mod brands; mod bundle; mod cache_units; mod cursors; +mod doc_tests; mod grant_sites; mod ico; mod layers; @@ -200,7 +201,8 @@ pub fn metadata() -> Result { } fn cmd_layers() -> Result<(), String> { - let crates = layers::from_metadata(&metadata()?)?; + let meta = metadata()?; + let crates = layers::from_metadata(&meta)?; println!("Dependency layering (plan/architecture.md §3)\n"); println!("{:<28} {:<14} workspace deps", "crate", "layer"); for c in &crates { @@ -219,17 +221,18 @@ fn cmd_layers() -> Result<(), String> { .collect(); println!("{:<28} {:<14} {}", c.name, layers::describe(layers::classify(&c.name)), ws.join(", ")); } - let violations = layers::check(&crates); + let mut violations: Vec = layers::check(&crates).iter().map(ToString::to_string).collect(); + violations.extend(doc_tests::check(&meta)?); println!(); if violations.is_empty() { - println!("OK: {} crates, no layering violations.", crates.len()); + println!("OK: {} crates, no layering violations, and every library's doc tests deny unsafe code.", crates.len()); Ok(()) } else { println!("{} violation(s):", violations.len()); for v in &violations { println!(" - {v}"); } - Err(format!("{} layering violation(s)", violations.len())) + Err(format!("{} violation(s)", violations.len())) } } From 9995ffc36c7dc4beab3e10e6e8cc2ceb7d28056c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:53:40 -0800 Subject: [PATCH 36/65] Image Trace: drop an unfinished slider value when the selection changes A value typed into an Image Trace slider row or the Divider and not yet committed stayed in the field after another object was selected, so pressing Enter applied it to the newly selected object. The settings sliders (Threshold, Colors, Paths, Corners, Noise, Stroke) and the Divider are now keyed on the selection, so another selection starts a fresh field. This stands in for SliderField::edit_target (storytold/craft-libs#5024) until the craft-libs pin includes it; the pin bump replaces each id_salt with edit_target. --- crates/ui-egui/src/panels/image_trace.rs | 13 ++++- crates/ui-egui/src/panels/image_trace/rows.rs | 29 +++++++--- .../ui-egui/src/panels/image_trace/tests.rs | 58 +++++++++++++++++++ 3 files changed, 90 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 372d3117aa..fb30859192 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -299,9 +299,18 @@ pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(split) = selected_split(app) else { return }; // The canvas sets the divider to a ten-thousandth: a hundredth of a percent. let pct = (split * 10_000.0).round() / 100.0; + // Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a value + // typed for one object when another is selected. The pin bump replaces this with `edit_target`. + let target = crate::panels::selection_target(app); let edit = Field::new(tl!("Divider")) .show(ui, |ui, _| { - SliderField::new(tl!("Divider"), Bind::given(pct), 0.0..=100.0).layout(SliderFieldLayout::Inline).step(1.0).unit("%").show(ui).edit + SliderField::new(tl!("Divider"), Bind::given(pct), 0.0..=100.0) + .layout(SliderFieldLayout::Inline) + .step(1.0) + .unit("%") + .id_salt(("divider", &target)) + .show(ui) + .edit }) .inner; let Some(edit) = edit else { return }; @@ -1031,7 +1040,7 @@ fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list: } split_row(app, ui); - let data = RowsData::of(app); + let data = RowsData::of_selection(app); let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() }; let (main, advanced) = rows::settings_group(ui, |ui| { let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); diff --git a/crates/ui-egui/src/panels/image_trace/rows.rs b/crates/ui-egui/src/panels/image_trace/rows.rs index 2c87a42d50..cbcecc07bc 100644 --- a/crates/ui-egui/src/panels/image_trace/rows.rs +++ b/crates/ui-egui/src/panels/image_trace/rows.rs @@ -22,7 +22,7 @@ use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; use super::{MODES, PALETTES, ignore_color, palette_label}; use crate::VectorcraftApp; -use crate::panels::swatches; +use crate::panels::{SelectionTarget, selection_target, swatches}; /// Where the rows are shown. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -40,13 +40,21 @@ pub(crate) struct RowsData { pub(crate) libraries: Vec>, /// The active document's colour group names. pub(crate) groups: Vec, + /// The selection whose settings the rows show, for a host that follows the selection (the panel). A slider's + /// unfinished value is dropped when it changes. + pub(crate) target: Option, } impl RowsData { /// The lists for the active document. pub(crate) fn of(app: &VectorcraftApp) -> Self { // PLAN: assumed `swatches::library_entries(app: &VectorcraftApp) -> Vec>` (color-w10). - RowsData { libraries: swatches::library_entries(app), groups: swatch_groups(app) } + RowsData { libraries: swatches::library_entries(app), groups: swatch_groups(app), target: None } + } + + /// The lists for the active document, for rows that show the selection's settings. + pub(crate) fn of_selection(app: &VectorcraftApp) -> Self { + RowsData { target: Some(selection_target(app)), ..Self::of(app) } } } @@ -151,13 +159,18 @@ fn slider(key: &'static str, label: &'static str, range: RangeInclusive, un Slider { key, label, range, unit, default: 0.0 } } -fn slider_row(ui: &mut Ui, params: &mut Value, spec: Slider, enabled: bool, out: &mut RowsOutput) { +fn slider_row(ui: &mut Ui, params: &mut Value, data: &RowsData, spec: Slider, enabled: bool, out: &mut RowsOutput) { let Slider { key, label, range, unit, default } = spec; let value = params[key].as_f64().unwrap_or(default); let events = Field::new(label) .enabled(enabled) .show(ui, |ui, _| { let mut field = SliderField::new(label, Bind::given(value), range.clone()).layout(SliderFieldLayout::Inline).step(1.0).enabled(enabled); + // Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a + // value typed for one object when another is selected. The pin bump replaces this with `edit_target`. + if let Some(target) = &data.target { + field = field.id_salt((key, target)); + } if let Some(unit) = unit { field = field.unit(unit); } @@ -234,14 +247,14 @@ pub(crate) fn main_rows(ui: &mut Ui, params: &mut Value, data: &RowsData, host: _ if matches!(palette.as_str(), "fullTone" | "automatic") => slider("colorDetail", tl!("Colors"), 0.0..=100.0, Some("%")), _ => slider("colors", tl!("Colors"), 2.0..=256.0, None), }; - slider_row(ui, params, count, true, &mut out); + slider_row(ui, params, data, count, true, &mut out); out } /// The Advanced settings: fidelity, method, Create, snapping, shapes, grouping, gradients and Ignore Color, with an -/// eyedropper for Ignore Color when the host passes a `sampler`. `_data` and `_host` are the arguments of +/// eyedropper for Ignore Color when the host passes a `sampler`. `data` and `_host` are the arguments of /// [`main_rows`], so a host passes the same set to both. -pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _host: RowsHost, sampler: Option) -> RowsOutput { +pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, data: &RowsData, _host: RowsHost, sampler: Option) -> RowsOutput { let mut out = RowsOutput::default(); let mode = text(params, "mode", "blackAndWhite"); for spec in [ @@ -249,7 +262,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _ slider("corners", tl!("Corners"), 0.0..=100.0, Some("%")), slider("noise", tl!("Noise"), 1.0..=100.0, Some("px")), ] { - slider_row(ui, params, spec, true, &mut out); + slider_row(ui, params, data, spec, true, &mut out); } // Flat Logo always paints biggest shapes first with a hair of overlap, so there is no choice. if mode != "logo" { @@ -282,7 +295,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _ params[key] = json!(!create(params, key)); out.picked(); } - slider_row(ui, params, Slider { default: 10.0, ..slider("strokeWidth", tl!("Stroke"), 1.0..=100.0, Some("px")) }, strokes, &mut out); + slider_row(ui, params, data, Slider { default: 10.0, ..slider("strokeWidth", tl!("Stroke"), 1.0..=100.0, Some("px")) }, strokes, &mut out); } // (Black and White has one colour and Flat Logo flat ones: no gradients to find.) let gradients = mode == "grayscale" || mode == "color"; diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 00516ffd34..c97e3e1c27 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -599,6 +599,64 @@ fn the_divider_slider_keeps_an_exact_divider_and_a_drag_is_one_undo_step() { assert_eq!(undo(&panel.app()), steps + 1, "one undo step for the edit"); } +/// Two traced objects with the same settings, the first one selected: the app, the first and the second object. +fn two_traced_objects(app: VectorcraftApp) -> (VectorcraftApp, NodeId, NodeId) { + let mut app = app; + let a = first_selected(&app).unwrap().id; + app.run("edit.duplicate", json!({})).unwrap(); + let b = first_selected(&app).unwrap().id; + assert_ne!(a, b); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + (app, a, b) +} + +/// Types `text` into the number box of the slider row `name` without finishing the edit. +fn type_unfinished(panel: &mut Panel, name: &str, text: &str) { + panel.click_role(name, craft::ui::contract::Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); +} + +/// A value typed into a settings slider for one Image Trace object, and not finished, is dropped when another +/// object is selected: Enter afterwards changes neither object. +#[test] +fn an_unfinished_slider_value_is_dropped_when_another_object_is_selected() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let (app, a, b) = two_traced_objects(traced_app()); + let mut panel = panel_over(app); + panel.frame(); + let threshold = param(&panel.app(), "threshold"); + let steps = undo(&panel.app()); + type_unfinished(&mut panel, "Threshold", "3"); + select(&mut panel, b); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(param(&panel.app(), "threshold"), threshold, "B keeps its threshold"); + assert_eq!(undo(&panel.app()), steps, "nothing was traced"); + select(&mut panel, a); + assert_eq!(param(&panel.app(), "threshold"), threshold, "A keeps its threshold"); +} + +/// A value typed into the Divider for one Image Trace object, and not finished, is dropped when another object is +/// selected: Enter afterwards moves neither divider. +#[test] +fn an_unfinished_divider_value_is_dropped_when_another_object_is_selected() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + app.run("imageTrace.setView", json!({"view": "split", "split": 0.4})).unwrap(); + let (app, a, b) = two_traced_objects(app); + let mut panel = panel_over(app); + panel.frame(); + let steps = undo(&panel.app()); + type_unfinished(&mut panel, "Divider", "8"); + select(&mut panel, b); + assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "B has the same divider"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "B keeps its divider"); + assert_eq!(undo(&panel.app()), steps, "no undo step"); + select(&mut panel, a); + assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "A keeps its divider"); +} + /// Properties shows the Divider slider of the selected Image Trace object in the Split view only, /// with its name and value for screen readers. #[test] From bf8c0978a5f458b4a471ee4d806b49a4ca80556f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:53:55 -0800 Subject: [PATCH 37/65] Home: head the recent files "Recent Files" The Home screen headed its recent files with the framework's word "Recent". It now shows "Recent Files", in the interface language where the catalog translates it; other languages keep the framework's translation. This is a word override on the start screen until craft-libs#4890 is in the craft-libs pin; the pin bump that takes it sets the start screen's recent_title and removes the override. --- crates/ui-egui/src/canvas/home.rs | 27 ++++++++++++++++++++++----- crates/ui-egui/src/tests/home.rs | 16 ++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index 5034e23f17..b7d6620836 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -1,12 +1,13 @@ use craft::behavior::{ColumnWidth, IconId}; +use craft::i18n::WordSet as _; use craft::ui::buttons::{Link, LinkLook}; use craft::ui::contract::{Bind, Gap, Pad, Props as _, Show as _, ShowContainer as _, clicked}; use craft::ui::display::Text; use craft::ui::layout::CellAlign; use craft::ui::layout_components::{Grid, Stack}; -use craft::ui::runtime::env::{Env, Overrides, with_env}; +use craft::ui::runtime::env::{Env, Overrides, WordRows, WordsOverride, with_env}; use craft::ui::sections::Section; -use craft::ui::shell::{RecentFile, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template}; +use craft::ui::shell::{RecentFile, ShellWords, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template}; use craft::ui::style::{SurfaceKind, TypeRole}; use super::{Ui, VectorcraftApp, json}; @@ -45,9 +46,14 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } let mut pressed = None; let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); - // Production's community links read in the accent alone, with no underline. - let plain_links = |overrides: &mut Overrides| { + let words = recent_words(app.ui_language()); + // Production's community links read in the accent alone, with no underline, and the recent files are headed + // "Recent Files". + let set_env = |overrides: &mut Overrides| { overrides.values.set(LinkLook::Plain); + if let Some(words) = words { + overrides.words = Some(WordsOverride::Overlay(words)); + } }; // Learn follows the presets, which stand right under New and Open as in production 0.24.1. let start = StartScreen::new(Bind::bound(&mut app.ui.home_view), Bind::bound(&mut app.ui.home_sort), &recent) @@ -62,7 +68,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { .links(&links) .links_title(tl!("Community")) .section(StartPlace::AfterSections, |ui, _| learn(ui, &mut pressed)); - let out = with_env(&mut child, plain_links, |ui| start.show(ui)); + let out = with_env(&mut child, set_env, |ui| start.show(ui)); for action in out.actions { run_action(app, action); } @@ -73,6 +79,17 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } } +/// VectorCraft's heading for the Home screen's recent files, "Recent Files", over the framework's "Recent". Outside +/// English, a language whose catalog does not translate it keeps the framework's translation. +// Workaround for craft-libs#4890: once the craft-libs pin includes it, the start screen's `recent_title` heads the +// list, and this word row is removed. +fn recent_words(lang: crate::i18n::Lang) -> Option { + const ENGLISH: &str = "Recent Files"; + let shown = crate::i18n::tr(lang, ENGLISH); + let word = ShellWords::word("startScreen.recent")?; + (lang == crate::i18n::Lang::EN || shown != ENGLISH).then(|| WordRows::new().row(word, shown)) +} + /// What the start screen's user did. A command that fails says why in the status bar (#6160). fn run_action(app: &mut VectorcraftApp, action: StartAction) { fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) { diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 904de40932..b0fb87fd02 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -164,6 +164,22 @@ fn home_lists_recent_files_and_a_click_opens_one() { assert!(!app.ui.status.is_empty(), "a file that can't be opened says so"); } +/// The Home screen heads its recent files "Recent Files", in the interface language where the catalog translates it. +#[test] +fn home_heads_the_recent_files_recent_files() { + let shown = |lang: &str| { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.session.prefs.interface_language = lang.into(); + app.ui.recent_files = vec![std::env::temp_dir().join("vectorcraft-home-heading").join("Drawing.svg").to_string_lossy().into_owned()]; + home_screen(app) + }; + let home = shown("en"); + assert!(home.shows("Recent Files"), "the recent files are headed Recent Files"); + assert!(!home.shows("Recent"), "not Recent alone"); + let home = shown("de"); + assert!(home.shows("Zuletzt geöffnete Dateien"), "German shows the catalog's Recent Files"); +} + /// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A /// tutorial shows the Learn panel at its steps and no document is opened; the Quick skill guide /// shows its list of skills. From 4ecd645b2a25c29378638efb0fdf7a10b13fc46a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:01:44 -0800 Subject: [PATCH 38/65] Home: read the German Recent Files heading from the catalog in its test The test compares the German heading with the catalog's translation of "Recent Files" instead of a fixed phrase, so a change to the German row does not fail it. Without a German row, it checks that the framework's heading stays. --- crates/ui-egui/src/tests/home.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index b0fb87fd02..bc9b5b0e5a 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -167,6 +167,7 @@ fn home_lists_recent_files_and_a_click_opens_one() { /// The Home screen heads its recent files "Recent Files", in the interface language where the catalog translates it. #[test] fn home_heads_the_recent_files_recent_files() { + use crate::i18n::LangExt as _; let shown = |lang: &str| { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); app.session.prefs.interface_language = lang.into(); @@ -177,7 +178,12 @@ fn home_heads_the_recent_files_recent_files() { assert!(home.shows("Recent Files"), "the recent files are headed Recent Files"); assert!(!home.shows("Recent"), "not Recent alone"); let home = shown("de"); - assert!(home.shows("Zuletzt geöffnete Dateien"), "German shows the catalog's Recent Files"); + let german = crate::i18n::tr(crate::i18n::Lang::from_code("de").expect("German is registered"), "Recent Files"); + if german == "Recent Files" { + assert!(!home.shows("Recent Files"), "without a catalog row German keeps the framework's heading"); + } else { + assert!(home.shows(german), "German shows the catalog's Recent Files, {german}"); + } } /// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A From 44ac2010184ee247f43cedfc0c731b4e7e355db1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:15:06 -0800 Subject: [PATCH 39/65] =?UTF-8?q?Print:=20the=20File=20=E2=80=BA=20Print?= =?UTF-8?q?=20dialog=20is=20titled=20Print?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared print dialog titles its sections layout "Print Settings", so File › Print opened under that title. While the Print dialog is open in Print mode, the window's shell now shows its dialogs with the dialog's title word set to "Print". The print preset editor keeps "Print Settings". This is temporary: storytold/craft-libs#4891 lets the app set the title, and once the craft-libs pin includes it the override is removed and the dialog is titled with HostedPrint::title. --- crates/ui-egui/src/app.rs | 11 ++++--- crates/ui-egui/src/dialogs/print.rs | 11 ++++++- crates/ui-egui/src/dialogs/tests_print.rs | 36 +++++++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 442ddaffbf..b75aec3934 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -11,7 +11,7 @@ use craft::ui::docking::IconGroupSeparator; use craft::ui::list::{CommandHighlight, ThumbRows}; use craft::ui::menu::{MenuTitleLook, MenuTitlePad}; use craft::ui::patterns::form_dialogs::PresetCardLook; -use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey}; +use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env}; use craft::ui::runtime::frame::{FrameInput, FrameOutput}; use craft::ui::runtime::toast::{self, Toast}; use craft::ui::runtime::windows::WindowHost; @@ -762,7 +762,7 @@ impl VectorcraftApp { let mut control_bar_place = chrome::control_bar_place(&self.ui); // PLAN: assumed `chrome::window_title(&VectorcraftApp) -> String` (shell-01 A1 names the call, no row gives its signature; shell-w9). let window_title = chrome::window_title(self); - let shown = AppShell::new(WindowKey::main()) + let shell = AppShell::new(WindowKey::main()) .title_bar_if(true, |_| None, chrome::app_bar) .options_bar( self.ui.control_bar, @@ -792,8 +792,11 @@ impl VectorcraftApp { .body(|ui, cx, app: &mut VectorcraftApp| { panel_docking::show(app, ui, cx.shell().is_some_and(|shell| shell.panels_hidden())); crate::place::window_files(app, ui); - }) - .show(ui, self); + }); + // The shell shows the window's dialogs under these words. Temporary: removed once the craft-libs pin includes + // storytold/craft-libs#4891 (`dialogs::print::title_words`). + let words = dialogs::print::title_words(self).map(WordsOverride::Overlay); + let shown = with_env(ui, |env| env.words = words, |ui| shell.show(ui, self)); chrome::set_control_bar_place(&mut self.ui, control_bar_place); if shown.screen_mode != given { self.ui.follow_screen_mode(shown.screen_mode); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 4863a67cb3..b55edcbe6d 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -33,7 +33,7 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKi use craft::ui::patterns::presets::{NamedPresetEvent, PresetError, PresetRow}; use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::env::{LengthUnits, UnitKind}; +use craft::ui::runtime::env::{LengthUnits, UnitKind, WordRows}; use craft::ui::shell::WindowDialogs; use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText}; use serde_json::{Map, Value, json}; @@ -518,6 +518,15 @@ pub(super) fn settings(fields: &DialogFields) -> Value { Value::Object(nested(p)) } +/// The words that title File › Print "Print" while the Print dialog is open in Print mode, for the window's shell to +/// show its dialogs under. The framework titles a dialog in sections "Print Settings". Temporary: this is removed, and +/// the dialog is titled with `HostedPrint::title`, once the craft-libs pin includes storytold/craft-libs#4891. +pub(crate) fn title_words(app: &VectorcraftApp) -> Option { + app.print_dialog.open.as_ref().filter(|open| open.mode == PrintMode::Print)?; + let title = craft::i18n::Word::keyed("printDialog.title", "Print Settings"); + Some(WordRows::new().row(title, tl!("Print"))) +} + /// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was /// dragged to, the presets and OK. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 9340f14350..7f99bc817b 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -143,6 +143,42 @@ fn pages(pdf: &[u8]) -> usize { vectorcraft_pdf::info(pdf, None).unwrap().pages.len() } +/// The texts the whole window paints, with where each is drawn, once the open dialog has faded in (each frame is a +/// quarter second on). +fn window_texts(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> { + let ctx = ctx(app); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)); + let mut texts = vec![]; + for k in 0..4 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let out = crate::testing::app_frame(app, &ctx, raw); + texts = crate::tests_labels::text_shapes(&out) + .into_iter() + .map(|(t, transform)| (t.galley.text().to_string(), transform * t.galley.rect.translate(t.pos.to_vec2()))) + .collect(); + } + texts +} + +#[test] +fn the_print_dialog_is_titled_print_and_the_preset_editor_keeps_its_title() { + let (mut printing, _) = app(); + printing.run("file.print", json!({})).unwrap(); + let texts = window_texts(&mut printing); + let painted = |texts: &[(String, egui::Rect)], text: &str| texts.iter().filter(|(t, _)| t == text).map(|(_, r)| *r).collect::>(); + assert!(painted(&texts, "Print Settings").is_empty(), "the Print dialog is not titled Print Settings: {texts:?}"); + let preset_row = painted(&texts, "Print Preset"); + let preset_row = preset_row.first().expect("the Print Preset row is shown"); + // The title sits above the dialog's first row; the Print button sits below it. + assert!(painted(&texts, "Print").iter().any(|title| title.bottom() <= preset_row.top()), "the dialog is titled Print: {texts:?}"); + + // The preset editor keeps the framework's title. + let (mut editing, _) = app(); + editing.run("ui.printPresetDialog", json!({"preset": vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET})).unwrap(); + let texts = window_texts(&mut editing); + assert!(!painted(&texts, "Print Settings").is_empty(), "the preset editor is titled Print Settings: {texts:?}"); +} + #[test] fn print_sends_every_page_to_the_chosen_printer_and_keeps_the_settings() { let (mut app, jobs) = app(); From e6ca6ed1a9355ce800d3a62abb9197134b557d87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:20:43 -0800 Subject: [PATCH 40/65] Doc tests: read whole attributes and skip comments in the unsafe-code check The check read crate-root attributes one physical line at a time and compared whole attribute strings. It accepted a doc-test attribute that sat inside a block comment or a string literal, rejected a valid attribute split over several lines, and did not see `unsafe_code` in a grouped list such as `#![forbid(unsafe_code, unused_must_use)]`, so it accepted `deny` in the doc tests of such a library. The check now removes comments and literal contents, reads each `#![...]` attribute up to its matching bracket, and reads lint lists item by item, in the library's own attribute and in the doc-test one. --- xtask/src/doc_tests.rs | 196 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 192 insertions(+), 4 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 9ba395136c..ef434ab8bd 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -49,10 +49,9 @@ fn check_root(name: &str, root: &Path, path: &Path) -> Result, St /// What a library root is missing, or `None` when its doc tests deny unsafe code at least as /// strictly as the library does. fn problem(src: &str) -> Option<&'static str> { - let attrs: Vec = - src.lines().map(|l| l.chars().filter(|c| !c.is_whitespace()).collect::()).filter(|l| l.starts_with("#![")).collect(); - let forbids = attrs.iter().any(|a| a == "#![forbid(unsafe_code)]"); - let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("#![doc(test(") && a.contains(&format!("{level}(unsafe_code)"))); + let attrs = inner_attributes(src); + let forbids = attrs.iter().any(|a| a.strip_prefix("forbid(").and_then(|rest| rest.strip_suffix(')')).is_some_and(names_unsafe_code)); + let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("doc(test(") && calls(a, level).into_iter().any(names_unsafe_code)); if doc_test("forbid") { None } else if forbids { @@ -64,6 +63,171 @@ fn problem(src: &str) -> Option<&'static str> { } } +/// The body of every `#![...]` attribute in `src`, without whitespace, read across line breaks. +/// Comments are skipped, and string and character literals are read as empty. +fn inner_attributes(src: &str) -> Vec { + let code: Vec = code_only(src).chars().filter(|c| !c.is_whitespace()).collect(); + let mut out = Vec::new(); + let mut i = 0; + while i + 2 < code.len() { + if code[i] != '#' || code[i + 1] != '!' || code[i + 2] != '[' { + i += 1; + continue; + } + let start = i + 3; + let mut depth = 1usize; + let mut j = start; + while j < code.len() && depth > 0 { + match code[j] { + '[' => depth += 1, + ']' => depth -= 1, + _ => {} + } + j += 1; + } + if depth > 0 { + break; + } + out.push(code[start..j - 1].iter().collect()); + i = j; + } + out +} + +/// `src` with line and (nested) block comments replaced by a space, and the contents of string, +/// raw string and character literals removed. +fn code_only(src: &str) -> String { + let c: Vec = src.chars().collect(); + let mut out = String::with_capacity(src.len()); + let mut i = 0; + while i < c.len() { + let next = c.get(i + 1).copied(); + let ident_before = i > 0 && (c[i - 1].is_alphanumeric() || c[i - 1] == '_'); + match c[i] { + '/' if next == Some('/') => { + while i < c.len() && c[i] != '\n' { + i += 1; + } + out.push(' '); + } + '/' if next == Some('*') => { + let mut depth = 0usize; + while i < c.len() { + if c[i] == '/' && c.get(i + 1) == Some(&'*') { + depth += 1; + i += 2; + } else if c[i] == '*' && c.get(i + 1) == Some(&'/') { + depth = depth.saturating_sub(1); + i += 2; + if depth == 0 { + break; + } + } else { + i += 1; + } + } + out.push(' '); + } + 'r' | 'b' if !ident_before && raw_string_hashes(&c, i).is_some() => { + let (open, hashes) = raw_string_hashes(&c, i).unwrap_or((i, 0)); + let mut j = open + 1; + while j < c.len() && !(c[j] == '"' && (1..=hashes).all(|k| c.get(j + k) == Some(&'#'))) { + j += 1; + } + out.push_str("\"\""); + i = j + 1 + hashes; + } + '"' => { + let mut j = i + 1; + while j < c.len() && c[j] != '"' { + j += if c[j] == '\\' { 2 } else { 1 }; + } + out.push_str("\"\""); + i = j + 1; + } + '\'' if next == Some('\\') => { + let mut j = i + 3; + while j < c.len() && c[j] != '\'' { + j += 1; + } + out.push_str("''"); + i = j + 1; + } + '\'' if c.get(i + 2) == Some(&'\'') => { + out.push_str("''"); + i += 3; + } + ch => { + out.push(ch); + i += 1; + } + } + } + out +} + +/// For a raw string literal starting at `i` (`r"`, `r#"`, `br"`...), the index of its opening +/// quote and its number of `#`s. +fn raw_string_hashes(c: &[char], i: usize) -> Option<(usize, usize)> { + let mut j = i; + if c.get(j) == Some(&'b') { + j += 1; + } + if c.get(j) != Some(&'r') { + return None; + } + j += 1; + let hashes = c[j..].iter().take_while(|&&ch| ch == '#').count(); + (c.get(j + hashes) == Some(&'"')).then_some((j + hashes, hashes)) +} + +/// The argument lists of every `name(...)` in `attr` that starts a list item. +fn calls<'a>(attr: &'a str, name: &str) -> Vec<&'a str> { + let mut out = Vec::new(); + let pat = format!("{name}("); + for (at, _) in attr.match_indices(&pat) { + if at > 0 && !matches!(attr.as_bytes()[at - 1], b'(' | b',') { + continue; + } + let start = at + pat.len(); + let mut depth = 1usize; + for (k, ch) in attr[start..].char_indices() { + match ch { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + out.push(&attr[start..start + k]); + break; + } + } + _ => {} + } + } + } + out +} + +/// Whether a lint list such as `unsafe_code,unused_must_use` names `unsafe_code`. +fn names_unsafe_code(list: &str) -> bool { + let mut depth = 0usize; + let mut item_start = 0; + for (k, ch) in list.char_indices().chain(std::iter::once((list.len(), ','))) { + match ch { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + if &list[item_start..k] == "unsafe_code" { + return true; + } + item_start = k + 1; + } + _ => {} + } + } + false +} + #[cfg(test)] mod tests { use super::problem; @@ -95,4 +259,28 @@ mod tests { fn spacing_and_other_attributes_in_the_list_are_accepted() { assert_eq!(problem("#![doc(test(attr(deny(warnings), forbid( unsafe_code ))))]\n#![forbid(unsafe_code)]\n"), None); } + + #[test] + fn block_comments_and_string_literals_do_not_count() { + assert!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n").is_some()); + assert!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n").is_some()); + assert!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n").is_some()); + assert!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n").is_some()); + assert_eq!(problem("const Q: char = '\\'';\nconst S: &str = \"/*\";\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + } + + #[test] + fn an_attribute_may_span_several_lines() { + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(\n forbid(unsafe_code)\n)))]\n"), None); + assert_eq!(problem("#![forbid(\n unsafe_code\n)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + } + + #[test] + fn grouped_lint_lists_are_read_item_by_item() { + let grouped = "#![forbid(unsafe_code, unused_must_use)]\n"; + assert!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")).is_some_and(|p| p.contains("forbid"))); + assert_eq!(problem(&format!("{grouped}#![doc(test(attr(forbid(unused_must_use, unsafe_code))))]\n")), None); + assert!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_none()); + assert!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n").is_some()); + } } From 6b442ae207b30bd82de690ed40bd46c1d5f22f6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:24:15 -0800 Subject: [PATCH 41/65] Canvas: selection anchors paint from one kept mesh A large selection slowed every canvas frame. The canvas cloned the anchor paths each frame for two BezierOverlay calls, and the overlay at the pinned craft-libs laid out its scene and flattened and stroked every outline on every paint, even with nothing changed. The anchors, handles and outlines now paint through AnchorMarks, a display-only component that builds the same shapes BezierOverlay paints under BezierTool::Anchors and keeps them as one tessellated mesh. The mesh is kept while the marks, the canvas view, the clip, the display scale, the tessellation options and the theme look stay the same, so an idle frame clones and tessellates nothing. AnchorMarks is temporary. craft-libs#4900 and craft-libs#4928 make BezierOverlay keep its layout and paint its marks as one mesh; when the craft-libs pin includes both, AnchorMarks is removed and the canvas goes back to BezierOverlay::display with the marks revision. Tests compare the shapes AnchorMarks paints with what BezierOverlay paints under the Selection, Direct Selection and Curvature tools, for each handle mode and handle style, a selected segment, and the Path Options color and thickness. Others check that idle frames tessellate nothing, and that a press on a shown anchor and Tab from the canvas reach what they reached with BezierOverlay. --- crates/ui-egui/src/canvas/selection.rs | 484 ++++++++++++++++++- crates/ui-egui/src/canvas/selection/tests.rs | 211 ++++++++ 2 files changed, 670 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 4f50576df8..e201066396 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -8,15 +8,15 @@ use std::hash::{Hash, Hasher}; use std::sync::{Arc, Weak}; use craft::behavior::Input; -use craft::behavior::Metrics; +use craft::behavior::{CanvasView, Metrics}; use craft::draw::ui::{ - AnchorsShown, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleStyle, HandlesShown, Knot, KnotRef, PathOptionsSettings, PathSelection, + AnchorsShown, EditPath, EditSubpath, HandleSide, HandleStyle, HandlesShown, Knot, KnotRef, MAX_ANCHORS, PathOptionsSettings, PathSelection, SegmentMark, }; use craft::theme::Srgba; use craft::ui::canvas::{CanvasSpace, canvas_space}; -use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline}; -use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; +use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline, path_runs}; +use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _, Styled as _}; use craft::ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2}; use vectorcraft_doc::{Document, NodeId, NodeKind}; @@ -622,6 +622,457 @@ impl Component for SelectionDots<'_> { } } +// TEMPORARY: craft-libs#4900 and craft-libs#4928. `BezierOverlay` at the pinned craft-libs lays out its scene and +// flattens and strokes every outline on every paint, and the canvas cloned the paths for it each frame, so a large +// selection stalled every frame. `AnchorMarks` draws what the overlay draws under `BezierTool::Anchors`, from the +// kept marks, and keeps it as one mesh while the marks, the view and the look stay the same. When the craft-libs pin +// includes both pull requests, remove `AnchorMarks` and this section and go back to +// `BezierOverlay::display(...).revision(marks.key)`. + +/// The marks' look, resolved from the theme: the colors and widths `BezierOverlay` paints anchors, handles and +/// outlines with. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +struct AnchorMarksStyle { + #[style(metrics)] + metrics: Metrics, + /// The outline of a path without a color of its own, and the fill of a selected anchor. + line: craft::ui::style::StyleColor, + /// The fill of a hollow anchor and of a handle's end, per state. + fill: craft::ui::style::Stateful, + /// The edge of an anchor or a handle's end, for a path without a color of its own. + edge: craft::ui::style::StyleColor, + /// An anchor's side. + anchor: f32, + /// A handle end's side with Large handles. + large: f32, + thin: f32, + medium: f32, + thick: f32, + /// How far outside the canvas an anchor or a handle's end is still drawn. + reach: f32, +} + +/// [`AnchorMarksStyle`] for one paint, with the fill resolved: what the kept mesh is built from besides the marks. +#[derive(Clone, Copy, Debug, PartialEq)] +struct MarkLook { + line: Color32, + fill: Color32, + edge: Color32, + anchor: f32, + large: f32, + thin: f32, + medium: f32, + thick: f32, + reach: f32, +} + +/// Everything the kept mesh of the anchor marks depends on. +#[derive(Clone, Copy, Debug, PartialEq)] +struct MeshKey { + /// [`marks_key`] of the marks. + marks: u64, + view: CanvasView, + rect: Rect, + clip: Rect, + pixels_per_point: f32, + options: egui::epaint::TessellationOptions, + look: MarkLook, +} + +/// The anchor marks tessellated as one mesh, and what they were tessellated from. +pub(crate) struct KeptMesh { + key: MeshKey, + mesh: Arc, +} + +/// One set of anchors as `BezierOverlay` took it: the paths, which anchors are selected and how they show. +struct MarkSet<'a> { + paths: &'a [EditPath], + selection: &'a PathSelection, + handles: HandlesShown, + shown: AnchorsShown, + segment_mark: SegmentMark, + options: &'a PathOptionsSettings, +} + +/// The two sets the canvas shows: the paths whose handles the tools drag, then the paths whose anchors show selected +/// without handles. +fn mark_sets(anchors: &Anchors) -> [MarkSet<'_>; 2] { + [ + MarkSet { + paths: &anchors.paths, + selection: &anchors.selection, + handles: anchors.handles, + shown: anchors.shown, + segment_mark: anchors.segment_mark, + options: &anchors.options, + }, + MarkSet { + paths: &anchors.plain, + selection: &anchors.plain_selection, + handles: HandlesShown::OneAnchor, + shown: anchors.shown, + segment_mark: SegmentMark::default(), + options: &anchors.options, + }, + ] +} + +/// The anchors, handles and outlines of the selection, painted over the canvas as one kept mesh: no pointer, key or +/// accessibility node, as `BezierOverlay` under `BezierTool::Anchors` has none. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(canvas_control, content_painter)] +struct AnchorMarks<'a> { + #[common] + common: Common, + anchors: &'a Anchors, + /// [`marks_key`] of `anchors`. + key: u64, + kept: &'a std::cell::RefCell>, +} + +impl Component for AnchorMarks<'_> { + const ROLE: Role = Role::GRAPHICS_OBJECT; + const ALT_ROLES: &'static [Role] = &[Role::None]; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + type Style = AnchorMarksStyle; + type Output = Response; + + fn style(cx: &StyleCx<'_>, _: AnchorMarksStyleKey) -> AnchorMarksStyle { + let tokens = cx.tokens; + let handle = cx.handle(); + AnchorMarksStyle { + metrics: Metrics::new(), + line: cx.color(tokens.color.overlay.line), + fill: handle.fill, + edge: handle.stroke, + anchor: tokens.size.handle.sm, + large: handle.side, + thin: tokens.stroke.thin, + medium: tokens.stroke.medium, + thick: tokens.stroke.thick, + reach: tokens.size.hit.target, + } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 { + egui::Vec2::ZERO + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(space) = canvas_space(&cx.env) else { return }; + let style = &cx.style; + let look = MarkLook { + line: style.line.egui(), + fill: cx.resolve(&style.fill).egui(), + edge: style.edge.egui(), + anchor: style.anchor, + large: style.large, + thin: style.thin, + medium: style.medium, + thick: style.thick, + reach: style.reach, + }; + let painter = ui.content_painter(cx); + let key = MeshKey { + marks: self.key, + view: space.view, + rect: cx.rect, + clip: painter.painter.clip_rect(), + pixels_per_point: painter.pixels_per_point(), + options: painter.painter.ctx().tessellation_options(|options| *options), + look, + }; + let shapes = || { + let mut shapes = Vec::new(); + for set in mark_sets(self.anchors) { + mark_shapes(&mut shapes, &set, &space.view, cx.rect, &look); + } + shapes + }; + #[cfg(test)] + if tests::RAW_MARKS.with(std::cell::Cell::get) { + painter.painter.extend(shapes()); + return; + } + let mut kept = self.kept.borrow_mut(); + let mesh = match kept.as_ref().filter(|kept| kept.key == key) { + Some(kept) => Arc::clone(&kept.mesh), + None => { + let shapes = shapes(); + let mesh = Arc::new(tessellate(shapes, &key)); + *kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh) }); + mesh + } + }; + if !mesh.is_empty() { + painter.painter.add(Shape::Mesh(mesh)); + } + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.role(Role::None); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// `shapes` as one mesh, tessellated as the frame would tessellate them, except that a small filled circle is a +/// polygon rather than a disc from the font atlas, so a later change to the atlas cannot leave the mesh wrong. +fn tessellate(shapes: Vec, key: &MeshKey) -> egui::Mesh { + #[cfg(test)] + tests::MESHES_BUILT.with(|built| built.set(built.get() + 1)); + let mut tessellator = egui::epaint::Tessellator::new(key.pixels_per_point, key.options, [1, 1], Vec::new()); + tessellator.set_clip_rect(key.clip); + let mut mesh = egui::Mesh::default(); + for shape in shapes { + tessellator.tessellate_shape(shape, &mut mesh); + } + mesh +} + +/// Shows the selection's anchors, handles and outlines from `marks`. +fn paint_anchor_marks(ui: &mut egui::Ui, rect: Rect, marks: &SelectionMarks) { + let anchors = &marks.anchors; + if anchors.paths.is_empty() && anchors.plain.is_empty() { + return; + } + #[cfg(test)] + if tests::OVERLAY_MARKS.with(std::cell::Cell::get) { + tests::paint_with_overlay(ui, rect, anchors); + return; + } + AnchorMarks { common: Common::new(), anchors, key: marks.key, kept: &marks.mesh }.label("Anchors").show_at(ui, rect); +} + +/// The fill of an anchor or a handle's end. +#[derive(Clone, Copy)] +enum MarkFill { + /// The look's fill. + Look, + /// The path's color, or the look's line without one: a selected anchor. + Path, +} + +/// The egui shapes `BezierOverlay` paints for `set` under `BezierTool::Anchors`, in its order: every outline, the +/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors. +fn mark_shapes(out: &mut Vec, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook) { + let options = set.options; + let option_color = options.color.map(|[r, g, b]| Color32::from(Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0))); + let path_color = |path: &EditPath| path.color.map(Color32::from); + let anchor_side = options.anchor_size.unwrap_or(look.anchor); + let handle_side = if options.handles == HandleStyle::Large { look.large } else { look.anchor }; + let circles = set.shown == AnchorsShown::Curvature; + let line = |out: &mut Vec, points: Vec, closed: bool, segment: bool, color: Option| { + let named = if segment { look.thick } else { look.medium }; + let ink = color.unwrap_or(look.line); + match options.thickness { + Some(thickness) => { + if segment { + stroke_line(out, points.clone(), closed, Stroke::new(thickness, ink)); + stroke_line(out, points, closed, Stroke::new(named, ink)); + } else { + stroke_line(out, points, closed, Stroke::new(thickness, ink)); + } + } + None => stroke_line(out, points, closed, Stroke::new(named, ink)), + } + }; + for path in set.paths { + let color = path.color.map(Color32::from).or(option_color); + for sub in &path.subpaths { + for (points, closed) in path_runs(view, &sub.bez_path()) { + line(out, points, closed, false, color); + } + } + if set.segment_mark == SegmentMark::Line + && let Some(s) = set.selection.segment.filter(|_| set.selection.path == Some(path.key)) + && let Some(curve) = path.subpaths.get(s.subpath).and_then(|sub| sub.segment(s.knot)) + { + let mut segment = BezPath::new(); + segment.move_to(curve.p0); + segment.curve_to(curve.p1, curve.p2, curve.p3); + for (points, closed) in path_runs(view, &segment) { + line(out, points, closed, true, color); + } + } + } + let total: usize = set.paths.iter().map(EditPath::anchor_count).sum(); + if set.shown == AnchorsShown::Hidden || total > MAX_ANCHORS { + return; + } + let mark = |out: &mut Vec, at: egui::Pos2, side: f32, circle: bool, fill: MarkFill, color: Option| { + let fill = match fill { + MarkFill::Look => look.fill, + MarkFill::Path => color.unwrap_or(look.line), + }; + let edge = Stroke::new(look.thin, color.unwrap_or(look.edge)); + if circle { + let radius = side / 2.0; + out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill, stroke: Stroke::NONE })); + out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill: Color32::TRANSPARENT, stroke: edge })); + } else { + let square = Rect::from_center_size(at, egui::Vec2::splat(side)); + out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, fill, Stroke::NONE, StrokeKind::Inside))); + out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, Color32::TRANSPARENT, edge, StrokeKind::Inside))); + } + }; + // A direction handle: its line from the anchor, then its end. + let handle = |out: &mut Vec, path: &EditPath, knot: KnotRef, end: egui::Pos2| { + let color = path_color(path); + if let Some(knot) = path.knot(knot) { + out.push(Shape::line(vec![view.to_screen(knot.anchor), end], Stroke::new(look.thin, color.unwrap_or(look.line)))); + } + mark(out, end, handle_side, true, MarkFill::Look, color); + }; + let selected = Selected::of(set.selection); + let near = rect.expand(look.reach); + let shown = if circles { Vec::new() } else { shown_handles(set.paths, set.selection, &selected, set.handles, view) }; + let mut handles = shown.iter().peekable(); + for (at, path) in set.paths.iter().enumerate() { + for knot_ref in path.knot_refs() { + let Some(knot) = path.knot(knot_ref) else { continue }; + let anchor = view.to_screen(knot.anchor); + if near.contains(anchor) && set.selection.shows(path.key, knot_ref.subpath) { + let fill = if selected.draws_selected(path.key, knot_ref) { MarkFill::Path } else { MarkFill::Look }; + mark(out, anchor, anchor_side, circles, fill, path_color(path)); + } + while let Some(&(_, _, end)) = handles.next_if(|(p, k, _)| *p == at && *k == knot_ref) { + if near.contains(end) { + handle(out, path, knot_ref, end); + } + } + } + } + if circles || set.handles == HandlesShown::All { + return; + } + // The handles of anchors selected in paths other than the edited one. + let edited = set.selection.path.map_or(0, |_| set.selection.anchors.len()); + for path in set.paths { + if set.selection.path == Some(path.key) || !selected.listed.contains(&path.key) { + continue; + } + let own = PathSelection::new(Some(path.key), Vec::new(), None); + let listed = |key: u64, knot: KnotRef| selected.others.contains(&(key, knot)); + for (_, knot, end) in handles_of(std::slice::from_ref(path), &own, listed, selected.others_len + edited, set.handles, view) { + handle(out, path, knot, end); + } + } +} + +/// Strokes the run `points`, closed or open, on its centre line. +fn stroke_line(out: &mut Vec, points: Vec, closed: bool, stroke: Stroke) { + if closed { + if stroke.is_empty() { + return; + } + let mut line = egui::epaint::PathStroke::from(stroke); + line.kind = StrokeKind::Middle; + out.push(Shape::closed_line(points, line)); + } else { + out.push(Shape::line(points, stroke)); + } +} + +/// The anchors a [`PathSelection`] selects, gathered into sets once. +struct Selected { + path: Option, + anchors: std::collections::HashSet, + others: std::collections::HashSet<(u64, KnotRef)>, + listed: std::collections::HashSet, + others_len: usize, +} + +impl Selected { + fn of(sel: &PathSelection) -> Self { + Self { + path: sel.path, + anchors: sel.anchors.iter().copied().collect(), + others: sel.others.iter().flat_map(|(key, knots)| knots.iter().map(|knot| (*key, *knot))).collect(), + listed: sel.others.iter().map(|(key, _)| *key).collect(), + others_len: sel.others.iter().map(|(_, knots)| knots.len()).sum(), + } + } + + /// Whether `knot` of `path` is a selected anchor of the edited path. + fn has_anchor(&self, path: u64, knot: KnotRef) -> bool { + self.path == Some(path) && self.anchors.contains(&knot) + } + + /// Whether `knot` of `path` draws selected. + fn draws_selected(&self, path: u64, knot: KnotRef) -> bool { + self.has_anchor(path, knot) || self.others.contains(&(path, knot)) + } +} + +/// The handles that show for `sel`, in path order, in then out: each path's index, the knot and the end on screen. +fn shown_handles( + paths: &[EditPath], + sel: &PathSelection, + selected: &Selected, + shown: HandlesShown, + view: &CanvasView, +) -> Vec<(usize, KnotRef, egui::Pos2)> { + handles_of(paths, sel, |path, knot| selected.has_anchor(path, knot), sel.selected_len(), shown, view) +} + +/// The handles that show, with `has_anchor` answering whether a knot is a selected anchor and `count` the number of +/// selected anchors `HandlesShown::OneAnchor` counts. A retracted handle and the handles of a subpath the selection +/// does not show are left out. +fn handles_of( + paths: &[EditPath], + sel: &PathSelection, + has_anchor: impl Fn(u64, KnotRef) -> bool, + count: usize, + shown: HandlesShown, + view: &CanvasView, +) -> Vec<(usize, KnotRef, egui::Pos2)> { + let mut out = Vec::new(); + for (index, path) in paths.iter().enumerate() { + let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| { + let (a, b) = path.subpaths.get(s.subpath)?.segment_ends(s.knot)?; + Some((KnotRef::new(s.subpath, a), KnotRef::new(s.subpath, b))) + }); + for knot_ref in path.knot_refs().filter(|k| sel.shows(path.key, k.subpath)) { + let Some(knot) = path.knot(knot_ref) else { continue }; + for side in [HandleSide::In, HandleSide::Out] { + let of_selection = || { + has_anchor(path.key, knot_ref) + || next_to_selected(path, &has_anchor, knot_ref, side) + || segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref)) + }; + let wanted = match shown { + HandlesShown::All => true, + HandlesShown::OneAnchor => count == 1 && of_selection(), + _ => of_selection(), + }; + if wanted && !knot.retracted(side) { + out.push((index, knot_ref, view.to_screen(knot.handle(side)))); + } + } + } + } + out +} + +/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out handle +/// or the next anchor's in handle, across a closed subpath's seam too. +fn next_to_selected(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool { + let Some(sub) = path.subpaths.get(knot.subpath) else { return false }; + let count = sub.knots.len(); + if side == HandleSide::Out { + return sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))); + } + let previous = (knot.knot + count.saturating_sub(1)) % count.max(1); + sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous))) +} + /// Whether the active tool draws its own points over the paths: the Curvature tool while it has a draft. fn tool_draws_points(app: &mut VectorcraftApp) -> bool { if app.session.tool_id() != "curvature" { @@ -675,27 +1126,7 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } outline.show_at(ui, rect); } - let anchors = &marks.anchors; - if !anchors.paths.is_empty() { - let mut paths = anchors.paths.clone(); - // The marks only show the selection: the tools make the edits. - let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection) - .tool(BezierTool::Anchors) - .handles(anchors.handles) - .anchors(anchors.shown) - .segment_mark(anchors.segment_mark) - .path_options(&anchors.options) - .show_at(ui, rect); - } - if !anchors.plain.is_empty() { - let mut paths = anchors.plain.clone(); - let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) - .tool(BezierTool::Anchors) - .handles(HandlesShown::OneAnchor) - .anchors(anchors.shown) - .path_options(&anchors.options) - .show_at(ui, rect); - } + paint_anchor_marks(ui, rect, &marks); let dots = &marks.dots; if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) { SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect); @@ -722,6 +1153,8 @@ pub(crate) struct SelectionMarks { outlines: Vec, anchors: Anchors, dots: Dots, + /// The anchor marks as one mesh, from the last paint ([`AnchorMarks`]). + mesh: std::cell::RefCell>, } impl SelectionMarks { @@ -738,6 +1171,7 @@ impl SelectionMarks { outlines: outlines(app, st), anchors: anchors(app, st, tool, tool_points), dots: dots(app, st), + mesh: std::cell::RefCell::new(None), } } diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 42e0bc620b..850dd453a5 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -942,6 +942,217 @@ fn grouping_selected_anchors_by_path_compares_each_path_a_bounded_number_of_time assert!(compared.get() < 2 * 2001, "{} comparisons for 2,001 entries", compared.get()); } +thread_local! { + /// Whether `show` draws the anchor marks with `BezierOverlay`, as it did before [`AnchorMarks`]. + pub(super) static OVERLAY_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Whether [`AnchorMarks`] paints its shapes one by one instead of as a mesh. + pub(super) static RAW_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many meshes [`AnchorMarks`] tessellated. + pub(super) static MESHES_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The anchor marks as `show` drew them before [`AnchorMarks`]: two `BezierOverlay`s under `BezierTool::Anchors`. +pub(super) fn paint_with_overlay(ui: &mut egui::Ui, rect: Rect, anchors: &Anchors) { + use craft::draw::ui::{BezierOverlay, BezierTool}; + use craft::ui::contract::Bind; + if !anchors.paths.is_empty() { + let mut paths = anchors.paths.clone(); + let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection) + .tool(BezierTool::Anchors) + .handles(anchors.handles) + .anchors(anchors.shown) + .segment_mark(anchors.segment_mark) + .path_options(&anchors.options) + .show_at(ui, rect); + } + if !anchors.plain.is_empty() { + let mut paths = anchors.plain.clone(); + let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) + .tool(BezierTool::Anchors) + .handles(HandlesShown::OneAnchor) + .anchors(anchors.shown) + .path_options(&anchors.options) + .show_at(ui, rect); + } +} + +/// One frame of the canvas alone with `events`. +fn canvas_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui)); + out.textures_delta.clear(); + out +} + +/// The shapes a canvas frame paints, with the anchor marks drawn by `BezierOverlay` (`overlay`) or by +/// [`AnchorMarks`] one shape at a time. +fn canvas_shapes(app: &mut VectorcraftApp, ctx: &egui::Context, overlay: bool) -> Vec { + OVERLAY_MARKS.with(|on| on.set(overlay)); + RAW_MARKS.with(|on| on.set(!overlay)); + canvas_frame(app, ctx, vec![]); + let out = canvas_frame(app, ctx, vec![]); + OVERLAY_MARKS.with(|on| on.set(false)); + RAW_MARKS.with(|on| on.set(false)); + crate::tests::labels::flat_painted_shapes(&out.shapes) +} + +/// A canvas app with one curve, the task bar off and every frame drawn on this thread. +fn canvas_app() -> (VectorcraftApp, NodeId) { + let mut app = blank(); + app.ui.task_bar = false; + app.canvas.worker_started = true; + let curve = id_of(&app.run("path.create", json!({"d": "M40 40 C60 10 90 10 110 40 S160 70 180 40 L180 90"})).unwrap()); + (app, curve) +} + +// The anchor marks paint the shapes `BezierOverlay` paints for the same marks: under the Selection tool, Direct +// Selection with a partial selection, a selected segment and the Curvature tool, with handles shown for one anchor or +// for every selected anchor, each handle style, and the Path Options color and thickness on paths without a color. +#[test] +fn the_anchor_marks_paint_what_the_bezier_overlay_paints() { + let (mut app, curve) = scene(); + let ctx = crate::testing::ui_context(); + let compare = |app: &mut VectorcraftApp, case: &str, change: &dyn Fn(&mut Anchors)| { + canvas_frame(app, &ctx, vec![]); + if let Some(marks) = app.canvas.selection_marks.as_mut() { + change(&mut marks.anchors); + } + let overlay = canvas_shapes(app, &ctx, true); + let marks = canvas_shapes(app, &ctx, false); + assert!(overlay.len() > 20, "{case}: the overlay painted the marks ({} shapes)", overlay.len()); + let differs = overlay.iter().zip(&marks).position(|(a, b)| a != b); + assert!( + overlay == marks, + "{case}: {} shapes from the overlay, {} from the marks, first difference at {differs:?}", + overlay.len(), + marks.len() + ); + }; + let same = |_: &mut Anchors| {}; + app.select_tool("selection"); + compare(&mut app, "the Selection tool", &same); + for (multiple, style) in [(true, "solid"), (false, "hollow"), (true, "large")] { + app.session.prefs.show_handles_multiple_anchors = multiple; + app.session.prefs.handle_style = style.into(); + app.session.prefs.anchor_size = 5; + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1], [0, 2]], "mode": "set"})).unwrap(); + compare(&mut app, &format!("Direct Selection, multiple {multiple}, {style}"), &same); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + compare(&mut app, &format!("one anchor, multiple {multiple}, {style}"), &same); + } + // A segment selected in place keeps the revision, so the kept marks are dropped to build them again. + let pick_segment = |app: &mut VectorcraftApp| { + app.session.active_mut().unwrap().selection.segments.insert(curve, [(0, 1)].into_iter().collect()); + app.canvas.selection_marks = None; + }; + pick_segment(&mut app); + compare(&mut app, "a selected segment", &|anchors| assert!(anchors.selection.segment.is_some(), "a segment is selected")); + app.session.active_mut().unwrap().selection.segments.clear(); + app.run("select.all", json!({})).unwrap(); + compare(&mut app, "every handle", &|anchors| anchors.handles = HandlesShown::All); + let options = |anchors: &mut Anchors| { + anchors.options.color = Some([10, 200, 30]); + anchors.options.thickness = Some(3.0); + for path in anchors.paths.iter_mut().chain(&mut anchors.plain) { + path.color = None; + } + }; + compare(&mut app, "the Path Options color and thickness", &options); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + app.select_tool("directSelection"); + pick_segment(&mut app); + compare(&mut app, "a selected segment with a thickness", &options); + compare(&mut app, "paths without a color", &|anchors| { + for path in anchors.paths.iter_mut().chain(&mut anchors.plain) { + path.color = None; + } + }); + app.session.active_mut().unwrap().selection.segments.clear(); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + app.select_tool("curvature"); + compare(&mut app, "the Curvature tool", &same); +} + +// The canvas tessellates the anchor marks once and paints the kept mesh while nothing they show changes: frames that +// change nothing tessellate none, and a new selection, a scroll of the view and a new zoom each tessellate them once. +#[test] +fn an_idle_frame_tessellates_no_anchor_marks() { + let (mut app, curve) = canvas_app(); + app.select_tool("directSelection"); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let ctx = crate::testing::ui_context(); + let frames = |app: &mut VectorcraftApp, n: usize| { + let before = MESHES_BUILT.with(std::cell::Cell::get); + for _ in 0..n { + canvas_frame(app, &ctx, vec![]); + } + MESHES_BUILT.with(std::cell::Cell::get) - before + }; + assert_eq!(frames(&mut app, 3), 1, "the first frame tessellates the marks"); + assert_eq!(frames(&mut app, 10), 0, "frames that change nothing"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + assert_eq!(frames(&mut app, 5), 1, "a new selection"); + app.view_mut().unwrap().center.x += 40.0; + assert_eq!(frames(&mut app, 5), 1, "a scroll"); + app.view_mut().unwrap().zoom *= 2.0; + assert_eq!(frames(&mut app, 5), 1, "a new zoom"); + app.run("select.none", json!({})).unwrap(); + assert_eq!(frames(&mut app, 5), 0, "nothing selected, nothing to tessellate"); +} + +/// What a press-drag and Tab presses did: the curve's bounds, its selected anchors, and the focused accessibility node +/// after each Tab. +type Reached = (vectorcraft_geom::Rect, Vec<(usize, usize)>, Vec>); + +/// What the canvas does with a press-drag from the curve's third anchor under `tool`, then Tab presses. +fn press_and_tab(tool: &str, overlay: bool) -> Reached { + OVERLAY_MARKS.with(|on| on.set(overlay)); + let (mut app, curve) = canvas_app(); + app.select_tool(tool); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + canvas_frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + // The curve's third anchor, and a drag away from it. + let (from, to) = (xf.to_screen(Point::new(110.0, 40.0)), xf.to_screen(Point::new(130.0, 60.0))); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + canvas_frame(&mut app, &ctx, vec![button(from, true)]); + for i in 1..=5 { + canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * (i as f32 / 5.0))]); + } + canvas_frame(&mut app, &ctx, vec![button(to, false)]); + let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let focused = (0..4) + .map(|_| { + let out = canvas_frame(&mut app, &ctx, vec![tab.clone()]); + let update = out.platform_output.accesskit_update.as_ref().expect("an accessibility tree"); + update.nodes.iter().find(|(id, _)| *id == update.focus).and_then(|(_, node)| node.label().map(str::to_owned)) + }) + .collect(); + OVERLAY_MARKS.with(|on| on.set(false)); + let st = app.session.active().unwrap(); + let bounds = st.doc.bounds_of(&[curve], false).unwrap(); + let mut chosen: Vec<(usize, usize)> = st.selection.partial(curve).map(|set| set.iter().copied().collect()).unwrap_or_default(); + chosen.sort_unstable(); + (bounds, chosen, focused) +} + +// A press on a shown anchor reaches the tool and Tab from the canvas goes where it went with `BezierOverlay`: the +// Selection tool drags the whole path, Direct Selection drags the anchor, and Tab keeps the focus on the canvas. +#[test] +fn a_press_on_an_anchor_and_tab_reach_what_they_reached_with_the_overlay() { + for tool in ["selection", "directSelection"] { + let overlay = press_and_tab(tool, true); + let marks = press_and_tab(tool, false); + assert_eq!(marks, overlay, "{tool}"); + let (bounds, ..) = &marks; + assert!((bounds.x0 - 40.0).abs() > 1.0 || (bounds.x1 - 180.0).abs() > 1.0, "{tool}: the drag edited the curve: {bounds:?}"); + } +} + thread_local! { /// How many times the canvas built the selection's marks ([`SelectionMarks::build`]). pub(super) static MARKS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; From f7a8f86cea677c43a1cbe0f6875788e0459db266 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:41:31 -0800 Subject: [PATCH 42/65] Panels: Character and Paragraph show no scroll bar over an empty state that fits With no text selected, the Character and Paragraph panels showed a vertical scroll bar over "No text selected" in a group tall enough for the message. A scroll body measures its content beside the bar's lane first, and in that narrower width the message wraps onto one more line and overflows, so the bar stayed. While a panel shows only its empty state, its body now scrolls with an overlay bar, which takes no room from the content. The message is laid out at the group's full width, and a group too short for it still scrolls. This is temporary until the craft-libs pin includes craft-libs#4898, which fixes the measuring run; the pin bump removes the dock case and the two shows_only_empty_state helpers. --- crates/ui-egui/src/dock.rs | 87 +++++++++++++++++++++++++- crates/ui-egui/src/panels/character.rs | 5 ++ crates/ui-egui/src/panels/paragraph.rs | 5 ++ 3 files changed, 96 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ea6dcb4c69..7289a7a0d3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -40,12 +40,26 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { { // These panels lay out forms. Collection panels own their scrolling viewport // and reserve their own footer outside it. - Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body)); + let scroll = if empty_state_only(app, id) { Scroll::vertical().overlay().at_rest() } else { Scroll::vertical() }; + Stack::new().id_salt(id).fill().scroll(scroll).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body)); } None => memoized(app, ui, id, icon_panel_body), } } +/// Whether panel `id` is the Character or Paragraph panel showing only its empty state. Its body then scrolls with an +/// overlay bar, which leaves the message its full width: a scroll body measures its content beside the bar's lane, and a +/// message that wraps onto one more line there kept a bar it did not need. This case is temporary: the craft-libs pin +/// bump that includes craft-libs#4898, which fixes the measuring run, removes it and the two `shows_only_empty_state` +/// helpers. +fn empty_state_only(app: &VectorcraftApp, id: &str) -> bool { + match id { + "character" => panels::character::shows_only_empty_state(app), + "paragraph" => panels::paragraph::shows_only_empty_state(app), + _ => false, + } +} + /// The Layers panel's body. fn layers_body(p: &mut BodyProps<'_>, ui: &mut Ui) { #[cfg(test)] @@ -180,6 +194,8 @@ mod tests { static DIRECT: Cell = const { Cell::new(false) }; /// The panel [`draw`] shows. static SHOWN: RefCell<&'static str> = const { RefCell::new("") }; + /// The height of the body [`draw_unscrolled`] drew last. + static UNSCROLLED_HEIGHT: Cell = const { Cell::new(0.0) }; } pub(super) fn count_run() { @@ -356,6 +372,75 @@ mod tests { assert!(panel.shows_value_with(|v| v.starts_with('7')), "the panel shows the 7 pt weight: {:?}", panel.values()); } + /// The Character or Paragraph empty state, drawn without a scroll body; [`UNSCROLLED_HEIGHT`] holds its height. + fn draw_unscrolled(app: &mut VectorcraftApp, ui: &mut Ui) { + let top = ui.min_rect().top(); + crate::panels::show_icon_panel(app, ui, SHOWN.with(|s| *s.borrow())); + UNSCROLLED_HEIGHT.with(|h| h.set(ui.min_rect().bottom() - top)); + } + + /// Panel `id` drawn by `draw` over a document with nothing selected, in `room`. + fn empty_panel(id: &'static str, draw: fn(&mut VectorcraftApp, &mut Ui), room: egui::Vec2) -> Panel { + SHOWN.with(|s| *s.borrow_mut() = id); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.room(room); + panel.frame(); + panel.frame(); + panel + } + + /// The empty state's texts as `panel` paints them, in paint order. + fn empty_state_texts(panel: &Panel, message: &str) -> Vec<(String, egui::Rect)> { + panel.texts().into_iter().filter(|(text, _)| text == "No text selected" || text == message).collect() + } + + /// In a dock group tall enough for the Character or Paragraph empty state at the group's full width, the dock body + /// lays the message out as an unscrolled body does, and the wheel does not move it: the body shows no scroll bar + /// and keeps no room for one. The groups are a little wider than the widths at which the message wraps onto one + /// line fewer, so beside a bar's lane it would take one more line, and from the empty state's own height to about + /// one line more. + #[test] + fn an_empty_state_that_fits_its_group_does_not_scroll() { + let cases = [ + ("character", "Select a text object to edit its character attributes."), + ("paragraph", "Select a text object to edit its paragraph attributes."), + ]; + for (id, message) in cases { + let height_at = |width: f32| { + let tall = empty_panel(id, draw_unscrolled, egui::vec2(width, 1600.0)); + assert_eq!(empty_state_texts(&tall, message).len(), 2, "{id} shows its empty state: {:?}", tall.texts()); + UNSCROLLED_HEIGHT.with(Cell::get).ceil() + }; + let mut widths = Vec::new(); + let mut last = height_at(120.0); + for step in 1..=50 { + let width = 120.0 + 4.0 * step as f32; + let height = height_at(width); + if height < last { + widths.extend([width, width + 2.0]); + } + last = height; + } + assert!(widths.len() >= 4, "{id}: the message wraps onto fewer lines as the group widens"); + for width in widths { + let height = height_at(width); + for extra in [0.0, 4.0, 8.0, 12.0] { + let room = egui::vec2(width, height + extra); + let unscrolled = empty_panel(id, draw_unscrolled, room); + let mut docked = empty_panel(id, draw, room); + docked.scroll_at(egui::pos2(width / 2.0, room.y / 2.0), -120.0); + assert_eq!( + empty_state_texts(&docked, message), + empty_state_texts(&unscrolled, message), + "{id} at {room:?}: the docked empty state is laid out and stays where the unscrolled one is" + ); + } + } + } + } + /// The texts `id`'s body paints after idle frames, shown in its `MemoView` or, with `direct`, directly. fn texts(id: &'static str, direct: bool) -> Vec<(String, egui::Rect)> { DIRECT.with(|d| d.set(direct)); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 677eec516a..256a5c1c91 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1262,6 +1262,11 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow } } +/// Whether [`show`] draws only the empty state: no type is selected and the Snap to Glyph options are hidden. +pub(crate) fn shows_only_empty_state(app: &VectorcraftApp) -> bool { + text_style(app).is_none() && !app.ui.snap_to_glyph_options +} + /// The Character panel: the controls over the selected type (an empty state without any), then the /// Snap to Glyph options while they are shown, which need no type. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 8bc176f74d..97896eeb95 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -848,6 +848,11 @@ fn localized_control_words() -> WordRows { .fold(WordRows::new(), |rows, (word, translated)| rows.row(word, translated)) } +/// Whether [`show`] draws only the empty state: no type is selected. +pub(crate) fn shows_only_empty_state(app: &VectorcraftApp) -> bool { + text_style(app).is_none() +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((_, para)) = text_style(app) else { super::empty_state(ui, "pilcrow", tl!("No text selected"), tl!("Select a text object to edit its paragraph attributes.")); From 820a17f3aa749c73bffd3606ae7f01872c37c217 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:45:49 -0800 Subject: [PATCH 43/65] Docs: pathItems.removeAll counts only text inside the mask group The visible-text exception applies only to text inside the group that is the clipping path. Text beside the clipping path in the clipping group does not keep it clipping, and a clipping group nested in the mask counts only when its own clipping path keeps geometry. --- docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index b24494f654..936fade68e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3245,7 +3245,8 @@ through `$`: `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`, `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that - clips when a visible text object that lays out glyphs stays in it, because the text then clips. Hidden text, text + is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then + clips. Text beside the clipping path in the clipping group does not count. Hidden text, text in a hidden group, blank text without a list marker, area text too short for its first line, and text that a clipping group nested in the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 150bc78e60..acf447d1af 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a clipping group when a visible text object that lays out glyphs stays in the group, because the text then clips. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 48ef8740e94c12c4d5c7d205b7ad8545a47f7e2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:33:13 -0800 Subject: [PATCH 44/65] Direct Selection: Ctrl held before pressing a handle mirrors the opposite handle With Direct Selection chosen, Cmd/Ctrl lends the Selection tool for the press. That loan also took presses on the end of a shown direction handle, so a Ctrl-drag on a handle moved the whole object (and anything selected with it), or drew a marquee where no object was under the handle. Only Ctrl added after the drag began mirrored the opposite handle. A new Tool::keeps_cmd_press lets the active tool keep a Cmd/Ctrl press. Direct Selection keeps one without Alt on the end of a shown handle of a path, of type on a path, or of a selected blend spine anchor, so the drag mirrors the opposite handle, with Shift constraining it. The session's lent_tool_at asks it, so the press, the cursor and the status bar agree. A press elsewhere, on a handle of the bounding box the lent Selection tool shows, or with Cmd+Alt (Group Selection) is still lent as before. docs/gaps.md and docs/ui-parity.md describe the press. --- crates/engine/src/tooling.rs | 7 +- .../engine/tests/it/direct_handle_mirror.rs | 80 +++++++++++++++++++ crates/tools/src/direct.rs | 27 +++++++ crates/tools/src/lib.rs | 6 ++ docs/gaps.md | 2 +- docs/ui-parity.md | 2 +- 6 files changed, 120 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 05dde4c156..37d1282f26 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -409,11 +409,14 @@ impl Session { /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when /// the Selection tool keeps a Cmd press on a selected object to select the object behind it /// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd - /// press armed ([`Self::behind_armed`]). + /// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press + /// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown + /// direction handle to mirror the opposite handle. fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { let id = self.lent_tool(self.tool.id(), mods)?; let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); - (!behind).then_some(id) + let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods)); + (!behind && !kept).then_some(id) } /// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks diff --git a/crates/engine/tests/it/direct_handle_mirror.rs b/crates/engine/tests/it/direct_handle_mirror.rs index bfe8db75a0..732319f675 100644 --- a/crates/engine/tests/it/direct_handle_mirror.rs +++ b/crates/engine/tests/it/direct_handle_mirror.rs @@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() { assert_eq!(s.doc().unwrap().history.undo.len(), before.undo); } +#[test] +fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + let end = Point::new(180.0, 100.0); + pointer(&mut s, PointerKind::Down, end, cmd()); + assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(s.tool_id(), "directSelection"); +} + +#[test] +fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + let p = anchor(&s, id).p; + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted); + assert_eq!(s.tool_id(), "directSelection"); + let raw = Point::new(180.0, 150.0); + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, raw, shifted); +} + +#[test] +fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + // A second object widens the selection's bounding box so its top-middle handle lands on the + // curve's outgoing handle end at (180, 100). + let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true})); + run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]})); + let boxed = ViewInfo { show_bbox: true, ..view() }; + let end = Point::new(180.0, 100.0); + s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap(); + assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool"); + s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); +} + +#[test] +fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let a = anchor(&s, id); + let both = Mods { alt: true, ..cmd() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both); + assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle"); + pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both); + assert_eq!(s.tool_id(), "directSelection"); + assert_eq!(anchor(&s, id), a); +} + #[test] fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() { let mut s = session(); @@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() { assert_content(&s, &after); } +#[test] +fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() { + let mut s = session(); + let id = blend(&mut s); + let (a, keys, _) = blend_state(&s, id); + pointer(&mut s, PointerKind::Down, a.h_out, cmd()); + assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + pointer(&mut s, PointerKind::Up, q, cmd()); + let (after, after_keys, _) = blend_state(&s, id); + near(after.p, a.p); + assert_mirrored(after, q, AnchorKind::Smooth); + assert_eq!(after_keys, keys, "the key objects did not move"); +} + #[test] fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() { let mut s = session(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c1c4bcbfb2..06723b8fcf 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1046,6 +1046,33 @@ impl Tool for DirectSelectionTool { self.lent_cmd = value.as_bool().unwrap_or(false); } } + /// A Cmd/Ctrl press without Alt on the end of a shown direction handle (a path's, type on a + /// path's or a selected blend spine anchor's) stays with Direct Selection, so the drag mirrors + /// the opposite handle ([`DirectSelectionTool::mirrors`]). A press on a handle of the bounding + /// box the lent Selection tool shows still goes to that tool, and so does a press anywhere else, + /// including one that a press of the tool gives to something it checks before the handles (a + /// corner widget, a bracket of type on a path, a gradient mesh point). + fn keeps_cmd_press(&self, cx: &ToolContext, p: Point, mods: Mods) -> bool { + if self.group || mods.alt || crate::select::bbox_handle_at(cx, p) { + return false; + } + let point = cx.point_tol(); + // The order of the checks is the order `pointer` tries them in on a press. + let ev = PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods); + if CornerDrag::hit(cx, &ev, true).is_some_and(|c| !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w)))) { + return false; + } + if !over_path_type_anchor(cx, p) && BracketDrag::hit_any(cx, &ev).is_some() { + return false; + } + if self.spine.filter(|(id, _)| cx.selection.contains(*id)).and_then(|sel| hit_spine_handle(cx, sel, p, point)).is_some() { + return true; + } + if self.mesh.hit(cx, &cx.selection.objects, p).is_some() { + return false; + } + hit_handle(cx, p, point).is_some() + } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved /// goes back and the tool waits for the next press (#1743). diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..81a67e4ffb 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -278,6 +278,12 @@ pub trait Tool: Send { fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option { None } + /// Does a press at `p` with Cmd/Ctrl and `mods` held stay with the tool, instead of going to + /// the selection tool the session lends for Cmd/Ctrl? Direct Selection keeps a press on a shown + /// direction handle, where Cmd/Ctrl mirrors the opposite handle. + fn keeps_cmd_press(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> bool { + false + } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. diff --git a/docs/gaps.md b/docs/gaps.md index 79fdb40586..953373bfb2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -189,7 +189,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. -- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. +- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. Control/Command held before pressing the end of a shown direction handle also mirrors: that press stays with Direct Selection, while a press anywhere else, or on a handle of the bounding box, is still lent to the Selection tool. The Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. - **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a2b7812ee9..ccb16f35cf 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -283,7 +283,7 @@ Every parity table on this page has a Headless column: the Summary table (12 are | Drag a curved segment to bend it, a straight one to move its anchors | done | | unknown | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | unknown | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | unknown | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/it/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | unknown | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag or held before pressing the handle (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan away from handle ends and on bounding box handles, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/it/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | unknown | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | unknown | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | unknown | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | unknown | From 5277ec20ef30bc92e09e6b9a8ca1eb25d13e991f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:37:22 -0800 Subject: [PATCH 45/65] Tests: canvas painted points read the anchor marks as shapes The canvas tests that look for a mark at a point read circles, rectangles and lines from the frame. The selection's anchor marks now paint as one mesh, so painted_points has AnchorMarks paint the shapes the mesh is made of for its frame. --- crates/ui-egui/src/canvas/selection.rs | 2 +- crates/ui-egui/src/canvas/selection/tests.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index e201066396..c2d53fcf97 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -1237,4 +1237,4 @@ fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) } #[cfg(test)] -mod tests; +pub(super) mod tests; diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 850dd453a5..42adf76890 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -946,7 +946,7 @@ thread_local! { /// Whether `show` draws the anchor marks with `BezierOverlay`, as it did before [`AnchorMarks`]. pub(super) static OVERLAY_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Whether [`AnchorMarks`] paints its shapes one by one instead of as a mesh. - pub(super) static RAW_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; + pub(in crate::canvas) static RAW_MARKS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// How many meshes [`AnchorMarks`] tessellated. pub(super) static MESHES_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index df0d8fc387..e7fec25534 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -267,10 +267,12 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { } /// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the -/// points of lines and paths. +/// points of lines and paths. The selection's anchor marks paint as the shapes their mesh is made of. fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + super::selection::tests::RAW_MARKS.with(|on| on.set(true)); let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + super::selection::tests::RAW_MARKS.with(|on| on.set(false)); out.textures_delta.clear(); let mut points = vec![]; for shape in flat_shapes(out.shapes) { From a520deb991e51508386dfa8176f2b2f8089f8add Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:55:35 -0800 Subject: [PATCH 46/65] Doc tests: assert the exact report in the unsafe-code check's tests CI's test-lint step failed with only-weak at xtask/src/doc_tests.rs:250: every assertion in comments_other_lints_and_allow_do_not_count checked only that problem() returned Some. Such a test still passes when the check reports the wrong problem, for example when a commented-out #![forbid(unsafe_code)] is counted and the forbid message is returned instead of the deny message. The tests now compare problem() with the exact message for each case, and two cases cover a commented-out forbid on either side. The other tests in the file that checked only is_some, is_none or a substring compare the full result too. --- xtask/src/doc_tests.rs | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index ef434ab8bd..1ed8871ceb 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -232,27 +232,32 @@ fn names_unsafe_code(list: &str) -> bool { mod tests { use super::problem; + const NEEDS_DENY: Option<&str> = Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]"); + const NEEDS_FORBID: Option<&str> = Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]"); + #[test] fn a_forbidding_library_needs_forbid_in_its_doc_tests() { assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); - assert!(problem("#![forbid(unsafe_code)]\n").is_some_and(|p| p.contains("forbid(unsafe_code))))"))); - assert!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_some_and(|p| p.contains("forbid"))); + assert_eq!(problem("#![forbid(unsafe_code)]\n"), NEEDS_FORBID); + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID); } #[test] fn a_library_on_the_workspace_deny_needs_deny_or_forbid() { assert_eq!(problem("//! Docs.\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); assert_eq!(problem("#![doc(test(attr(forbid(unsafe_code))))]\n"), None); - assert!(problem("//! Docs.\npub fn f() {}\n").is_some_and(|p| p.contains("deny(unsafe_code))))"))); + assert_eq!(problem("//! Docs.\npub fn f() {}\n"), NEEDS_DENY); } #[test] fn comments_other_lints_and_allow_do_not_count() { - assert!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n").is_some()); - assert!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n").is_some()); - assert!(problem("#![doc(test(attr(allow(unsafe_code))))]\n").is_some()); - assert!(problem("#![doc(test(attr(deny(warnings))))]\n").is_some()); - assert!(problem("#![deny(unsafe_code)]\n").is_some()); + assert_eq!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(allow(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(warnings))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![deny(unsafe_code)]\n"), NEEDS_DENY); + assert_eq!(problem("// #![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![forbid(unsafe_code)]\n// #![doc(test(attr(forbid(unsafe_code))))]\n"), NEEDS_FORBID); } #[test] @@ -262,10 +267,10 @@ mod tests { #[test] fn block_comments_and_string_literals_do_not_count() { - assert!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n").is_some()); - assert!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n").is_some()); - assert!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n").is_some()); - assert!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n").is_some()); + assert_eq!(problem("#![forbid(unsafe_code)]\n/*\n#![doc(test(attr(forbid(unsafe_code))))]\n*/\n"), NEEDS_FORBID); + assert_eq!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n"), NEEDS_DENY); + assert_eq!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n"), NEEDS_DENY); + assert_eq!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n"), NEEDS_DENY); assert_eq!(problem("const Q: char = '\\'';\nconst S: &str = \"/*\";\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); } @@ -278,9 +283,9 @@ mod tests { #[test] fn grouped_lint_lists_are_read_item_by_item() { let grouped = "#![forbid(unsafe_code, unused_must_use)]\n"; - assert!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")).is_some_and(|p| p.contains("forbid"))); + assert_eq!(problem(&format!("{grouped}#![doc(test(attr(deny(unsafe_code))))]\n")), NEEDS_FORBID); assert_eq!(problem(&format!("{grouped}#![doc(test(attr(forbid(unused_must_use, unsafe_code))))]\n")), None); - assert!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_none()); - assert!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n").is_some()); + assert_eq!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n"), NEEDS_DENY); } } From 233ae38bfe1b83c570b35f670407b551ffcd64b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:03:39 -0800 Subject: [PATCH 47/65] Home: require the German Recent Files row in the heading test The test skipped its heading check when the German catalog had no Recent Files row, so a lost heading passed in that case. It now asserts that the row exists and that Home shows its text. --- crates/ui-egui/src/tests/home.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index bc9b5b0e5a..66aba4b3b8 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -179,11 +179,8 @@ fn home_heads_the_recent_files_recent_files() { assert!(!home.shows("Recent"), "not Recent alone"); let home = shown("de"); let german = crate::i18n::tr(crate::i18n::Lang::from_code("de").expect("German is registered"), "Recent Files"); - if german == "Recent Files" { - assert!(!home.shows("Recent Files"), "without a catalog row German keeps the framework's heading"); - } else { - assert!(home.shows(german), "German shows the catalog's Recent Files, {german}"); - } + assert_ne!(german, "Recent Files", "the German catalog translates Recent Files"); + assert!(home.shows(german), "German shows the catalog's Recent Files, {german}"); } /// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A From 8387f54b97d17d2c4f0616652d41fa09b82f5cdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:05:15 -0800 Subject: [PATCH 48/65] Doc tests: count only crate-level attributes in the unsafe-code check The check read every #![...] attribute in a library root, including ones inside a module's braces. A root with mod tests { #![doc(test(attr(deny(unsafe_code))))] } and no crate-level attribute passed, although an attribute inside a module does not apply to the crate's other doc tests. A #![forbid(unsafe_code)] inside a module was also read as the library forbidding unsafe code. Attributes inside braces are now skipped, with a test for each case. --- xtask/src/doc_tests.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 1ed8871ceb..2cc73d2ce9 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -63,14 +63,21 @@ fn problem(src: &str) -> Option<&'static str> { } } -/// The body of every `#![...]` attribute in `src`, without whitespace, read across line breaks. -/// Comments are skipped, and string and character literals are read as empty. +/// The body of every crate-level `#![...]` attribute in `src`, without whitespace, read across +/// line breaks. Attributes inside braces (a module, a function) are skipped, comments are +/// skipped, and string and character literals are read as empty. fn inner_attributes(src: &str) -> Vec { let code: Vec = code_only(src).chars().filter(|c| !c.is_whitespace()).collect(); let mut out = Vec::new(); + let mut braces = 0usize; let mut i = 0; while i + 2 < code.len() { - if code[i] != '#' || code[i + 1] != '!' || code[i + 2] != '[' { + if code[i] == '{' { + braces += 1; + } else if code[i] == '}' { + braces = braces.saturating_sub(1); + } + if braces > 0 || code[i] != '#' || code[i + 1] != '!' || code[i + 2] != '[' { i += 1; continue; } @@ -260,6 +267,14 @@ mod tests { assert_eq!(problem("#![forbid(unsafe_code)]\n// #![doc(test(attr(forbid(unsafe_code))))]\n"), NEEDS_FORBID); } + #[test] + fn attributes_inside_a_module_do_not_count() { + assert_eq!(problem("mod tests {\n #![doc(test(attr(deny(unsafe_code))))]\n}\n"), NEEDS_DENY); + assert_eq!(problem("#![forbid(unsafe_code)]\nmod a { #![doc(test(attr(forbid(unsafe_code))))] }\n"), NEEDS_FORBID); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a { #![forbid(unsafe_code)] }\n"), None); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nmod a {\n fn f() {}\n}\n"), None); + } + #[test] fn spacing_and_other_attributes_in_the_list_are_accepted() { assert_eq!(problem("#![doc(test(attr(deny(warnings), forbid( unsafe_code ))))]\n#![forbid(unsafe_code)]\n"), None); From 4fbe7364d96bcedaa552995a486e554817f96dda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:12:26 -0800 Subject: [PATCH 49/65] Tests: read the coalesced release and press from the frame that took them review_596866_owned_up_then_new_down_in_one_frame_keeps_the_next_click_single checked the release and press edges in the step's last frame. The press's Down comes in a second pass of the same frame only when another part of the UI asks for a rerun; otherwise it comes in the next frame, whose first pass has no events. Keying the Image Trace sliders on the selection moves the status bar's rerun to an earlier step, so the Down came in a second frame and the precondition failed while every behavior assertion still held. The edges are now read with frame_event, which looks at the first pass of each frame in the step. --- crates/ui-egui/tests/image_trace_ignore_sampler.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs index f9e6bff2ed..91edfb5512 100644 --- a/crates/ui-egui/tests/image_trace_ignore_sampler.rs +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -1155,7 +1155,9 @@ fn review_596866_owned_release_then_press(coalesced: bool) { let history = (app.session.active().unwrap().history.undo.len(), app.session.active().unwrap().history.redo.len()); if coalesced { frame_at(&mut app, &ctx, start + step, vec![review_596866_button(at, false), review_596866_button(at, true)]); - assert!(frame_input(&ctx, |i| i.pointer.primary_released() && i.pointer.primary_pressed() && i.pointer.primary_down())); + // The press's Down comes in a second pass of this frame when another part of the UI asks for a rerun, and in the + // next frame otherwise. The coalesced release and press are read from the frame whose first pass took them. + assert!(frame_event(&ctx, |i| i.pointer.primary_released() && i.pointer.primary_pressed() && i.pointer.primary_down())); } else { review_gesture_release(&mut app, &ctx, at, start + step); assert_eq!(app.session.active().unwrap().selection.objects, Vec::::new(), "CONTROL: the owned Up remains consumed"); From 8c15c135f9b5b8e0d7b441ba54a74a04adc7791d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:13:03 -0800 Subject: [PATCH 50/65] Panels: a popover opened from an auto-collapsing flyout leaves it open With Auto-Collapse Iconic Panels on, the Gradient panel's stop chip in an icon column's flyout opened the stop popover, and the flyout closed in the same frames. The popover is a layer of the window's dialog host, outside the flyout's layers, so the focus moving into it and presses in it counted as leaving the flyout. The dock now notes the dialogs that open while a flyout is open. While one of them is still open, the flyout is shown without auto-collapse; once they close, a click away from the flyout closes it again. --- crates/ui-egui/src/panel_docking.rs | 30 +++++++++++++++++- crates/ui-egui/src/panel_docking/tests.rs | 37 +++++++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 1a47d5a7d2..91403aa95f 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -21,6 +21,7 @@ use std::sync::Arc; use craft::behavior::{Axis, DockSide, IconId}; use craft::ui::buttons::IconButton; use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked}; +use craft::ui::dialog::DialogId; use craft::ui::docking::{ ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions, @@ -73,6 +74,9 @@ pub(crate) struct Runtime { /// A panel just floated out of a tool rail, whose window takes over the held press on the next /// pass, with the pointer at this point inside it ([`continue_move`]). hand_over: Option<(String, egui::Vec2)>, + /// The dialogs a panel in the open flyout opened, by id and opening serial: while one is open, Auto-Collapse Iconic + /// Panels leaves the flyout open ([`show`]). + flyout_dialogs: Vec<(DialogId, u64)>, } /// `ui.docking`: the layout in use, the hidden panels, the open flyout, the focused panel, the @@ -1335,6 +1339,16 @@ fn raise(app: &VectorcraftApp, ctx: &egui::Context, panel: &str) { } } +/// The open dialogs of the main window, by id and opening serial: a dialog closed and opened again has a new serial. +fn open_dialogs(app: &VectorcraftApp) -> Vec<(DialogId, u64)> { + app.dialogs().map_or_else(Vec::new, |dialogs| { + dialogs.with(|host| { + let host = &*host; + host.stack().ids().filter_map(|id| Some((id, host.open_serial(id)?))).collect() + }) + }) +} + /// The floating window holding `panel` takes over the held primary press on the next pass, with the /// pointer at `grab` inside it: a panel floated out of a tool rail mid-drag follows the pointer and /// docks where the release lands. @@ -1360,7 +1374,15 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo let presenting = app.ui.screen_mode >= 3; // Shift+Tab, from its key, a menu or automation, closes a panel popped out of the icon column. let mut flyout = flyout_before.clone().filter(|_| !keeps_tools); - let auto_collapse = app.session.prefs.auto_collapse_icon_panels; + let dialogs_before = open_dialogs(app); + if flyout_before.is_some() { + app.dock_rt.flyout_dialogs.retain(|dialog| dialogs_before.contains(dialog)); + } else { + app.dock_rt.flyout_dialogs.clear(); + } + // A dialog a panel of the flyout opened (the Gradient panel's stop popover) is a layer of the window's dialog host, + // outside the flyout's: while one is open, a press in it or the focus moving into it leaves the flyout open. + let auto_collapse = app.session.prefs.auto_collapse_icon_panels && app.dock_rt.flyout_dialogs.is_empty(); // The specs and rails leave the app for the pass, which lends the app to the panel bodies. let specs = std::mem::take(&mut app.dock_rt.specs); let rails = std::mem::take(&mut app.dock_rt.rails); @@ -1406,6 +1428,12 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo if app.ui.open_panel == flyout_before { app.ui.open_panel = flyout; } + if app.ui.open_panel.is_some() { + let opened: Vec<_> = open_dialogs(app).into_iter().filter(|dialog| !dialogs_before.contains(dialog)).collect(); + app.dock_rt.flyout_dialogs.extend(opened); + } else { + app.dock_rt.flyout_dialogs.clear(); + } if output.error.is_some() { Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[])); app.status(tl!("Invalid panel layout; restored the default dock").to_string()); diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 45babc785c..4db88f1fc5 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1349,3 +1349,40 @@ fn a_tab_menus_stock_items_start_at_the_panel_items_check_column() { let within = find(&shown, "Float").1; assert!(within < stock.1 - 0.5, "\"Float\" starts {within} into its row with no rows before it, as far as {} after them", stock.1); } + +/// With Auto-Collapse Iconic Panels on, the popover the Gradient panel's stop chip opens from the panel's flyout leaves +/// the flyout open while it shows; once it closes, a click away from the flyout still closes it. +#[test] +fn a_popover_opened_from_an_auto_collapsing_flyout_leaves_the_flyout_open() { + let mut h = Harness::new(); + h.app.session.prefs.auto_collapse_icon_panels = true; + h.app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 120, "height": 100})).unwrap(); + let stops = json!([{"offset": 0, "color": "#2468ac"}, {"offset": 1, "color": "#e09020"}]); + h.app.run("paint.setFill", json!({"keepModel": true, "gradient": {"kind": "linear", "stops": stops}})).unwrap(); + h.app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap(); + h.app.select_tool("directSelection"); + h.app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + h.app.run("window.panel", json!({"panel": "gradient"})).unwrap(); + h.frames(3); + let flyout = h.app.ui.open_panel.clone(); + assert!(flyout.is_some(), "the Gradient panel opens in its icon column's flyout"); + let popover = craft::ui::dialog::dialog_id(crate::dialogs::gradient_stop::KIND); + let popover_open = |h: &Harness| h.app.dialogs().unwrap().with(|host| host.stack().contains(popover)); + let chip = h + .nodes + .iter() + .filter(|(_, node)| node.label() == Some("Edit the stop")) + .find_map(|(_, node)| node.bounds()) + .map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) + .expect("the flyout's stop chip"); + h.click(chip.center()); + h.frames(3); + assert!(popover_open(&h), "the chip opens the stop popover"); + assert_eq!(h.app.ui.open_panel, flyout, "the flyout stays open while its panel's popover shows"); + h.press(egui::Key::Escape, Default::default()); + h.frames(2); + assert!(!popover_open(&h), "Escape closes the popover"); + assert_eq!(h.app.ui.open_panel, flyout, "closing the popover leaves the flyout open"); + h.click(h.canvas().center()); + assert_eq!(h.app.ui.open_panel, None, "a click away from the flyout still closes it"); +} From b44dbefe1243d0f4d337d77c24e4b3a5d0f257f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:59:09 -0800 Subject: [PATCH 51/65] Direct Selection: a Cmd/Ctrl drag of one of several picked handles mirrors With two or more direction handles picked, a press without Shift on one of them started a drag of all the picked handles (path.moveHandles), which never mirrors. A Cmd/Ctrl press that Direct Selection now keeps on a shown handle therefore translated every picked handle instead of mirroring the opposite one. press_handle now drags the pressed handle alone when the press mirrors (Cmd/Ctrl without Alt, and not the press that lent the tool from another tool), so the drag mirrors its opposite handle and the other picked handles stay where they are. A drag without Cmd/Ctrl still moves every picked handle. --- crates/engine/tests/it/several_handles.rs | 17 +++++++++++++++++ crates/tools/src/direct.rs | 9 +++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs index 7b5469c278..0d314f68ea 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -119,6 +119,23 @@ fn picked_handles_stay_picked_after_they_are_dragged() { near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0)); } +/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone +/// and mirrors its opposite handle; the other picked handle stays where it is. +#[test] +fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd = Mods { cmd: true, ..Mods::default() }; + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd); + assert_eq!(s.tool_id(), "directSelection"); + let a = anchor(&s, id, 1); + near(a.h_out, Point::new(180.0, 160.0)); + near(a.h_in, Point::new(20.0, 40.0)); + assert_eq!(a.kind, AnchorKind::Smooth); + near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0)); +} + /// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag /// then moves only the handle pressed. #[test] diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 06723b8fcf..9fa0fd754f 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1923,9 +1923,10 @@ impl DirectSelectionTool { self.state = State::Handle { id, si, ai, out, drag: Some(drag) }; vec![Action::Preview("path.setHandle".into(), params)] } - /// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift on one of two or - /// more picked handles (`picks`, as they were before the press), a drag moves them all; any - /// other press drags that handle alone, as before handles could be picked. + /// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift or a mirroring + /// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were + /// before the press), a drag moves them all; any other press drags that handle alone, as before + /// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. fn press_handle( &mut self, cx: &ToolContext, @@ -1958,7 +1959,7 @@ impl DirectSelectionTool { }; let handle = (id, (si, ai, out)); let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1)); - let several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::() > 1; + let several = on && !ev.mods.shift && !self.mirrors(ev) && picks.values().map(BTreeSet::len).sum::() > 1; let begin = if several { let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect(); self.state = State::Handles { handle, from, start: p, items, began: false }; From 56831e1dac4e47fdd5348e825a110b70e758747a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 19:59:26 -0800 Subject: [PATCH 52/65] Home: keep the German heading test passing without a catalog row The test no longer requires the German catalog to translate Recent Files. When the row is there, Home must show its text; when it is not, Home must show the framework's translation of the start screen's Recent heading. --- crates/ui-egui/src/tests/home.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 66aba4b3b8..50991b8d8c 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -178,9 +178,11 @@ fn home_heads_the_recent_files_recent_files() { assert!(home.shows("Recent Files"), "the recent files are headed Recent Files"); assert!(!home.shows("Recent"), "not Recent alone"); let home = shown("de"); - let german = crate::i18n::tr(crate::i18n::Lang::from_code("de").expect("German is registered"), "Recent Files"); - assert_ne!(german, "Recent Files", "the German catalog translates Recent Files"); - assert!(home.shows(german), "German shows the catalog's Recent Files, {german}"); + let de = crate::i18n::Lang::from_code("de").expect("German is registered"); + let german = crate::i18n::tr(de, "Recent Files"); + // Without a German row for Recent Files, the framework's heading stays. + let heading = if german == "Recent Files" { crate::i18n::tr_id(de, "startScreen.recent", "Recent") } else { german }; + assert!(home.shows(heading), "German shows {heading}"); } /// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A From fb0bce30e64beab00184782924015b8fe2638555 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 20:06:43 -0800 Subject: [PATCH 53/65] Doc tests: read the unsafe-code level that the doc-test attributes leave in force The check accepted a library root when deny(unsafe_code) or forbid(unsafe_code) appeared anywhere inside #![doc(test(...))]. Two roots passed although their doc tests still allow unsafe code: - #![doc(test(attr(cfg_attr(any(), forbid(unsafe_code)))))]: the lint sits inside a cfg_attr whose condition is false, so rustdoc adds no lint to the doc tests. - #![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]: rustdoc adds both attributes in order, and the later allow overrides the deny. The check now reads only the lint attributes that are direct members of attr(...), in order, and keeps the last level for unsafe_code. A later allow, warn or expect lowers deny, and nothing lowers forbid. Tests cover each case. --- xtask/src/doc_tests.rs | 147 ++++++++++++++++++++++++++--------------- 1 file changed, 94 insertions(+), 53 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 2cc73d2ce9..6fb57db610 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -50,19 +50,87 @@ fn check_root(name: &str, root: &Path, path: &Path) -> Result, St /// strictly as the library does. fn problem(src: &str) -> Option<&'static str> { let attrs = inner_attributes(src); - let forbids = attrs.iter().any(|a| a.strip_prefix("forbid(").and_then(|rest| rest.strip_suffix(')')).is_some_and(names_unsafe_code)); - let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("doc(test(") && calls(a, level).into_iter().any(names_unsafe_code)); - if doc_test("forbid") { - None - } else if forbids { - Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]") - } else if doc_test("deny") { - None - } else { - Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]") + let forbids = attrs.iter().any(|a| args(a, "forbid").is_some_and(names_unsafe_code)); + match doc_test_level(&attrs) { + Some(Level::Forbid) => None, + _ if forbids => Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]"), + Some(Level::Deny) => None, + _ => Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]"), } } +/// A lint level that rustdoc can add to every doc test. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Level { + Allow, + Deny, + Forbid, +} + +/// The lint attributes that set a level, and the level each one sets for this check. +const LEVELS: [(&str, Level); 5] = + [("forbid", Level::Forbid), ("deny", Level::Deny), ("allow", Level::Allow), ("warn", Level::Allow), ("expect", Level::Allow)]; + +/// The `unsafe_code` level that the `#![doc(test(attr(...)))]` attributes leave in force, read in +/// order. Only lint attributes that are direct members of `attr(...)` count, so one inside +/// `cfg_attr(...)` is ignored. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and +/// nothing lowers a `forbid`. +fn doc_test_level(attrs: &[String]) -> Option { + let mut level = None; + for doc in attrs.iter().filter_map(|a| args(a, "doc")) { + for test in items(doc).into_iter().filter_map(|i| args(i, "test")) { + for attr in items(test).into_iter().filter_map(|i| args(i, "attr")) { + for lint in items(attr) { + let next = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l)); + if let Some(next) = next + && level != Some(Level::Forbid) + { + level = Some(next); + } + } + } + } + } + level +} + +/// The argument list of `item` when it is exactly `name(...)`. +fn args<'a>(item: &'a str, name: &str) -> Option<&'a str> { + let rest = item.strip_prefix(name)?.strip_prefix('(')?.strip_suffix(')')?; + let mut depth = 0usize; + for ch in rest.chars() { + match ch { + '(' => depth += 1, + ')' if depth == 0 => return None, + ')' => depth -= 1, + _ => {} + } + } + (depth == 0).then_some(rest) +} + +/// The comma-separated items of a list such as `deny(warnings),forbid(unsafe_code)`, split only +/// at the top level. +fn items(list: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut depth = 0usize; + let mut item_start = 0; + for (k, ch) in list.char_indices().chain(std::iter::once((list.len(), ','))) { + match ch { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + if k > item_start { + out.push(&list[item_start..k]); + } + item_start = k + 1; + } + _ => {} + } + } + out +} + /// The body of every crate-level `#![...]` attribute in `src`, without whitespace, read across /// line breaks. Attributes inside braces (a module, a function) are skipped, comments are /// skipped, and string and character literals are read as empty. @@ -188,51 +256,9 @@ fn raw_string_hashes(c: &[char], i: usize) -> Option<(usize, usize)> { (c.get(j + hashes) == Some(&'"')).then_some((j + hashes, hashes)) } -/// The argument lists of every `name(...)` in `attr` that starts a list item. -fn calls<'a>(attr: &'a str, name: &str) -> Vec<&'a str> { - let mut out = Vec::new(); - let pat = format!("{name}("); - for (at, _) in attr.match_indices(&pat) { - if at > 0 && !matches!(attr.as_bytes()[at - 1], b'(' | b',') { - continue; - } - let start = at + pat.len(); - let mut depth = 1usize; - for (k, ch) in attr[start..].char_indices() { - match ch { - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - out.push(&attr[start..start + k]); - break; - } - } - _ => {} - } - } - } - out -} - /// Whether a lint list such as `unsafe_code,unused_must_use` names `unsafe_code`. fn names_unsafe_code(list: &str) -> bool { - let mut depth = 0usize; - let mut item_start = 0; - for (k, ch) in list.char_indices().chain(std::iter::once((list.len(), ','))) { - match ch { - '(' => depth += 1, - ')' => depth = depth.saturating_sub(1), - ',' if depth == 0 => { - if &list[item_start..k] == "unsafe_code" { - return true; - } - item_start = k + 1; - } - _ => {} - } - } - false + items(list).contains(&"unsafe_code") } #[cfg(test)] @@ -303,4 +329,19 @@ mod tests { assert_eq!(problem("#![forbid(unsafe_code_extra)]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); assert_eq!(problem("#![doc(test(attr(deny(not_unsafe_code))))]\n"), NEEDS_DENY); } + + #[test] + fn a_lint_inside_cfg_attr_does_not_count() { + assert_eq!(problem("#![doc(test(attr(cfg_attr(any(), deny(unsafe_code)))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(cfg_attr(any(), forbid(unsafe_code)))))]\n"), NEEDS_FORBID); + assert_eq!(problem("#![doc(test(no_crate_inject, attr(deny(unsafe_code))))]\n"), None); + } + + #[test] + fn a_later_allow_lowers_deny_but_not_forbid() { + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\n#![doc(test(attr(warn(unsafe_code))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(allow(unsafe_code), deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code), allow(unsafe_code))))]\n"), None); + } } From 1bccc76d77d76876058b3ce2d283a155c51e5bda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 20:23:55 -0800 Subject: [PATCH 54/65] Tests: dock panel tests wait for the font scan before counting idle frames dock::tests::idle_frames_replay_the_color_panel failed now and then with "idle frames replay the Color panel" (left: 1, right: 0). The app starts the scan of the installed fonts on a background thread, and frames do not wait for it. When the scan ends, the fonts' generation changes, and a panel body's inputs hold that generation through layout_inputs. On a loaded machine the scan can end after the helper's two settle frames, so the first idle frame runs the body once. The panel() helper now calls FontDb::global().family_list() after making the app, which waits for that scan (or runs it), as the font menu, properties and native menu tests already do. Every test in the module goes through panel(), so all of them get the fix. --- crates/ui-egui/src/dock.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ea6dcb4c69..f07c0e9a4f 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -202,6 +202,9 @@ mod tests { fn panel(id: &'static str) -> Panel { SHOWN.with(|s| *s.borrow_mut() = id); let mut app = VectorcraftApp::new(Session::new(), Default::default()); + // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends, and the + // bodies' inputs hold that generation: wait for it, or an idle frame that it ends in runs the body. + vectorcraft_text::FontDb::global().family_list(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); let mut panel = Panel::new(app, draw); From 4e2581f63d8201932391bf39edb0d99fba7e5026 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 21:17:30 -0800 Subject: [PATCH 55/65] Doc tests: treat cfg_attr lints by what they could do, and skip raw C strings The check did not read lint attributes inside cfg_attr at all, and it does not evaluate cfg conditions. Two roots passed although the condition all() is always true: - #![cfg_attr(all(), forbid(unsafe_code))] with doc-test deny: the library forbids unsafe code, so its doc tests need forbid. - #![doc(test(attr(deny(unsafe_code), cfg_attr(all(), allow(unsafe_code)))))]: the allow lowers the deny. A cfg_attr now counts only in the direction that is never too lenient: a forbid inside one asks the doc tests for forbid, and an allow, warn or expect inside one lowers the doc tests' level. A deny or forbid inside cfg_attr in the doc-test list still does not count. The comment and literal scanner also skips raw C strings (cr"..."), so text such as #![forbid(unsafe_code)] inside one is not read as an attribute. Tests cover each case. --- xtask/src/doc_tests.rs | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs index 6fb57db610..ece5ccfe45 100644 --- a/xtask/src/doc_tests.rs +++ b/xtask/src/doc_tests.rs @@ -50,7 +50,7 @@ fn check_root(name: &str, root: &Path, path: &Path) -> Result, St /// strictly as the library does. fn problem(src: &str) -> Option<&'static str> { let attrs = inner_attributes(src); - let forbids = attrs.iter().any(|a| args(a, "forbid").is_some_and(names_unsafe_code)); + let forbids = attrs.iter().any(|a| sets_level(a, &["forbid"])); match doc_test_level(&attrs) { Some(Level::Forbid) => None, _ if forbids => Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]"), @@ -72,16 +72,17 @@ const LEVELS: [(&str, Level); 5] = [("forbid", Level::Forbid), ("deny", Level::Deny), ("allow", Level::Allow), ("warn", Level::Allow), ("expect", Level::Allow)]; /// The `unsafe_code` level that the `#![doc(test(attr(...)))]` attributes leave in force, read in -/// order. Only lint attributes that are direct members of `attr(...)` count, so one inside -/// `cfg_attr(...)` is ignored. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and -/// nothing lowers a `forbid`. +/// order. A later `allow`, `warn` or `expect` lowers an earlier `deny`, and nothing lowers a +/// `forbid`. The check does not evaluate `cfg_attr` conditions: a `deny` or `forbid` inside +/// `cfg_attr(...)` does not count, and an `allow`, `warn` or `expect` inside one lowers the level. fn doc_test_level(attrs: &[String]) -> Option { let mut level = None; for doc in attrs.iter().filter_map(|a| args(a, "doc")) { for test in items(doc).into_iter().filter_map(|i| args(i, "test")) { for attr in items(test).into_iter().filter_map(|i| args(i, "attr")) { for lint in items(attr) { - let next = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l)); + let direct = LEVELS.into_iter().find_map(|(name, l)| args(lint, name).is_some_and(names_unsafe_code).then_some(l)); + let next = direct.or_else(|| sets_level(lint, &["allow", "warn", "expect"]).then_some(Level::Allow)); if let Some(next) = next && level != Some(Level::Forbid) { @@ -94,6 +95,15 @@ fn doc_test_level(attrs: &[String]) -> Option { level } +/// Whether `attr` is one of the lint attributes `names` applied to `unsafe_code`, directly or +/// inside `cfg_attr(...)`, whatever its condition. +fn sets_level(attr: &str, names: &[&str]) -> bool { + if names.iter().any(|name| args(attr, name).is_some_and(names_unsafe_code)) { + return true; + } + args(attr, "cfg_attr").is_some_and(|inner| items(inner).into_iter().skip(1).any(|a| sets_level(a, names))) +} + /// The argument list of `item` when it is exactly `name(...)`. fn args<'a>(item: &'a str, name: &str) -> Option<&'a str> { let rest = item.strip_prefix(name)?.strip_prefix('(')?.strip_suffix(')')?; @@ -170,7 +180,7 @@ fn inner_attributes(src: &str) -> Vec { } /// `src` with line and (nested) block comments replaced by a space, and the contents of string, -/// raw string and character literals removed. +/// raw string (including raw byte and raw C string) and character literals removed. fn code_only(src: &str) -> String { let c: Vec = src.chars().collect(); let mut out = String::with_capacity(src.len()); @@ -203,7 +213,7 @@ fn code_only(src: &str) -> String { } out.push(' '); } - 'r' | 'b' if !ident_before && raw_string_hashes(&c, i).is_some() => { + 'r' | 'b' | 'c' if !ident_before && raw_string_hashes(&c, i).is_some() => { let (open, hashes) = raw_string_hashes(&c, i).unwrap_or((i, 0)); let mut j = open + 1; while j < c.len() && !(c[j] == '"' && (1..=hashes).all(|k| c.get(j + k) == Some(&'#'))) { @@ -241,11 +251,11 @@ fn code_only(src: &str) -> String { out } -/// For a raw string literal starting at `i` (`r"`, `r#"`, `br"`...), the index of its opening -/// quote and its number of `#`s. +/// For a raw string literal starting at `i` (`r"`, `r#"`, `br"`, `cr"`...), the index of its +/// opening quote and its number of `#`s. fn raw_string_hashes(c: &[char], i: usize) -> Option<(usize, usize)> { let mut j = i; - if c.get(j) == Some(&'b') { + if matches!(c.get(j), Some('b' | 'c')) { j += 1; } if c.get(j) != Some(&'r') { @@ -312,6 +322,7 @@ mod tests { assert_eq!(problem("/* /* nested */ #![doc(test(attr(deny(unsafe_code))))] */\n"), NEEDS_DENY); assert_eq!(problem("const S: &str = \"#![doc(test(attr(deny(unsafe_code))))]\";\n"), NEEDS_DENY); assert_eq!(problem("const S: &str = r#\"#![doc(test(attr(deny(unsafe_code))))]\"#;\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code))))]\nconst S: &CStr = cr#\"\" #![forbid(unsafe_code)] \"#;\n"), None); assert_eq!(problem("const Q: char = '\\'';\nconst S: &str = \"/*\";\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); } @@ -337,6 +348,15 @@ mod tests { assert_eq!(problem("#![doc(test(no_crate_inject, attr(deny(unsafe_code))))]\n"), None); } + #[test] + fn cfg_attr_can_only_lower_the_doc_tests_or_raise_the_library() { + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(all(), allow(unsafe_code)))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), cfg_attr(test, cfg_attr(all(), warn(unsafe_code))))))]\n"), NEEDS_DENY); + assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), NEEDS_FORBID); + assert_eq!(problem("#![cfg_attr(all(), forbid(unsafe_code))]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert_eq!(problem("#![cfg_attr(forbid, deny(unsafe_code))]\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + } + #[test] fn a_later_allow_lowers_deny_but_not_forbid() { assert_eq!(problem("#![doc(test(attr(deny(unsafe_code), allow(unsafe_code))))]\n"), NEEDS_DENY); From 74b2ffdb82321d08c6dd566cdc13f6c3c64d1288 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 21:26:04 -0800 Subject: [PATCH 56/65] Direct Selection: picked handles stay picked after a Cmd/Ctrl drag A Cmd/Ctrl press on one of several picked direction handles drags that handle alone so its opposite handle mirrors. The press cleared the picked handles, and neither the release nor Escape restored them, so after the drag only the pressed handle could be picked again. The press now records that it is such a mirroring press. Its release after a drag, and Escape during the drag, restore the handles that were picked when the press began. A drag without Cmd/Ctrl still moves every picked handle, and a click still picks the pressed handle alone. --- crates/engine/tests/it/several_handles.rs | 32 ++++++++++++++++++++++ crates/tools/src/direct.rs | 33 ++++++++++++++++------- 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs index 0d314f68ea..f5ad79d614 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -136,6 +136,38 @@ fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() { near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0)); } +/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without +/// Cmd/Ctrl then moves both. +#[test] +fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd = Mods { cmd: true, ..Mods::default() }; + drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); +} + +/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both +/// picked. +#[test] +fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd = Mods { cmd: true, ..Mods::default() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd); + pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd); + near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0)); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); +} + /// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag /// then moves only the handle pressed. #[test] diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 9fa0fd754f..b27564fd40 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -110,6 +110,8 @@ struct HandlePress { moved: bool, /// The picked handles when the press began. picked: PickedHandles, + /// A mirroring Cmd/Ctrl press on one of several picked handles: they stay picked after its drag. + keeps_picks: bool, } #[derive(Clone, Debug)] @@ -1114,13 +1116,16 @@ impl Tool for DirectSelectionTool { self.mesh.cancel(); // The frame anchors or handles a cancelled drag held stay selected. let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty(); - let handles = matches!(self.state, State::Handles { .. }); + let kept = self.handle_press.take().filter(|press| press.keeps_picks && matches!(self.state, State::Handle { .. })); + let handles = matches!(self.state, State::Handles { .. }) || kept.is_some(); + if let Some(press) = kept { + self.handles = press.picked; + } self.state = State::Idle; self.guides.clear(); (self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None); self.last_location = None; (self.click, self.click_segment, self.click_group, self.frame_click) = (None, None, None, None); - self.handle_press = None; match (frame, handles) { (true, _) => vec![Action::Cancel, Action::Notify(FRAME_PICKED.into())], (_, true) => vec![Action::Cancel, Action::Notify(HANDLES_PICKED.into())], @@ -1926,7 +1931,8 @@ impl DirectSelectionTool { /// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift or a mirroring /// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were /// before the press), a drag moves them all; any other press drags that handle alone, as before - /// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. + /// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. The picked handles + /// stay picked after such a Cmd/Ctrl drag of one of them. fn press_handle( &mut self, cx: &ToolContext, @@ -1959,8 +1965,9 @@ impl DirectSelectionTool { }; let handle = (id, (si, ai, out)); let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1)); - let several = on && !ev.mods.shift && !self.mirrors(ev) && picks.values().map(BTreeSet::len).sum::() > 1; - let begin = if several { + let among_several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::() > 1; + let keeps_picks = among_several && self.mirrors(ev); + let begin = if among_several && !keeps_picks { let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect(); self.state = State::Handles { handle, from, start: p, items, began: false }; self.handles = picks.clone(); @@ -1970,7 +1977,7 @@ impl DirectSelectionTool { self.state = State::Handle { id, si, ai, out, drag }; vec![Action::Begin("Reshape".into())] }; - self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks }); + self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks, keeps_picks }); begin } /// The release of a press on one of several picked handles: a drag commits, and the picked @@ -1985,10 +1992,18 @@ impl DirectSelectionTool { self.handles = BTreeMap::from([(handle.0, BTreeSet::from([handle.1]))]); vec![Action::Notify(HANDLES_PICKED.into())] } - /// After the release of a press on a handle that did not drag: a click picks the handle alone, - /// and a Shift-click adds it to the picked handles or takes it away. + /// After the release of a press on a handle: a click picks the handle alone, and a Shift-click + /// adds it to the picked handles or takes it away. A mirroring drag of one of several picked + /// handles leaves them all picked. fn pick_clicked_handle(&mut self) -> Option { - let press = self.handle_press.take().filter(|press| !press.moved)?; + let press = self.handle_press.take()?; + if press.moved { + if !press.keeps_picks { + return None; + } + self.handles = press.picked; + return Some(Action::Notify(HANDLES_PICKED.into())); + } let (id, h) = press.handle; let mut picked = if press.shift { press.picked } else { BTreeMap::new() }; let set = picked.entry(id).or_default(); From 472d7f8e69c03a778d047ab7426c93992d990bdf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 22:21:02 -0800 Subject: [PATCH 57/65] Direct Selection: picked handles stay picked after a Cmd/Ctrl+Shift drag With two direction handles picked, a Cmd/Ctrl+Shift press on one of them drags that handle alone with its opposite handle mirrored and its angle constrained. Shift kept the press from counting as a press on one of several picked handles, so the press did not record the picks, and its release after a drag, or Escape during it, left only the pressed handle. The press now records the picks for any mirroring press on one of several picked handles, with or without Shift. Shift still keeps a drag from moving every picked handle, and a Shift-click still adds or removes the pressed handle. --- crates/engine/tests/it/several_handles.rs | 23 +++++++++++++++++++++++ crates/tools/src/direct.rs | 8 +++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/several_handles.rs b/crates/engine/tests/it/several_handles.rs index f5ad79d614..45b2e39f19 100644 --- a/crates/engine/tests/it/several_handles.rs +++ b/crates/engine/tests/it/several_handles.rs @@ -150,6 +150,29 @@ fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() { near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); } +/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during +/// one. +#[test] +fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() { + for escape in [false, true] { + let (mut s, id) = session(); + click(&mut s, Point::new(180.0, 100.0), Mods::default()); + click(&mut s, Point::new(300.0, 140.0), shift()); + let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() }; + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift); + pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift); + if escape { + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + } + pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift); + let x = if escape { 180.0 } else { 220.0 }; + near(anchor(&s, id, 1).h_out, Point::new(x, 100.0)); + drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default()); + near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0)); + near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0)); + } +} + /// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both /// picked. #[test] diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index b27564fd40..cf3551fc19 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1932,7 +1932,7 @@ impl DirectSelectionTool { /// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were /// before the press), a drag moves them all; any other press drags that handle alone, as before /// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. The picked handles - /// stay picked after such a Cmd/Ctrl drag of one of them. + /// stay picked after such a Cmd/Ctrl or Cmd/Ctrl+Shift drag of one of them. fn press_handle( &mut self, cx: &ToolContext, @@ -1965,8 +1965,10 @@ impl DirectSelectionTool { }; let handle = (id, (si, ai, out)); let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1)); - let among_several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::() > 1; - let keeps_picks = among_several && self.mirrors(ev); + let one_of_several = on && picks.values().map(BTreeSet::len).sum::() > 1; + let among_several = one_of_several && !ev.mods.shift; + // A mirroring drag keeps the picks with Shift held too. + let keeps_picks = one_of_several && self.mirrors(ev); let begin = if among_several && !keeps_picks { let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect(); self.state = State::Handles { handle, from, start: p, items, began: false }; From b2f59ace0714e2848159cb4745029492d6b1c921 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:36:50 -0800 Subject: [PATCH 58/65] Docs: add a script for editable numbered grids (#10417) * Docs: add a script for editable numbered grids * Docs: bound the numbered-grid example and validate label numbers --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- docs/mcp.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/docs/mcp.md b/docs/mcp.md index 0937b3ba51..e99e34fe86 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4245,6 +4245,49 @@ change anything outside the documents: `script.*` except `script.check`, `plugin an error. With Data Recovery off for complex documents, a run in the web build does not start while a complex document has unsaved changes. +#### Create a numbered grid + +Open the drawing, save the code below as `Number Grid.jsx`, then run it with **File › Scripts › Other Script…**. +Change the first number, count, columns and spacing before running it. Positions and spacing are in document +points. `left` and `top` set the baseline origin of the first label, and numbers advance across each row. +Every label stays editable with the Type tool. One Undo removes the entire grid. + +```javascript +var firstNumber = 1; +var count = 31; +var columns = 7; +var left = 36; +var top = 54; +var columnSpacing = 42; +var rowSpacing = 32; +var size = 16; + +if (count < 1 || count > 1000 || count !== Math.floor(count)) { + throw new Error("Count must be a whole number from 1 to 1000."); +} +if (!isFinite(columns) || columns < 1 || columns !== Math.floor(columns)) { + throw new Error("Columns must be a positive whole number."); +} +var maxInteger = 9007199254740991; +var lastNumber = firstNumber + (count - 1); +if (firstNumber !== Math.floor(firstNumber) || + Math.abs(firstNumber) > maxInteger || Math.abs(lastNumber) > maxInteger) { + throw new Error("The first and last label number must be safe integers."); +} + +for (var i = 0; i < count; i++) { + vc.run("text.create", { + x: left + (i % columns) * columnSpacing, + y: top + Math.floor(i / columns) * rowSpacing, + text: String(firstNumber + i), + size: size + }); +} +``` + +This example creates up to 1,000 labels in one run. Make more room between larger labels by increasing +`columnSpacing`. + ### Script engines A named engine (`#targetengine`) keeps its globals and functions between the runs that name it, until it is dropped From 4070779f8838c87ba7b8abff95356f9b2ccaf201 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:52:39 -0800 Subject: [PATCH 59/65] View: keep Cmd+0 on Fit Artboard in Window (#10396) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/menus/model.rs | 5 ++++- crates/ui-egui/src/shortcuts/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 3e4cecdc1d..84125b1a43 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -477,7 +477,10 @@ fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft: Ok(catalog) => { // While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it, // and the Type tool's commands run while it types. - let catalog = catalog.typing_rule(TypingRule::AllWait); + // The document canvas also defaults to Cmd+0, but its Fit on Screen stops at actual size. + // Leave that chord to VectorCraft's Fit Artboard in Window. + let fit_on_screen = CommandRef::from(craft::ui::canvas::ViewCommands::FitOnScreen); + let catalog = catalog.typing_rule(TypingRule::AllWait).replace_defaults(fit_on_screen.id, Vec::new()); let catalog = linked_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys)); let catalog = UNROUTED.iter().fold(catalog, |catalog, id| catalog.replace_defaults(id.as_str(), Vec::new())); Some(type_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys))) diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 6673ef5da6..5ed8517c01 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -80,6 +80,33 @@ fn idle(app: &mut VectorcraftApp, ctx: &egui::Context, n: usize) { } } +/// A focused document canvas must use the app's artboard fit, whose zoom may exceed 100%. +#[test] +fn command_zero_fits_the_active_artboard_when_the_canvas_has_focus() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 120, "height": 80, "artboards": 2})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let ctx = ready(&mut app); + app.view_mut().unwrap().artboard = 1; + + app.run("view.fitArtboard", json!({})).unwrap(); + idle(&mut app, &ctx, 12); + let fitted = app.view().unwrap(); + let (zoom, center) = (fitted.zoom, fitted.center); + assert!(zoom > 1.0, "this artboard has room to grow past actual size: {zoom}"); + + app.run("view.setZoom", json!({"zoom": 50})).unwrap(); + idle(&mut app, &ctx, 12); + focus_canvas(&mut app, &ctx); + assert!(app.view().unwrap().zoom < 1.0); + key_frame(&mut app, &ctx, tap(Key::Num0, cmd())); + idle(&mut app, &ctx, 12); + + let fitted = app.view().unwrap(); + assert!((fitted.zoom - zoom).abs() < 1e-6, "shortcut zoom {} should match the menu fit {zoom}", fitted.zoom); + assert_eq!(fitted.center, center, "fit the active artboard, not the whole document"); +} + /// An app with a 200 × 200 document whose window has drawn its first frame, which builds the keymap the shortcut /// commands edit. fn new_app() -> VectorcraftApp { From 8ce080b5a4093c37db762173c0fb5c1c8c58a376 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:00:19 -0800 Subject: [PATCH 60/65] Cursors: keep the pen nib details visible (#10393) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- assets/cursors/cursor-pen-convert.svg | 6 +++- assets/cursors/cursor-pen-curvature.svg | 6 +++- assets/cursors/cursor-pen-join.svg | 7 ++++- assets/cursors/cursor-pen-new.svg | 9 +++++- crates/ui-egui/src/cursors/tests.rs | 37 +++++++++++++++++++++++++ 5 files changed, 61 insertions(+), 4 deletions(-) diff --git a/assets/cursors/cursor-pen-convert.svg b/assets/cursors/cursor-pen-convert.svg index fa78f562ef..79e29af75d 100644 --- a/assets/cursors/cursor-pen-convert.svg +++ b/assets/cursors/cursor-pen-convert.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-curvature.svg b/assets/cursors/cursor-pen-curvature.svg index 94ba1708b5..b8d4bd3650 100644 --- a/assets/cursors/cursor-pen-curvature.svg +++ b/assets/cursors/cursor-pen-curvature.svg @@ -1 +1,5 @@ - + + + + + diff --git a/assets/cursors/cursor-pen-join.svg b/assets/cursors/cursor-pen-join.svg index 3dd7ce7f6e..05a020bb12 100644 --- a/assets/cursors/cursor-pen-join.svg +++ b/assets/cursors/cursor-pen-join.svg @@ -1 +1,6 @@ - + + + + + + diff --git a/assets/cursors/cursor-pen-new.svg b/assets/cursors/cursor-pen-new.svg index 6690b1ffd6..a27dc0ddae 100644 --- a/assets/cursors/cursor-pen-new.svg +++ b/assets/cursors/cursor-pen-new.svg @@ -1 +1,8 @@ - + + + + + + + + diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index f4c1d52986..a0554f26bb 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -45,3 +45,40 @@ fn every_cursor_icon_the_app_names_is_in_its_set() { } } } + +/// Painted cursors use the SVG's alpha as ink. Drawing the vent in white makes it solid ink. +#[test] +fn the_painted_pen_nibs_keep_their_breather_holes() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + + register_app_icons(&crate::icons::APP_ICONS); + register_app_icons(&CURSOR_ICONS); + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + let tokens = env.tokens.tokens(); + let ink = rgba_color(tokens.color.overlay.cursor); + let is_ink = |px: &[u8]| px[3] >= 240 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + let scale = 4.0; + let from_art_units = tokens.size.icon.md * scale / 24.0; + for c in [Cursor::Pen, Cursor::PenConvert, Cursor::PenJoin, Cursor::Curvature] { + let cb::Cursor::Painted(painted @ PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) else { + panic!("{c:?} must have painted tool art"); + }; + let image = painted_image(&env, &painted, scale).expect("the cursor fits in its bitmap"); + let [hx, hy] = image.hotspot.map(f32::from); + let pixel = |x: f32, y: f32| { + let x = (hx + (x - hotspot.x) * from_art_units).round() as usize; + let y = (hy + (y - hotspot.y) * from_art_units).round() as usize; + let i = (y * usize::from(image.size[0]) + x) * 4; + &image.rgba[i..i + 4] + }; + assert!(is_ink(pixel(9.5, 13.2)), "{c:?}: the nib body is ink"); + assert!(!is_ink(pixel(6.62, 12.86)), "{c:?}: the vent must break up the ink"); + } + }) + .textures_delta + .clear(); +} From 406dac5645370380927e9e15e91f62fa1ea2c34c Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:09:08 -0800 Subject: [PATCH 61/65] Color panel: apply picks to the selected Fill or Stroke well (#10413) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/panels/color.rs | 23 ++++++++--------- crates/ui-egui/src/panels/color/tests.rs | 33 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index ba0c6cf7a3..759051fa29 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -6,7 +6,7 @@ //! //! The mode follows the colour's own model: the last mode picked comes back for colours in its model //! and the defaults for new art, and the app keeps it between sessions. Alt on the spectrum, a chip -//! or a recent colour targets the inactive proxy (the framework's `PanelTarget::Background`); +//! or a recent colour targets the inactive proxy; //! Cmd/Ctrl-clicking the spectrum recolours (Complement, with Shift Invert). //! //! `ui.colorPanel` picks a mode, shows or hides the options and checks or unchecks Show Recent @@ -432,12 +432,11 @@ fn recolor(app: &mut VectorcraftApp, tgt: &Target, invert: bool, behind: bool) { } } -/// Run what the panel reported this pass on the document: the edits (the inactive proxy for a -/// `Background` target), the Tint row, None, a recolour click and the proxy's own events. The +/// Run the panel's edits, Tint row, None, recolour clicks and proxy events on the document. The /// gradient stop popover, which embeds the panel, hands its output here too. pub(crate) fn apply_output(app: &mut VectorcraftApp, out: &ColorPanelOutput) { let tgt = target_now(app); - apply_with(app, &tgt, out); + apply_with(app, &tgt, PanelTarget::Foreground, out); } /// [`target`] with the "?" state of [`mixed_now`], for callers without the panel's pass. @@ -445,9 +444,9 @@ pub(crate) fn target_now(app: &VectorcraftApp) -> Target { target_with(app, mixed_now(app)) } -fn apply_with(app: &mut VectorcraftApp, tgt: &Target, out: &ColorPanelOutput) { +fn apply_with(app: &mut VectorcraftApp, tgt: &Target, active: PanelTarget, out: &ColorPanelOutput) { for (which, event) in &out.edits { - let behind = matches!(which, PanelTarget::Background); + let behind = *which != active; apply_event(app, event, &EditPath::Preview, &mut |app, picked: &PickedColor, phase| { choose(app, tgt, picked_color(picked), phase, behind); }); @@ -462,7 +461,7 @@ fn apply_with(app: &mut VectorcraftApp, tgt: &Target, out: &ColorPanelOutput) { }); } if let Some(which) = out.none { - let cmd = super::proxy_cmd(app, matches!(which, PanelTarget::Background)); + let cmd = super::proxy_cmd(app, which != active); app.run(cmd, json!({"none": true})).ok(); } if let Some(r) = out.recolor { @@ -549,16 +548,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (fill, stroke) = super::current_paints(app); let (fill_well, fill_color) = well(tl!("Fill"), &fill, fill_mixed); let (stroke_well, stroke_color) = well(tl!("Stroke"), &stroke, stroke_mixed); - let fill_active = app.session.fill_active; - let colors = if fill_active { [fill_color, stroke_color] } else { [stroke_color, fill_color] }; - let active = if fill_active { Well::Primary } else { Well::Secondary }; + // The shared panel uses fixed slots for both the displayed colors and its edit targets. + let (active, active_target) = + if app.session.fill_active { (Well::Primary, PanelTarget::Foreground) } else { (Well::Secondary, PanelTarget::Background) }; let edited = tgt.color().map(|c| PickedColor::in_model(srgba(&c), model_values(&c))); let rows = shown(app, &tgt); let printable = gamut(app); let stored: Vec = app.session.recent_colors.to_vec(); let chips: Vec = stored.iter().map(srgba).collect(); let before = app.ui.color_panel; - let out = ColorPanel::new(Bind::bound(&mut app.ui.color_panel), colors) + let out = ColorPanel::new(Bind::bound(&mut app.ui.color_panel), [fill_color, stroke_color]) .layout(LAYOUT) .wells([fill_well, stroke_well], Bind::given(active)) .edited(edited) @@ -570,7 +569,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .working_rgb(&WorkingRgb) .show(ui); // PLAN: a click on a recent chip reports only its sRGB, so a CMYK recent colour paints as RGB; co.K18 needs the edit to name the chip. - apply_with(app, &tgt, &out); + apply_with(app, &tgt, active_target, &out); let now = app.ui.color_panel.mode; // Shift-click on the spectrum cycles the mode inside the panel; the colour follows it here. if now != before.mode && picked_mode(now).is_some() { diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index d354702ef2..d66bb205cc 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -429,3 +429,36 @@ fn the_wells_show_a_gradient_and_none_as_the_tools_proxy_does() { assert!(color.shows_value(well), "the Color panel shows a well that reads as {well:?}"); } } + +#[test] +fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() { + use crate::tests::panel_harness::Panel; + + let mut app = app(); + app.run("paint.setFill", json!({"color": "#224466"})).unwrap(); + app.run("paint.setStroke", json!({"color": "#aa5522"})).unwrap(); + app.run("paint.toggleActive", json!({"fill": true})).unwrap(); + let mut panel = Panel::new(app, show); + let (fill, stroke) = paints_hex(&panel.app()); + let fill_well = panel.rect("Fill"); + let stroke_well = panel.rect("Stroke"); + let stroke_hit = egui::pos2(stroke_well.center().x, (fill_well.bottom() + stroke_well.bottom()) / 2.0); + assert!(stroke_well.contains(stroke_hit) && !fill_well.contains(stroke_hit), "click the exposed part of Stroke"); + panel.click_at(stroke_hit); + assert!(!panel.app().session.fill_active, "the Color panel made Stroke active"); + panel.click("Black"); + assert_eq!(paints_hex(&panel.app()), (fill.clone(), "#000000".into())); + assert_ne!(stroke, "#000000"); + + panel.click_with("White", egui::Modifiers::ALT); + assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), "#000000".into())); + assert!(!panel.app().session.fill_active, "Alt edits Fill without activating it"); + + panel.click("None"); + assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), String::new())); + + panel.click("Fill"); + assert!(panel.app().session.fill_active); + panel.click("Black"); + assert_eq!(paints_hex(&panel.app()), ("#000000".into(), String::new())); +} From e83947b9af511bd3d7ab731ff3367aa53b1e22ab Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Fri, 4 Dec 2026 09:42:44 +0100 Subject: [PATCH 62/65] Skip distant curves when testing outline hits (#10627) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/geom/src/hit.rs | 93 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 89 insertions(+), 4 deletions(-) diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index fea760b548..2624f0a1a9 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; -use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape}; +use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape}; use crate::path::{FillRule, PathData}; @@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> { /// Distance from `p` to the nearest point on the path outline. pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 { - path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt() + path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt() } /// Is `p` within `tol` of the path's stroke of width `width`? pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { - let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol); - quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol + let radius = width / 2.0 + tol; + if !path.bounding_box().inflate(radius, radius).contains(p) { + return false; + } + if !radius.is_finite() { + return distance_to_outline(path, p) <= radius; + } + + // Keep candidates whose squared distance could underflow near a zero radius. + let search_radius = radius.max(f64::MIN_POSITIVE.sqrt()); + path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius) +} + +// A Bézier stays inside the bounds of its control points. A line projection is +// already cheap, so only check the bounds before running a curve solver. +fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool { + let bounds = match segment { + PathSeg::Line(_) => return false, + PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2), + PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3), + }; + outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1) +} + +fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool { + // Leave room for rounding in the curve evaluation and the distance comparison. + let scale = p.abs().max(low.abs()).max(high.abs()).max(radius); + let padded = radius + 8.0 * f64::EPSILON * scale; + p < low - padded || p > high + padded +} + +fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 { + #[cfg(test)] + OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1)); + segment.nearest(p, 1e-9).distance_sq +} + +#[cfg(test)] +thread_local! { + static OUTLINE_NEAREST_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for @@ -185,6 +223,53 @@ mod tests { assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0))); } + #[test] + fn stroke_hit_skips_distant_curves_without_changing_results() { + let mut path = BezPath::new(); + for i in 0..96 { + let x = f64::from(i) * 16.0; + path.move_to((x, 0.0)); + path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0)); + } + path.move_to((512.0, 0.0)); + path.quad_to((513.0, 4.0), (514.0, 0.0)); + + for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] { + assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit); + assert!(path.bounding_box().contains(point)); + OUTLINE_NEAREST_CALLS.with(|count| count.set(0)); + assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit); + assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls); + } + + assert_stroke_hits_at_cutoff(); + } + + fn assert_stroke_hits_at_cutoff() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((0.0, 0.0)); + path.quad_to((4.0, 8.0), (8.0, 0.0)); + path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0)); + path.close_path(); + path.move_to((2.0, -3.0)); + path.line_to((2.0, -3.0)); + + for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] { + let transformed = transform * path.clone(); + for x in -2..23 { + for y in -5..9 { + let point = transform * Point::new(f64::from(x), f64::from(y)); + let distance = distance_to_outline(&transformed, point); + for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] { + let inside = transformed.bounding_box().inflate(radius, radius).contains(point); + assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}"); + } + } + } + } + } + #[test] fn evenodd_hole() { let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); From debd26b38f30f64328d90232f71c546ad798ac9a Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:43:08 -0800 Subject: [PATCH 63/65] Appearance: reorder shared effects on multiple objects (#10353) * Appearance: reorder shared effects on multiple objects * Appearance: compare resolved effect lists for aligned moves --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/engine/src/cmd/effectcmd.rs | 57 ++++++++++++-- crates/engine/src/tests/appearance.rs | 38 +++++++++ crates/ui-egui/src/panels/appearance.rs | 77 ++++++++++++++++--- crates/ui-egui/src/panels/appearance/tests.rs | 76 +++++++++++++++++- docs/mcp.md | 3 +- 5 files changed, 228 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 5d849cfed2..60a7aaba29 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -5,6 +5,7 @@ //! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"` //! the objects inside them (see `appearance`). +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; @@ -115,7 +116,7 @@ fn effect_specs() -> Vec { "Move Effect", [], None, - "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", + "{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}", has_doc, move_effect ), @@ -678,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids) })) } +impl Session { + /// Can the Appearance panel reorder shared effects on the exact subjects it displays? + /// A generated graph design or a selection normalized to different objects has no matching row. + pub fn can_reorder_selected_effects(&self) -> bool { + let Ok(st) = self.doc() else { return false }; + let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false }; + let selected: HashSet<_> = st.selection.subjects().iter().copied().collect(); + roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id)) + } +} + +/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the +/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing. +fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option>> { + let mut seen = HashSet::with_capacity(ids.len()); + let mut appearances: Vec<&vectorcraft_doc::Appearance> = + ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::>()?; + let first = *appearances.get(anchor)?; + if source == ItemTarget::Top { + return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]); + } + let item = source.effects_item(first, "effect.move").ok()??; + appearances.swap(0, anchor); + let shared = SharedStack::of(&appearances); + let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::>>()?; + slots.swap(0, anchor); + Some(slots) +} + /// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s. fn move_effect(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.move"; @@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src }; let copy = switch_or(p, "copy", false, C)?; let roots = edit_targets(s, p, C)?; - // Where an aligned effect would go in each of several different stacks isn't one place. - if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) { - return Err(bad(C, "effects of objects whose appearances differ can't be moved together")); - } + let reference = design_reference(s, p, C)?; + let d = &s.doc()?.doc; + let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) { + // An omitted item and a numbered item can use different anchors and still name the same row. + let shared = (!copy && reference.is_none()) + .then(|| { + shared_reorder_slots(d, &roots, src, src.anchor(s, &roots)) + .filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source)) + }) + .flatten(); + Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?) + } else { + None + }; // Where the effect landed in each object it moved in, in the order of `ids`. let mut landed = vec![]; let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| { let mut done = vec![]; - for id in &roots { + for (k, id) in roots.iter().enumerate() { let Some(n) = d.node_mut(*id) else { continue }; - let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?); + let (si, di) = match &slots { + Some(slots) => (slots[k], slots[k]), + None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?), + }; let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue }; // Taken out from the top down, so the lower positions stay valid; put back in order. let mut taken: Vec = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect(); diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index b967e6e3ed..8cb96c6a8a 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() { assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects"); } +#[test] +fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() { + let mut s = session(); + let (a, b) = reversed_pair(&mut s); + for (id, item) in [(a, 1), (b, 2)] { + for effect in ["distort.twist", "distort.roughen"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect})); + } + } + run(&mut s, "select.set", json!({"ids": [b.0, a.0]})); + let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone()); + let before = appearances(&s); + for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] { + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + let moved = run(&mut s, "effect.move", params); + assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor"); + assert_eq!(moved["index"], json!(0)); + for (appearance, item) in appearances(&s).iter().zip([1, 2]) { + let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["distort.roughen", "distort.twist"]); + assert!(appearance.effects_at(Some(0)).unwrap().is_empty()); + } + run(&mut s, "edit.undo", json!({})); + assert_eq!(appearances(&s), before); + } + + run(&mut s, "appearance.setActiveItem", json!({"index": 2})); + for destination in [0, 2] { + assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err()); + assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list"); + } + + run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"})); + let before = appearances(&s); + assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err()); + assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row"); +} + /// `effect.move`'s reply names where the effect landed in the object whose row the active item is /// (the first selected object), also when that object paints above the others. #[test] diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 8f28023e0a..c6c791b645 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let pass = pass.into_inner(); if let Some(list) = shown.inner { let opener = list.response.clone(); - apply_list(app, node.as_deref(), &order, selection, list); + apply_list(app, node.as_deref(), &order, mix, selection, list); if let (Some(key), Some(n)) = (app.ui.appearance_panel.menu, node.as_deref()) { row_menu(app, ui, &opener, n, key); } @@ -530,8 +530,7 @@ fn object_row_label(app: &VectorcraftApp, summary: Option<&Summary>, mixed: bool } } -/// The list over `rows` (`order` their keys), bound to `selection`. A mixed selection's rows don't -/// drag: where one would go in each of the different stacks isn't one place. +/// The list over `rows` (`order` their keys), bound to `selection`. fn show_list( ui: &mut Ui, cx: &RowCx<'_>, @@ -555,10 +554,11 @@ fn show_list( .deletable(true) .selection(Bind::bound(selection)) .can_drag(|key: &RowKey| key.drags()); - if let Some(n) = cx.node.filter(|_| cx.mix.is_none()) { + if let Some(n) = cx.node { + let mix = cx.mix; list = list .reorder(ReorderRule::new().copy_with(CopyKeys::Alt).into_groups()) - .accepts(move |drag: &ListDrag, over: Option<&RowKey>, insert: usize| accepts(n, order, drag, over, insert, copy)); + .accepts(move |drag: &ListDrag, over: Option<&RowKey>, insert: usize| accepts(n, order, mix, drag, over, insert, copy)); } list.show_items(ui, rows, &mut |key, item| build_row(cx, *key, item)) } @@ -569,6 +569,7 @@ fn apply_list( app: &mut VectorcraftApp, node: Option<&Node>, order: &[RowKey], + mix: Option<&Mixed>, selection: Selection, list: CollectionResponse, ) { @@ -610,7 +611,7 @@ fn apply_list( delete_selected(app, node, sel).ok(); } if let Some(mv) = moved { - reorder(app, n, order, &mv); + reorder(app, n, order, mix, &mv); } } @@ -1192,7 +1193,14 @@ fn mixed(app: &VectorcraftApp) -> Option { } let aps: Vec<&vectorcraft_doc::Appearance> = nodes.iter().map(|n| &*n.appearance).collect(); let fills_differ = rest.iter().any(|n| n.appearance.fill_paint() != first.appearance.fill_paint()); - Some(Mixed { shared: vectorcraft_doc::appearance::SharedStack::of(&aps), transparency, fills_differ }) + let object_effects_match = rest.iter().all(|n| n.appearance.effects == first.appearance.effects); + Some(Mixed { + shared: vectorcraft_doc::appearance::SharedStack::of(&aps), + transparency, + fills_differ, + object_effects_match, + effect_targets_match: app.session.can_reorder_selected_effects(), + }) } /// A mixed selection as the panel lists it ([`mixed`]). @@ -1203,6 +1211,10 @@ struct Mixed { transparency: bool, /// Their topmost fills differ: the object row shows no fill chip. fills_differ: bool, + /// All objects have the same complete, ordered object effect list. + object_effects_match: bool, + /// The command edits the same subjects whose rows the panel shows. + effect_targets_match: bool, } /// The selection's [`object_label`] and [`mixed`] summary for the active document as of one @@ -1673,17 +1685,40 @@ fn delete_selected(app: &mut VectorcraftApp, node: Option<&Node>, sel: Sel) -> R /// Whether the rows of `drag` may land before position `insert` of `order` (`over`: the row under /// the pointer, which takes them when it holds rows): a drop that moves or copies them /// ([`reorder_command`]). -fn accepts(n: &Node, order: &[RowKey], drag: &ListDrag, over: Option<&RowKey>, insert: usize, copy: bool) -> bool { +fn accepts(n: &Node, order: &[RowKey], mix: Option<&Mixed>, drag: &ListDrag, over: Option<&RowKey>, insert: usize, copy: bool) -> bool { let before = order.get(..insert).map_or(0, |rows| rows.iter().filter(|key| drag.keys.contains(key)).count()); let mv = ReorderMove::new(drag.grabbed, drag.keys.clone(), insert.saturating_sub(before), copy); let into = over.copied().filter(|key| key.has_children()).map(|key| mv.clone().in_group(Some(key))); - reorder_command(n, order, &mv).is_some() || into.is_some_and(|mv| reorder_command(n, order, &mv).is_some()) + reorder_for_selection(n, order, mix, &mv).is_some() || into.is_some_and(|mv| reorder_for_selection(n, order, mix, &mv).is_some()) +} + +/// A mixed selection has an unambiguous destination only within a list that all its objects share. +fn reorder_for_selection(n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove) -> Option<(&'static str, Value)> { + let (cmd, params) = reorder_command(n, order, mv)?; + let Some(mix) = mix else { return Some((cmd, params)) }; + let (item, _) = mv.key.effect()?; + let shared = item.map_or(mix.object_effects_match, |i| mix.shared.has_item(i)); + (cmd == "effect.move" && !mv.copy && mix.effect_targets_match && shared && params["fromItem"] == params["toItem"]).then_some((cmd, params)) } /// Runs the reorder `mv` of the rows `order` of `n` and picks the moved rows (the copies), the /// grabbed one the lead; a moved Contents row keeps its selection. -fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mv: &ReorderMove) { - let Some((cmd, params)) = reorder_command(n, order, mv) else { return }; +fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove) { + let Some((cmd, mut params)) = reorder_for_selection(n, order, mix, mv) else { return }; + if mix.is_some() { + if let Some((Some(item), _)) = mv.key.effect() { + // The panel shows the first selected object's rows. The engine's implicit active + // item uses that same anchor, even when another target paints first. + if app.session.appearance_item() != Some(item) && app.run("appearance.setActiveItem", json!({"index": item})).is_err() { + return; + } + if let Some(fields) = params.as_object_mut() { + fields.remove("fromItem"); + fields.remove("toItem"); + } + } + params = aligned(app, params); + } let Ok(result) = app.run(cmd, params.clone()) else { return }; let Some((kind, grabbed)) = mv.key.sel().rows() else { return }; let mut set: Vec = mv.keys.iter().filter_map(|key| key.sel().rows().map(|(_, k)| k)).collect(); @@ -1808,6 +1843,20 @@ fn items_move( Some(("appearance.moveItem", params)) } +/// An edge between rows in an expanded fill or stroke can report that item as its parent. +/// A drop immediately after the item header still means append to its effects. +fn item_effect_gap(remaining: &[RowKey], gap: usize, item: usize) -> Option { + let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied(); + if above == Some(RowKey::Item(item)) { + return None; + } + let index = |key: Option| match key { + Some(RowKey::ItemEffect(row, index)) if row == item => Some(index), + _ => None, + }; + index(remaining.get(gap).copied()).or_else(|| index(above).map(|at| at + 1)) +} + /// The effects `set` (ascending) of list `from_item` moved or copied to `gap` of `remaining`. fn effects_move( n: &Node, @@ -1818,7 +1867,11 @@ fn effects_move( mv: &ReorderMove, ) -> Option<(&'static str, Value)> { let (item, pos) = match mv.parent { - Some(RowKey::Item(i)) => (Some(i), n.appearance.effects_at(Some(i))?.len()), + Some(RowKey::Item(i)) => { + let end = n.appearance.effects_at(Some(i))?.len(); + let pos = if from_item == Some(i) && !mv.copy { item_effect_gap(remaining, gap, i).unwrap_or(end) } else { end }; + (Some(i), pos) + } Some(key) => key.effect()?, None => { let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied(); diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 5c601967d3..becf9ecc3c 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -353,6 +353,8 @@ fn drops_pick_the_command() { (mv(&[item(1)], 3, false, None), None), (mv(&[item(1)], 3, false, Some(ItemEffect(1, 0))), None), (mv(&[ItemEffect(1, 0)], 5, false, None), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))), + (mv(&[ItemEffect(1, 1)], 4, false, Some(item(1))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 1, "copy": false}))), + (mv(&[ItemEffect(1, 0)], 3, false, Some(item(1))), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))), (mv(&[ItemEffect(1, 0)], 4, false, None), None), (mv(&[ItemEffect(1, 1)], 5, true, Some(item(0))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 0, "copy": true}))), (mv(&[ItemEffect(1, 1)], 7, false, None), effects(json!({"from": 1, "fromItem": 1, "to": 1, "toItem": null, "copy": false}))), @@ -362,8 +364,8 @@ fn drops_pick_the_command() { assert_eq!(reorder_command(&path, &order, &moved), want, "{moved:?}"); } let drag = |keys: &[RowKey]| ListDrag::new(egui::Id::NULL, keys.to_vec(), keys[0]); - assert!(accepts(&path, &order, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row"); - assert!(!accepts(&path, &order, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is"); + assert!(accepts(&path, &order, None, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row"); + assert!(!accepts(&path, &order, None, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is"); // A group listed top-down S3, FA*, Contents, S1*, F0 (paint order F0 S1 FA S3, Contents above // two), FA and S1 dragged together. @@ -419,7 +421,7 @@ fn drops_pick_the_command() { ] { assert_eq!(reorder_command(&group, &order, &moved), want, "{moved:?}"); } - assert!(!accepts(&group, &order, &drag(&[Contents]), Some(&Contents), 3, false), "where it is"); + assert!(!accepts(&group, &order, None, &drag(&[Contents]), Some(&Contents), 3, false), "where it is"); } #[test] @@ -604,6 +606,74 @@ fn a_mixed_selection_lists_what_its_objects_share() { assert!(panel.shows("Mixed Objects")); } +#[test] +fn a_mixed_selection_reorders_its_identical_object_effect_lists() { + let mut app = app_with_a_selected_rectangle(); + let a = node(&app).id; + let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [b], "color": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [a.0, b]})).unwrap(); + for effect in ["distort.twist", "distort.roughen"] { + app.run("effect.apply", json!({"effect": effect, "item": null})).unwrap(); + } + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let order = |app: &VectorcraftApp| { + [a, NodeId(b)] + .map(|id| app.session.active().unwrap().doc.node(id).unwrap().appearance.effects.iter().map(|e| e.id.clone()).collect::>()) + }; + let before = order(&app); + let undo = steps(&app); + let mut panel = Panel::new(app, show); + assert!(panel.shows("Mixed Appearances")); + let drag = |panel: &mut Panel| { + let from = crate::panels::tests_appearance::row_spot(panel, &effect_row_label("distort.roughen")); + let above = panel.rect(&effect_row_label("distort.twist")); + panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE); + }; + drag(&mut panel); + { + let mut app = panel.app(); + assert_eq!(order(&app), [vec!["distort.roughen", "distort.twist"], vec!["distort.roughen", "distort.twist"]]); + assert_eq!(steps(&app), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(order(&app), before); + app.run("effect.apply", json!({"ids": [b], "effect": "stylize.feather", "item": null})).unwrap(); + } + let before = order(&panel.app()); + drag(&mut panel); + assert_eq!(order(&panel.app()), before, "a common prefix does not make both lists reorderable"); +} + +#[test] +fn a_mixed_selection_reorders_shared_stroke_effects_at_different_item_indices() { + let mut app = app_with_a_selected_rectangle(); + let a = node(&app).id; + let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("appearance.moveItem", json!({"from": 2, "to": 0})).unwrap(); + app.run("appearance.setItem", json!({"index": 0, "color": "#ff0000"})).unwrap(); + for (id, item) in [(a.0, 1), (b, 2)] { + for effect in ["distort.twist", "distort.roughen"] { + app.run("effect.apply", json!({"ids": [id], "item": item, "effect": effect})).unwrap(); + } + } + app.run("select.set", json!({"ids": [b, a.0]})).unwrap(); + app.ui.appearance_panel.open.insert(RowKey::Item(2)); + + let mut panel = Panel::new(app, show); + let from = crate::panels::tests_appearance::row_spot(&mut panel, &effect_row_label("distort.roughen")); + let above = panel.rect(&effect_row_label("distort.twist")); + panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE); + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + for (id, item) in [(a, 1), (NodeId(b), 2)] { + let effects = doc.node(id).unwrap().appearance.effects_at(Some(item)).unwrap(); + assert_eq!(effects.iter().map(|effect| effect.id.as_str()).collect::>(), ["distort.roughen", "distort.twist"]); + } + assert_eq!(app.ui.appearance_panel.selection.lead, Some(RowKey::ItemEffect(2, 0))); +} + /// The [`summary`] the canvas cache holds for the active document, checked field by field against /// what [`object_label`] and [`mixed`] work out from scratch. fn fresh_summary(app: &mut VectorcraftApp) -> Arc { diff --git a/docs/mcp.md b/docs/mcp.md index e99e34fe86..85e35043df 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7129,7 +7129,8 @@ act on several fills/strokes at once, and `appearance.showAllHidden` makes every visible again. In remote mode, `effect.dialog {effect, index, item}` opens an applied effect's dialog prefilled (`ui.dialog.confirm` runs `effect.setParams`); see the control protocol for the "already applied" question. `effect.move` rejects a `copy` value that is not a boolean, and every command that takes `aligned` rejects an `aligned` -value that is not a boolean. +value that is not a boolean. With `aligned: true`, objects with different appearances can reorder effects within an +identical object effect list or within a shared fill or stroke. Copies and moves between lists require equal appearances. Effect dialogs use the targeted object, group, or layer shown in Appearance. The Transform dialog previews valid numbers as they are typed, including Copies, distances with units, and rotation. With Preview off, changes apply From aaf3cc87f0425bda72f164b808a9ef690d98e733 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:43:27 -0800 Subject: [PATCH 64/65] PDF export: keep joins between opaque mesh patches smooth (#10372) Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/pdf/src/export/nodes.rs | 44 ++++++++++++++++- crates/pdf/src/tests/mesh_export.rs | 74 +++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index b3b5de36a4..a093ecc9c0 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +use vectorcraft_geom::Vec2; + use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf}; use super::{ Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind, @@ -19,6 +21,37 @@ fn brushed(b: Option, reach: f64) -> Option { if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b } } +/// Can the patch shade its own outline without folding across it? The differences of adjacent +/// tensor control points bound each directional derivative in a convex cone. If every pair of +/// derivatives has the same strict orientation, averaging them along any segment keeps them +/// independent, so distinct parameter points cannot map to the same point. +fn unfolded_patch(points: [(f32, f32); 12]) -> bool { + let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y))); + let top = [p[0], p[11], p[10], p[9]]; + let bottom = [p[3], p[4], p[5], p[6]]; + let left = [p[0], p[1], p[2], p[3]]; + let right = [p[9], p[8], p[7], p[6]]; + // Raise the linear blending terms of the Coons surface to cubic degree in each direction. + let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| { + let v = row as f64 / 3.0; + std::array::from_fn(|col| { + let u = col as f64 / 3.0; + let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v; + top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear + }) + }); + let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col])); + let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col])); + let orientation = du[0][0].cross(dv[0][0]).signum(); + du.into_iter().flatten().all(|u| { + dv.iter().flatten().all(|v| { + let cross = u.cross(*v) * orientation; + // Keep near-parallel directions on the existing clipped path through PDF quantization. + cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2() + }) + }) +} + #[cfg(test)] std::thread_local! { /// The objects this thread has measured for the walk and for the links (tests). @@ -542,7 +575,7 @@ impl Exporter<'_> { } } - /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1, + /// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1, /// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and /// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads /// instead banded, left seams between them, and made files with many meshes very large. @@ -560,7 +593,6 @@ impl Exporter<'_> { if !writable(s, Affine::IDENTITY, bounds) { return false; } - let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false }; let page: Vec = m.points.iter().map(|p| self.page_color(&p.color)).collect(); let mixed = page.windows(2).any(|w| w[0].model() != w[1].model()); let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. })); @@ -584,6 +616,14 @@ impl Exporter<'_> { patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] }); } } + // An unfolded single patch shades its own outline. Filling that exact outline makes some + // readers antialias it twice and leave seams where patches touch. Keep the outline for + // folded geometry and for meshes with more than one patch, which can overlap themselves. + let bounds_path = match patches.as_slice() { + [patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)), + _ => None, + }; + let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false }; let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false }; s.set_stroke(None); s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero })); diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index b2e8ecb2f6..b36926da21 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -2,12 +2,16 @@ //! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small //! flat-coloured paths that band, show seams and make the file large. +use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction}; +use craft::pdf::syntax::object::{Name, Object}; use vectorcraft_color::Color; use vectorcraft_doc::live::{GradientMesh, MeshAppearance}; use vectorcraft_doc::{ColorMode, Document, Node, NodeKind}; use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; use vectorcraft_testkit::raster::{assert_similar, render_artboard}; +use super::import_fidelity::stream; use crate::*; /// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured @@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) { (meshes, paths) } +fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document { + use std::fmt::Write as _; + let mut data = String::new(); + for boundary in boundaries { + data.push_str("00"); // Every patch supplies all its vertices. + for (x, y) in boundary { + write!(data, "{x:02X}{y:02X}").unwrap(); + } + data.push_str(&"28465A".repeat(4)); + } + data.push('>'); + let shading = stream( + "/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \ + /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode", + &data, + ); + let page = PdfPage { + resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)), + ..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q") + }; + let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap(); + assert_eq!(kinds(&imported).0, boundaries.len()); + imported +} + +fn has_curved_outline(bytes: &[u8]) -> bool { + let output = crate::pages::open(bytes, None).unwrap(); + let pages = output.pages(); + let has_curve = |content: &[u8]| { + let mut ops = TypedIter::new(content); + while let Some(op) = ops.next() { + if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) { + return true; + } + } + false + }; + if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) { + return true; + } + output.objects().into_iter().any(|object| match object { + Object::Stream(form) if form.dict().get::>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => { + has_curve(&form.decoded().unwrap()) + } + _ => false, + }) +} + +#[test] +fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() { + // The same cubic, in opposite directions, is the two patches' inner edge. + let imported = import_patches(&[ + [(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)], + [(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)], + ]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself"); + let reimported = import(&bytes).unwrap(); + assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings"); + assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01); +} + +#[test] +fn folded_pdf_mesh_still_uses_its_outline() { + let imported = + import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]); + let bytes = export(&imported, &PdfOptions::default()).unwrap(); + assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline"); +} + #[test] fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() { let d = doc(rgb, 1.0); From f29fe10c32dccdf3b4e9f91b7c597333499811f1 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:41:49 +0530 Subject: [PATCH 65/65] Retype: add a context menu to matching-font rows (#10594) * Retype: add a context menu to matching-font rows A secondary click, or Shift+F10 on the focused row, selects a font row in the Retype panel without setting its font and opens a menu with Apply Font (what a click on the row does; off without live text selected), the panel menu's sample sizes and Reset Retype Panel. The menu closes when the list or the document changes (G12). * Rerun CI: the apt package download failed in a test shard's setup --------- Co-authored-by: ruchirguitar Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/panels/retype.rs | 52 ++++++--- crates/ui-egui/src/panels/retype/tests.rs | 122 ++++++++++++++++++++++ crates/ui-egui/src/tests/panel_harness.rs | 5 + docs/gaps.md | 5 +- docs/ui-parity.md | 5 +- 5 files changed, 174 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/panels/retype.rs b/crates/ui-egui/src/panels/retype.rs index 16d607393c..697d80a2b8 100644 --- a/crates/ui-egui/src/panels/retype.rs +++ b/crates/ui-egui/src/panels/retype.rs @@ -7,15 +7,17 @@ //! list stays after the selection changes, so choosing a font in it sets that font on the live text //! selected then, as the font menus do. The sample field sets the text the samples show, and the //! panel menu sets their size; Reset Retype Panel clears the list. `retype.find`, `retype.list`, -//! `retype.preview` and `retype.reset` do the same. +//! `retype.preview` and `retype.reset` do the same. A font's menu (a secondary click on its row, or +//! Shift+F10 on the focused row) selects the row and holds Apply Font, which sets that font as a +//! click does, then the panel menu's sample sizes and Reset Retype Panel. use craft::behavior::{EditEvent, Mixed, keyed}; use craft::keymap::CommandRef; use craft::ui::buttons::{Button, Link}; -use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _}; +use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::primitives::ContentPainterCx; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::style::Variant; @@ -50,7 +52,7 @@ const SIZES: [(Size, &str, ThumbSize); 3] = [(Size::Small, "small", ThumbSize::Small), (Size::Medium, "medium", ThumbSize::Medium), (Size::Large, "large", ThumbSize::Large)]; /// One font in the list. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Found { pub family: String, pub style: String, @@ -114,21 +116,47 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let on_white = app.session.prefs.font_samples_on_white; let indexed: Vec<(usize, &Found)> = view.fonts.iter().enumerate().collect(); let source = keyed(&indexed, |(at, _)| *at); - // A click activates a row, so the same row chosen again sets its font again. - let list = List::::new(tl!("Matching fonts")).select(SelectMode::Single).activate(ActivateOn::Click).show_items( - ui, - &source, - &mut |key, _| { + // The rows are keyed by place, so a list with other fonts, or another document, is another + // list: a row's menu closes rather than act on the font that took its place. + let document = app.session.active().map(|st| st.uid); + // A click activates a row, so the same row chosen again sets its font again. A secondary + // click selects its row and asks for the row's menu; it does not activate the row. + let list = List::::new(tl!("Matching fonts")) + .id(ui.scope_id().with(("matching-fonts", document, &view.fonts))) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .row_menu() + .show_items(ui, &source, &mut |key, _| { let (family, style) = indexed.get(*key).map_or(("", ""), |(_, f)| (f.family.as_str(), f.style.as_str())); ListRow::new(format!("{family} {style}")).thumb_aspect(size, ThumbAspect::new(8, 1), move |cx: &ContentPainterCx, rect: Rect| { crate::font_menu::paint_family_sample(cx, rect, family, style, sample, on_white); }) - }, - ); - let chosen = list.events.iter().find_map(|e| match e { + }); + let mut chosen = list.events.iter().find_map(|e| match e { CollectionEvent::Activate(at) => view.fonts.get(*at), _ => None, }); + if let Some(request) = list.menu + && let Some(f) = view.fonts.get(request.key) + { + // Apply Font is off while choosing the font would set it on nothing. + let live = live_text_selected(app); + Menu::context(format!("{} {}", f.family, f.style), &list.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Apply Font")).enabled(live).show(ui).ran { + chosen = Some(f); + } + Divider::horizontal().show(ui); + for (size, name, _) in SIZES { + if MenuItem::new(size_label(size)).check(view.size == size).show(ui).ran { + run = Some(("retype.preview", json!({ "size": name }))); + } + } + Divider::horizontal().show(ui); + if MenuItem::new(tl!("Reset Retype Panel")).show(ui).ran { + run = Some(("retype.reset", json!({}))); + } + }); + } if let Some(f) = chosen && live_text_selected(app) { diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 992147064c..198f4cb2b9 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -232,3 +232,125 @@ fn choosing_a_listed_font_sets_it_on_the_selected_live_text() { click(&mut app, &ctx, "Source Serif 4 Regular"); assert!(app.session.active().unwrap().doc == before); } + +/// Live text in Source Sans 3, selected, and a list of two fonts → the app and the text's id. +fn listed_with_live_text() -> (VectorcraftApp, u64) { + let mut app = app(); + let font = |family: &str, style: &str| super::Found { family: family.into(), style: style.into(), matched: 1 }; + app.ui.retype.searched = true; + app.ui.retype.fonts = vec![font("Source Sans 3", "Bold"), font("Source Serif 4", "Regular")]; + let t = app.session.execute("text.create", &json!({"x": 10, "y": 300, "text": "live", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + select(&mut app, &[t]); + (app, t) +} + +fn family_of(app: &VectorcraftApp, id: u64) -> String { + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") }; + text.first_style().font_family.clone() +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +const SERIF: &str = "Source Serif 4 Regular"; +const SANS: &str = "Source Sans 3 Bold"; + +#[test] +fn a_fonts_menu_selects_its_row_without_setting_the_font() { + use craft::ui::contract::Role; + + let (app, t) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + let undo = undo_len(&panel.app()); + panel.secondary_click(SERIF); + assert!(panel.menu_item_enabled("Apply Font"), "live text is selected"); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "the secondary click sets no font"); + assert_eq!(undo_len(&panel.app()), undo); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); + assert!(panel.selected(SERIF), "the row the menu opened on is selected"); + assert!(!panel.selected(SANS)); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3"); +} + +#[test] +fn apply_font_sets_the_rows_font_on_the_live_text_in_one_undo_step() { + let (app, t) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + let undo = undo_len(&panel.app()); + // A menu opened on another row first, then closed: the menu acts on the row it opened on last. + panel.secondary_click(SANS); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.secondary_click(SERIF); + panel.click_menu_item("Apply Font"); + assert_eq!(family_of(&panel.app(), t), "Source Serif 4", "the font of the row the menu opened on"); + assert_eq!(undo_len(&panel.app()), undo + 1); +} + +#[test] +fn apply_font_is_off_without_live_text() { + let (mut app, t) = listed_with_live_text(); + select(&mut app, &[]); + let mut panel = Panel::new(app, show); + panel.secondary_click(SERIF); + assert!(!panel.menu_item_enabled("Apply Font")); + assert!(panel.menu_item_enabled("Reset Retype Panel"), "the panel's own items stay on"); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "text that is not selected keeps its font"); +} + +#[test] +fn the_fonts_menu_sets_the_sample_size_and_resets_the_panel() { + use craft::behavior::Mixed; + use craft::ui::contract::Role; + + let (app, _) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + let before = panel.app().ui.retype.size; + let (other, label) = if before == Size::Large { (Size::Small, "Small") } else { (Size::Large, "Large") }; + panel.secondary_click(SERIF); + panel.click_role(label, Role::MENU_ITEM_CHECK_BOX); + assert_eq!(panel.app().ui.retype.size, other, "the size changed to the one chosen"); + panel.secondary_click(SERIF); + assert_eq!(panel.toggled(label), Some(Mixed::Same(true)), "the size chosen is checked"); + panel.click_menu_item("Reset Retype Panel"); + assert!(!panel.app().ui.retype.searched, "the list is cleared"); + assert_eq!(panel.app().ui.retype.size, other, "the size stays"); +} + +#[test] +fn keyboard_opens_the_fonts_menu_and_escape_returns_focus() { + use craft::ui::contract::Role; + + let (app, t) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + panel.focus(SERIF); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + assert!(panel.menu_item_enabled("Apply Font")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); + assert!(panel.focused(SERIF)); + assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "opening and closing the menu sets no font"); +} + +#[test] +fn the_fonts_menu_closes_when_the_list_or_the_document_changes() { + use craft::ui::contract::Role; + + let (app, _) = listed_with_live_text(); + let mut panel = Panel::new(app, show); + panel.secondary_click(SERIF); + assert!(panel.shows_role("Apply Font", Role::MENU_ITEM)); + // Another search puts another font in the row's place. + panel.app().ui.retype.fonts.reverse(); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); + panel.secondary_click(SERIF); + assert!(panel.shows_role("Apply Font", Role::MENU_ITEM)); + panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap(); + panel.frame(); + assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM)); +} diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 7521da7d8c..65d23c6d3e 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -510,6 +510,11 @@ impl Panel { self.fixture.tree().focused_key() == self.look(name).node } + /// Whether the row or item named `name` reports itself selected. + pub(crate) fn selected(&self, name: &str) -> bool { + self.fixture.tree().selected_of(self.look(name).node).unwrap_or(false) + } + /// Whether the zero-based control of `role` has focus, including rows with identical names. pub(crate) fn focused_nth(&self, role: craft::ui::contract::Role, index: usize) -> bool { self.fixture.tree().focused_key() == self.look_nth(role, index).node diff --git a/docs/gaps.md b/docs/gaps.md index 10c5f8c549..7a3bb953f2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,7 +1,7 @@ # Gaps > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: SVG Interactivity event rows have an item menu (Remove Event, Clear Events, Link JavaScript Files…); scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: Retype panel font rows have an item context menu (Apply Font, sample sizes, Reset Retype Panel); scores and estimates unchanged; previously: G12: SVG Interactivity event rows have an item menu (Remove Event, Clear Events, Link JavaScript Files…); scores and estimates unchanged; previously: G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12: Document Info panel menu Selection Only (`ui.docInfo.selectionOnly`) counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. @@ -81,6 +81,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | G12: Retype panel font rows have an item context menu: a secondary click or Shift+F10 selects the row and offers Apply Font (what a click on the row does; off without live text selected), the panel menu's Small, Medium and Large sample sizes and Reset Retype Panel; the menu closes when the list or the document changes. Headless regressions: `panels::retype::tests`. Scores and estimates unchanged. | | 2026-12-02 | minor | G12: SVG Interactivity event rows have an item menu: a right-click (or Shift+F10 on the focused row) picks that event and offers Remove Event (`svgInteractivity.removeEvent` for that row, one undo step), Clear Events (`svgInteractivity.clearEvents`, enabled like the panel menu row) and Link JavaScript Files… (`ui.javascriptFilesDialog`). Headless regressions: `panels::svg_interactivity::tests`. Scores and estimates unchanged. | | 2026-11-25 | minor | Document Info › Objects: total enclosed area (`pathArea` in pt²) for closed and compound paths (holes subtracted per fill rule; guides and open paths left out) and formatted Path Area in document units, beyond reference panel (#6965). Worked out only when the request covers Objects (`pathArea` null otherwise or with `pathArea: false`); the panel asks for it only while Objects or All Categories is shown. Tests: `info_gives_the_paths_total_area`, `info_works_out_the_path_area_only_for_the_objects_category`, `the_path_area_is_worked_out_only_while_objects_is_shown`, `format_area_formats_and_trims_cleanly`. 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. | @@ -560,6 +561,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Done (2026-12-02):** Retype panel font rows have an item context menu ([apply Retype suggested fonts to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). A secondary click, or Shift+F10 on the focused row, selects that row without setting its font and offers **Apply Font**, which sets the row's font on the selected live text as a click does, in one undo step, and is off while no live text is selected; then the panel menu's **Small**, **Medium** and **Large** sample sizes (`retype.preview`, the current one checked) and **Reset Retype Panel** (`retype.reset`). The menu closes when the list or the document changes, so it never acts on the font that took its row's place. Headless regressions: `panels::retype::tests::a_fonts_menu_selects_its_row_without_setting_the_font`, `apply_font_sets_the_rows_font_on_the_live_text_in_one_undo_step`, `apply_font_is_off_without_live_text`, `the_fonts_menu_sets_the_sample_size_and_resets_the_panel`, `keyboard_opens_the_fonts_menu_and_escape_returns_focus` and `the_fonts_menu_closes_when_the_list_or_the_document_changes`. Other G12 gaps remain; scores and estimates unchanged. + - **Done (2026-12-02):** SVG Interactivity event rows have an item context menu. A right-click on an event row, or Shift+F10 on the focused row, picks that event and offers **Remove Event** (`svgInteractivity.removeEvent` for that row, one undo step, announced like the footer's Remove Selected Entry), **Clear Events** (`svgInteractivity.clearEvents`, enabled under the same rule as the panel menu row) and **Link JavaScript Files…** (`ui.javascriptFilesDialog`). The menu closes when its row leaves the list or the document changes. Headless regressions: `panels::svg_interactivity::tests::row_menu_picks_its_row_and_removes_that_event_in_one_undo_step`, `row_menu_offers_the_panel_menu_and_footer_commands`, `keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus` and `row_menu_closes_when_its_row_disappears_or_the_document_changes`. Other G12 gaps remain; scores and estimates unchanged. - Glyphs cells have an item context menu. A character offers **Insert Glyph** at the Type caret or in selected text. A glyph without a mapped character offers **Apply Alternate** for the character selected with the Type tool. The menu uses the same actions as Enter and double-click and disables the item when its text target cannot accept the glyph. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d73ae6bfd7..fde460db33 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,7 +1,7 @@ # UI and interaction parity > Status-bar snapping quick access (#8687, #8779): the bottom right offers Smart Guides, Snap to Point and Snap to Grid toggles plus the same live Snapping menu as the Control bar. Both use existing commands. Framework fit ranks omit the direct group first, then the dropdown, before the existing readouts or core status content narrow. The native buttons expose their current selected state. Scores and estimates are unchanged. -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: SVG Interactivity event rows have an item menu; scores and estimates unchanged; earlier: RFC-0052 Headless section, all unknown; earlier: Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged; previously: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (G12: Retype panel font rows have an item context menu (Apply Font, sample sizes, Reset Retype Panel); scores and estimates unchanged; previously: G12: SVG Interactivity event rows have an item menu; scores and estimates unchanged; earlier: RFC-0052 Headless section, all unknown; earlier: Ctrl/Cmd+arrow fine nudge, #5258; scores and estimates unchanged; previously: Smart Guides: in a document with more than 20,000 anchors, the snap targets are gathered topmost first, so the objects in front, the newest, keep their anchors, edges and centre as targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: 3D effect options: unchanged values preserve the document and add no Undo; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged; Layers: hollow diamond and state tooltip distinguish own appearance from targeting and selection (#8710), retaining #8757's ring visibility; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > Panel readout copy (#8432, #8826): Info values and paint names, Links information, and named Document Info rows with no separate value follow the guarded immediate-copy policy landed in #9353. A plain first click copies the full value and reports "Copied the value"; accessible activation copies it too. Selectable readouts retain word selection on double-click, Shift/drag selection and keyboard Copy/Cut. Links Location retains #9521's path fitting and full-path tooltip as static text, with the same full-value primary/accessible copy and a native Copy Location button for keyboard use. Scores and estimates are unchanged. > @@ -82,6 +82,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| | 2026-12-02 | minor | Canvas context menu: rows for edit, group, path, type, view and artboard commands show a leading icon from the app's icon set, so a row can be found by its shape; rows without a fitting glyph stay text only (#4602); scores and estimates unchanged | +| 2026-12-02 | minor | Retype panel (G12): font rows have an item context menu: a secondary click or Shift+F10 selects the row and offers Apply Font (what a click on the row does; off without live text selected), the panel menu's Small, Medium and Large sample sizes and Reset Retype Panel; the menu closes when the list or the document changes. Headless regressions: `panels::retype::tests`. Scores and estimates unchanged. | | 2026-12-02 | minor | Headless (RFC-0052) column on the Summary table and every behaviour table: 365 unknown, with marking rules | | 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-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | @@ -555,7 +556,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | unknown | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | unknown | | SVG Interactivity event row item menu (G12) | done | Right-clicking an event row (or Shift+F10 on the focused row) picks that event and offers Remove Event, Clear Events and Link JavaScript Files…, the same commands as the footer and the panel menu; the menu closes when its row leaves the list or the document or artwork selection changes. `panels::svg_interactivity::tests::row_menu_picks_its_row_and_removes_that_event_in_one_undo_step`, `row_menu_offers_the_panel_menu_and_footer_commands`, `keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus`, `row_menu_closes_when_its_row_disappears_or_the_document_changes` | unknown | -| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | unknown | +| Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). A row's context menu (secondary click or Shift+F10) selects it and offers Apply Font, off without live text, the three sample sizes and Reset Retype Panel (`panels::retype::tests`). Installed fonts not loaded yet are compared too, read in the background with Cancel (`retype.cancelSearch`). Opening it from the Type menu, the context menu, and the Properties panel for outlined shapes (the Properties panel Quick Action opens it for text selections only), filtering by font source and favorites, near matches and text in images are missing (#4934) | unknown | | Comments, Version History panels | missing | cloud features (out of scope) | unknown | | Blend panel (30.7) | partial | Window › Blend provides Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift, alongside the existing blend controls. Easing is disabled without a spine. Original polynomial distributions approximate the publicly documented behavior. On-canvas Appearance and Easing widgets set Shift and Ramp; a blend without a spine shows the Appearance widget alone. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) | unknown | | Gradient panel: Dither (30.0) | done | Dither box under the stops (`paint.editGradient` `dither`); dimmed behind the Stroke proxy, fills only; `panels::gradient` test | unknown |