From 1b9f1e26e8ca1ca44c64bf3b7206cd058fdb667f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:46:12 -0800 Subject: [PATCH 1/3] Image Trace: tracing again keeps the tracing's note and tags Tracing an Image Trace object again, with Image Trace > Make, Make and Expand, or a script's tracing options, replaced the object with one that had no attributes, so its note, tags and URL were lost. The new object now takes them over. A script's saved Tags and Tag objects follow the new object and keep their identity, as the PluginItem does. pathItems.removeAll() and textFrames.removeAll() could leave an image at the bottom of an ordinary group named Image Trace, which made the group a tracing. Both now throw "Only Image Trace can make a tracing" before anything is deleted, as move, remove() and zOrder do, counting a compound path that the deletion leaves empty. Follows up #9077. --- crates/engine/src/cmd/buildcmds/trace.rs | 25 ++++--- crates/engine/src/script/dom.rs | 18 +++++ crates/engine/src/script/dom/paths.rs | 11 ++- crates/engine/src/script/dom/tags.rs | 9 ++- crates/engine/src/script/dom/text.rs | 11 ++- crates/engine/src/tests/script_dom_tracing.rs | 75 +++++++++++++++++++ docs/mcp.md | 12 +-- docs/target-app-parity.md | 2 +- 8 files changed, 137 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index f5b3d9fa38..08a962f919 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1225,17 +1225,20 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result) -> } } +/// Whether deleting the objects `ids` together would leave an image first in an ordinary group +/// named as a tracing, which would make that group one. `edit.clear` also deletes a compound path +/// it leaves empty, so such a compound path counts as deleted. +pub(super) fn clearing_makes_tracing(d: &Document, ids: &[NodeId]) -> bool { + let mut gone: HashSet = ids.iter().copied().collect(); + let compounds: HashSet = + ids.iter().filter_map(|i| d.parent_of(*i)).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).collect(); + for c in compounds { + if d.children(Some(c)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id))) { + gone.insert(c); + } + } + let parents: HashSet = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect(); + parents.into_iter().filter(|p| named_as_tracing(d, *p)).any(|p| { + d.children(Some(p)).and_then(|c| c.iter().find(|n| !gone.contains(&n.id)).map(|n| matches!(n.kind, NodeKind::Image(_)))).unwrap_or(false) + }) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4c32058fa..34db320f87 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -474,15 +474,17 @@ 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, and so does an image the deletion would +/// leave first in an ordinary group named as a tracing. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, tracing) = 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 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 tracing = super::clearing_makes_tracing(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -492,6 +494,9 @@ 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 tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } 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/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs index dff0120f78..c9e6f619c0 100644 --- a/crates/engine/src/script/dom/tags.rs +++ b/crates/engine/src/script/dom/tags.rs @@ -47,10 +47,12 @@ fn owner_of(h: &Host, d: &Data) -> std::result::Result { } /// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must -/// still be in its document. +/// still be in its document. A tracing the run traced again is followed to the object that +/// replaced it, which keeps its tags, as its `PluginItem` is. fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = super::tracing::follow(h, doc.uid, id); let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some())); if !alive { return Err(HostError::Error(STALE_ITEM.into())); @@ -111,7 +113,8 @@ fn doc_of_owner(owner: Owner) -> Doc { } fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { - let [high, low] = id_parts(id); + // A tracing traced again keeps the id of the first object of its chain, as its `PluginItem` does. + let [high, low] = id_parts(super::tracing::origin(h, doc.uid, id)); let [tag_high, tag_low] = id_parts(NodeId(tag)); host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low]) } @@ -119,7 +122,7 @@ fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { /// `PageItem.tags`. pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer { let item = item_of(h, arg(a, 0))?; - let [high, low] = id_parts(item.id); + let [high, low] = id_parts(super::tracing::origin(h, item.doc.uid, item.id)); Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low])) } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 3c4acac317..9fae433f0e 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1363,16 +1363,18 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { } /// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a -/// locked artboard, stops it first, as `PageItems.removeAll()` does. +/// locked artboard, stops it first, as `PageItems.removeAll()` does, and so does an image the +/// deletion would leave first in an ordinary group named as a tracing. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, tracing) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.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 tracing = super::clearing_makes_tracing(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1382,6 +1384,9 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); } + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } 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_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..78e7fc930b 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1302,3 +1302,78 @@ fn retraced_plugin_is_the_same_object_as_its_collection_handle() { assert_eq!(out, vec![json!(true); 5]); let _ = std::fs::remove_dir_all(base); } + +#[test] +fn retrace_keeps_the_tracing_note_and_tags() { + let base = folder("retrace-attributes"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(); p.note = 'keep me'; var tags = p.tags, t = tags.add(); t.name = 'job'; t.value = '42';\ + p.tracing.tracingOptions.threshold = 90; vc.log(p.note); vc.log(p.tags.length); vc.log(p.tags[0].name + '=' + p.tags[0].value);\ + vc.log(tags.length); vc.log(t.value); vc.log(t === p.tags[0]); vc.log(tags === p.tags);", + ); + assert_eq!(out, [json!("keep me"), json!(1), json!("job=42"), json!(1), json!("42"), json!(true), json!(true)]); + // Image Trace › Make on the tracing keeps them too. + let id = traces(&s)[0]; + let r = s.execute("imageTrace.make", &json!({"id": id.0, "params": {"threshold": 100}})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + let attrs = d.node(id).and_then(|n| n.extras().attrs.as_deref().cloned()).unwrap_or_default(); + assert_eq!(attrs.note, "keep me"); + let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect(); + assert_eq!(tags, [("job", "42")]); + let r = s.execute("imageTrace.makeAndExpand", &json!({"id": id.0})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + let group = d.node(id).unwrap(); + assert!(matches!(group.kind, NodeKind::Group { .. })); + let attrs = group.extras().attrs.as_deref().cloned().unwrap_or_default(); + assert_eq!(attrs.note, "keep me"); + let tags: Vec<(&str, &str)> = attrs.tags.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect(); + assert_eq!(tags, [("job", "42")]); + let _ = std::fs::remove_dir_all(base); +} + +/// `pathItems.removeAll()` and `textFrames.removeAll()` refuse to leave an image at the bottom of an +/// ordinary group named as a tracing, before the document changes. +#[test] +fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let setup = |bottom: &str| { + format!( + "var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);" + ) + }; + for (name, bottom, list) in [ + ("remove-all-trace-name-paths", "d.pathItems.rectangle(10, 10, 20, 20)", "pathItems"), + // `edit.clear` also deletes the compound path its members leave empty. + ( + "remove-all-trace-name-compound", + "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\ + vc.run('object.compoundPath.make'); return d.pageItems[0]; })()", + "pathItems", + ), + ("remove-all-trace-name-type", "d.textFrames.pointText([10, 10])", "textFrames"), + ] { + let base = folder(name); + let (mut s, _) = session(&base, false); + log(&mut s, &base, &setup(bottom)); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(d.pageItems[0].typename);" + ), + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}"); + assert!(traces(&s).is_empty(), "{list}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}"); + assert_eq!(undo_steps(&s), steps, "{list}"); + let _ = std::fs::remove_dir_all(base); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index e716a1a08e..eb4cd18da8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3143,8 +3143,9 @@ through `$`: unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before - the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with - nothing changed, when they would leave an image at the bottom of such a group. An object of + the document changes, as renaming such a group does. `move`, `remove()`, `zOrder`, `pathItems.removeAll()` and + `textFrames.removeAll()` throw the same error, with nothing changed, when they would leave an image at the bottom of + such a group. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or @@ -3361,9 +3362,10 @@ through `$`: count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the - source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or - `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` - and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws + source image, the view, and the tracing's attributes (its note, tags and URL), and a value the tracing already has + runs no command. Assigning `viewRaster` or `viewVector` does not trace again: it runs `imageTrace.setView`. The + `PluginItem`, `TracingObject`, `TracingOptions` and the tracing's `Tags` and `Tag` objects follow the new object, + and a run traces again at most 10,000 times. Tracing again throws `Cannot retrace a tracing containing added artwork`, with nothing changed, when the tracing holds an object its trace did not make, whether this run, an earlier run or a command added it, and `releaseTracing()` throws `Cannot release a tracing containing added artwork` in the same case. When no object was added, both throw diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144759bf00..1961a50bae 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1115,7 +1115,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - 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: `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: `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. Tracing again keeps the tracing's note, tags and URL. 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, or deleting paths or type with `removeAll()` so that an image is left at its bottom, throws an error. `crates/engine/src/tests/script_dom_tracing.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. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`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: 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 cccd31c3aa2a3f1cf124172caf567a3e12332d56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 02:11:55 -0800 Subject: [PATCH 2/3] Clear: remove a compound path emptied through an emptied inner one Clear and the scripting tracing guard checked only the direct compound parents of the removed objects, once each. A compound path whose members were a removed path and an inner compound path the same clear emptied stayed behind empty, or went, depending on the order of the ids, and the guard could miss it. - emptied_compounds walks up through compound ancestors until nothing changes and returns the emptied compound paths sorted by id; Clear and clearing_makes_tracing both use it. - Clear with direct-selected anchors checks the compound path above each one it removes again. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/edit.rs | 36 +++++++++++++------ crates/engine/src/cmd/edit/tests.rs | 56 +++++++++++++++++++++++++++++ crates/engine/src/cmd/path.rs | 6 +++- crates/engine/src/script/dom.rs | 10 ++---- 5 files changed, 90 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 586deb604c..652f3e39b5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -885,7 +885,7 @@ pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop}; /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; -pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, artboard_tool_picks, emptied_compounds, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 55726c31c9..ea5f688b44 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1363,17 +1363,12 @@ fn clear(s: &mut Session, p: &Value) -> Result { } s.edit("Clear", |d, sel| { let clipped = clipped_ancestors(d, ids.iter().copied()); - let parents: Vec<_> = if keep_empty { - Vec::new() - } else { - ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect() - }; + let emptied = if keep_empty { Vec::new() } else { emptied_compounds(d, &ids) }; + // A compound path inside another emptied one leaves with it. + let outer: Vec = + emptied.iter().copied().filter(|p| !d.ancestry(*p).unwrap_or_default().iter().rev().skip(1).any(|a| emptied.binary_search(a).is_ok())).collect(); d.remove_many(&ids)?; - for p in parents { - if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { - d.remove(p)?; - } - } + d.remove_many(&outer)?; if with_guides { let gone = sel.guides.clone(); d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); @@ -1390,6 +1385,27 @@ fn clear(s: &mut Session, p: &Value) -> Result { ok() } +/// The compound paths that deleting the objects `ids` together leaves with no members, sorted by +/// id: a compound path counts when each of its members is deleted or is such a compound path, so +/// a compound path holding only an emptied inner one is emptied too. +pub(crate) fn emptied_compounds(d: &Document, ids: &[NodeId]) -> Vec { + let mut gone: BTreeSet = ids.iter().copied().collect(); + let mut emptied = BTreeSet::new(); + loop { + let parents: BTreeSet = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect(); + let found: BTreeSet = parents + .into_iter() + .filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) + .filter(|p| d.children(Some(*p)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id)))) + .collect(); + if found.is_empty() { + return emptied.into_iter().collect(); + } + gone.extend(found.iter().copied()); + emptied.extend(found); + } +} + /// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else /// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a /// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined` diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs index 7e0471f0f5..8764d313b8 100644 --- a/crates/engine/src/cmd/edit/tests.rs +++ b/crates/engine/src/cmd/edit/tests.rs @@ -400,3 +400,59 @@ fn selected_roots_are_found_once_for_each_document_and_selection() { selected_roots(&s).unwrap(); assert_eq!(roots_found() - before, 2, "an edit finds the roots once again"); } + +/// Clear removes a compound path whose members are cleared paths and a compound path the clear +/// empties, whichever order the ids come in, and the tracing guard's set counts both as deleted. +#[test] +fn clear_removes_a_compound_path_emptied_through_an_emptied_inner_one() { + for reversed in [false, true] { + let mut s = new_doc(); + let outer_paths = [(); 2].map(|()| rect(&mut s)); + let (outer, outer_members) = compound(&mut s, &outer_paths); + let inner_paths = [(); 2].map(|()| rect(&mut s)); + let (inner, inner_members) = compound(&mut s, &inner_paths); + s.edit("Nest", |d, _| { + let taken = d.remove_many(&[inner])?; + d.insert(Some(outer), 1, (*taken[0]).clone())?; + Ok(()) + }) + .unwrap(); + let mut ids: Vec = outer_members.iter().chain(&inner_members).copied().collect(); + if reversed { + ids.reverse(); + } + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(inner), Some(outer), "the inner compound path is a member of the outer one"); + let want: Vec = BTreeSet::from([outer, inner]).into_iter().collect(); + assert_eq!(emptied_compounds(d, &ids), want, "reversed: {reversed}"); + run(&mut s, "edit.clear", json!({"ids": ids.iter().map(|id| id.0).collect::>()})); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none(), "the emptied inner compound path goes (reversed: {reversed})"); + assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too (reversed: {reversed})"); + } +} + +/// With a direct-selected anchor of another path in the selection, Clear still removes the outer +/// compound path that an emptied inner one leaves empty. +#[test] +fn clear_with_direct_anchors_removes_a_compound_path_emptied_through_an_emptied_inner_one() { + let mut s = new_doc(); + let outer_paths = [(); 2].map(|()| rect(&mut s)); + let (outer, outer_members) = compound(&mut s, &outer_paths); + let inner_paths = [(); 2].map(|()| rect(&mut s)); + let (inner, inner_members) = compound(&mut s, &inner_paths); + let other = rect(&mut s); + s.edit("Nest", |d, _| { + let taken = d.remove_many(&[inner])?; + d.insert(Some(outer), 1, (*taken[0]).clone())?; + Ok(()) + }) + .unwrap(); + let whole: Vec = outer_members.iter().chain(&inner_members).copied().collect(); + select_direct(&mut s, &whole, &[(other, two_anchors())]); + run(&mut s, "edit.clear", json!({})); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none(), "the emptied inner compound path goes"); + assert!(d.node(outer).is_none(), "the outer compound path it leaves empty goes too"); + assert!(d.node(other).is_some(), "the path with anchors picked keeps its other sides"); +} diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 190c8b5810..a3234c2264 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1998,9 +1998,13 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo } } emptied.finish(d)?; - for p in compounds { + // A compound path left empty by an inner one that went is checked again after it. + let mut compounds = compounds; + while let Some(p) = compounds.pop_first() { if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { + let up = d.parent_of(p).filter(|u| matches!(d.node(*u).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); d.remove(p)?; + compounds.extend(up); } } super::edit::release_empty_clips(d, clipped); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6494a79ee7..511a8b95c2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -3055,16 +3055,10 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> /// Whether deleting the objects `ids` together would leave an image first in an ordinary group /// named as a tracing, which would make that group one. `edit.clear` also deletes a compound path -/// it leaves empty, so such a compound path counts as deleted. +/// it leaves empty, nested ones included, so such a compound path counts as deleted. pub(super) fn clearing_makes_tracing(d: &Document, ids: &[NodeId]) -> bool { let mut gone: HashSet = ids.iter().copied().collect(); - let compounds: HashSet = - ids.iter().filter_map(|i| d.parent_of(*i)).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).collect(); - for c in compounds { - if d.children(Some(c)).is_some_and(|k| k.iter().all(|n| gone.contains(&n.id))) { - gone.insert(c); - } - } + gone.extend(crate::cmd::emptied_compounds(d, ids)); let parents: HashSet = gone.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !gone.contains(p)).collect(); parents.into_iter().filter(|p| named_as_tracing(d, *p)).any(|p| { d.children(Some(p)).and_then(|c| c.iter().find(|n| !gone.contains(&n.id)).map(|n| matches!(n.kind, NodeKind::Image(_)))).unwrap_or(false) From ab636b13951748c2e4135c0e97cb3f90c6cd44f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:20:38 -0800 Subject: [PATCH 3/3] Image Trace: tracing again moves the tracing's attributes instead of copying them Tracing a tracing again copied its attributes twice: once when the edit read the tracing out of the document, and again for the new tracing. An object can hold 64 tags of up to 64 KiB each, so each extra copy could cost megabytes. The new tracing now takes the attributes from the edit's own copy of the old one. `vectorcraft_doc::attribute_copies()` counts copies of an object's attributes on the current thread, and a test checks that tracing again copies them once. --- crates/doc/src/lib.rs | 2 +- crates/doc/src/node.rs | 4 ++- crates/doc/src/node/attributes.rs | 30 ++++++++++++++++++- crates/engine/src/cmd/buildcmds/trace.rs | 7 +++-- crates/engine/src/tests/script_dom_tracing.rs | 21 +++++++++++++ 5 files changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 059a3d4bdc..5b6c67c1dc 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -119,7 +119,7 @@ pub use node::Knockout; pub use node::Scaling; pub use node::changed_nodes; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; -pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies}; pub use orient::OrientedBox; pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType}; pub use perspective::PerspectiveAttachment; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 3a4b2abd03..2fdb579ee1 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -25,7 +25,9 @@ mod opacity; mod ops; mod wire; -pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +pub use attributes::{ + ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies, +}; #[cfg(test)] pub(crate) use changed::COUNTERPART_LOOKUPS; pub use changed::changed_nodes; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 67d3d02308..62edeb3795 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -3,7 +3,7 @@ use super::live_shape::LiveShape; use super::{Deserialize, Node, Serialize}; /// Window → Attributes: an object's settings that don't change how it prints. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ObjectAttributes { /// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]). @@ -45,6 +45,34 @@ pub struct ObjectAttributes { pub tags: Vec, } +impl Clone for ObjectAttributes { + fn clone(&self) -> Self { + ATTRIBUTE_COPIES.set(ATTRIBUTE_COPIES.get().saturating_add(1)); + Self { + show_center: self.show_center, + image_map: self.image_map, + url: self.url.clone(), + note: self.note.clone(), + data: self.data.clone(), + events: self.events.clone(), + classes: self.classes.clone(), + foreign: self.foreign.clone(), + tags: self.tags.clone(), + } + } +} + +thread_local! { + /// [`attribute_copies`] of this thread. + static ATTRIBUTE_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times an object's [`ObjectAttributes`] have been copied on this thread. Tags can hold +/// up to [`MAX_TAGS`] values of [`MAX_TAG_TEXT`] bytes each, so each copy can cost megabytes. +pub fn attribute_copies() -> u64 { + ATTRIBUTE_COPIES.get() +} + /// The most tags one object has. pub const MAX_TAGS: usize = 64; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 08a962f919..f8ac3f152b 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1118,7 +1118,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result