From 13488c3103a4d3fd7aa6d34ec09db4e3734071e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:10:09 -0800 Subject: [PATCH 01/14] 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 02/14] 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 ec943eebf7dfa14576e4589991e8b2f84ca2e4b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 01:02:12 -0800 Subject: [PATCH 03/14] 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 04/14] 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 05/14] 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 06/14] 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 07/14] 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 bf13038b8d41cc4c860645df491ca9a0a79ea97d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:36:45 -0800 Subject: [PATCH 08/14] 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 9995ffc36c7dc4beab3e10e6e8cc2ceb7d28056c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:53:40 -0800 Subject: [PATCH 09/14] 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 6b442ae207b30bd82de690ed40bd46c1d5f22f6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:24:15 -0800 Subject: [PATCH 10/14] 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 11/14] 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 12/14] 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 5277ec20ef30bc92e09e6b9a8ca1eb25d13e991f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 11:37:22 -0800 Subject: [PATCH 13/14] 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 4fbe7364d96bcedaa552995a486e554817f96dda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 12:12:26 -0800 Subject: [PATCH 14/14] 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");