mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 20:43:18 -05:00
Scripts: moving an image cannot make a tracing; counts do only their work
- move() and duplicate() refuse to put an image at the bottom of an ordinary group named Image Trace, before the document changes, as renaming such a group already does. A tracing's source image moved out keeps its own error. - pathCount and usedColorCount no longer walk the anchor points, and anchorCount charges each path inside a compound path it reads. - The run keeps the reverse of its replacement map, so finding the first object of a chain no longer scans the whole map at each step. - docs: the source image of a traced item is left out of pageItems, placedItems and rasterItems and is reached through PluginItem.tracing.sourceArt; docs/mcp.md lists the new error.
This commit is contained in:
1 parent
6de89eece9
commit
d9d9354ec7
5 files changed
+120
-24
No files matched your search
@@ -2788,10 +2788,35 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
|
||||
let name = d.node(item.id).and_then(typename).unwrap_or("page item");
|
||||
return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0)));
|
||||
}
|
||||
// Checked here as well as in `place`, so `duplicate` refuses before it makes the copy. A
|
||||
// tracing's source image moved out keeps the error `place` gives it.
|
||||
let image = d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)));
|
||||
if image && (copy || !crate::cmd::is_trace_source(d, item.id)) && named_as_tracing(d, parent) {
|
||||
// Where the image comes from: its index in `parent` when it is already there.
|
||||
let own = d.position(item.id).and_then(|(p, i, _)| (p == Some(parent)).then_some(i)).filter(|_| !copy);
|
||||
let count = d.children(Some(parent)).map_or(0, Vec::len);
|
||||
let first = match how {
|
||||
Placement::Bottom => true,
|
||||
Placement::Top => count == usize::from(own.is_some()),
|
||||
Placement::Below => beside.and_then(|b| d.position(b)).is_some_and(|(_, i, _)| i == 0 || (i == 1 && own == Some(0))),
|
||||
Placement::Above => false,
|
||||
};
|
||||
if first {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
}
|
||||
Ok(Destination { parent, beside, how })
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `id` is an ordinary group named as an Image Trace object that is not one: an image put
|
||||
/// first in it would make it a tracing.
|
||||
fn named_as_tracing(d: &Document, id: NodeId) -> bool {
|
||||
d.node(id).is_some_and(|p| {
|
||||
!crate::cmd::is_trace_group(p) && matches!(p.kind, NodeKind::Group { clip: false, .. }) && p.name.as_deref() == Some(crate::cmd::TRACE_NAME)
|
||||
})
|
||||
}
|
||||
|
||||
/// 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| {
|
||||
@@ -2822,7 +2847,12 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
}
|
||||
(_, None) => count,
|
||||
};
|
||||
Ok::<_, HostError>(if clips { at.max(1) } else { at })
|
||||
let at = if clips { at.max(1) } else { at };
|
||||
// An image put first in an ordinary group named as a tracing would make that group one.
|
||||
if at == 0 && d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) && named_as_tracing(d, to.parent) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
Ok::<_, HostError>(at)
|
||||
})?;
|
||||
let now = with_doc(h, doc, |_, st| st.doc.position(id));
|
||||
if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) {
|
||||
|
||||
@@ -121,6 +121,8 @@ const NOT_IMPLEMENTED: &[&str] = &[
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
next: RefCell<HashMap<(u64, u64), u64>>,
|
||||
/// `next` the other way round: for each replacing object, the object it replaced.
|
||||
prev: RefCell<HashMap<(u64, u64), u64>>,
|
||||
sources: RefCell<HashMap<(u64, u64), NodeId>>,
|
||||
descendants: RefCell<HashMap<(u64, u64), HashSet<NodeId>>>,
|
||||
retraces: Cell<usize>,
|
||||
@@ -154,12 +156,12 @@ pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
/// in the chain resolves to it.
|
||||
pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
let first = {
|
||||
let next = h.dom.tracing.next.borrow();
|
||||
let prev = h.dom.tracing.prev.borrow();
|
||||
let mut first = id;
|
||||
// Each object replaces one made before it, so the steps end; the bound holds them anyway.
|
||||
for _ in 0..next.len() {
|
||||
match next.iter().find(|((u, _), n)| *u == uid && **n == first.0) {
|
||||
Some(((_, old), _)) => first = NodeId(*old),
|
||||
for _ in 0..prev.len() {
|
||||
match prev.get(&(uid, first.0)) {
|
||||
Some(old) => first = NodeId(*old),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
@@ -170,7 +172,14 @@ pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId {
|
||||
|
||||
/// Records that `new` replaced `old` in the document `uid`.
|
||||
fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) {
|
||||
h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0);
|
||||
let mut prev = h.dom.tracing.prev.borrow_mut();
|
||||
// A second replacement of `old` takes the place of the first in both directions.
|
||||
if let Some(earlier) = h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0)
|
||||
&& prev.get(&(uid, earlier)) == Some(&old.0)
|
||||
{
|
||||
prev.remove(&(uid, earlier));
|
||||
}
|
||||
prev.insert((uid, new.0), old.0);
|
||||
}
|
||||
|
||||
pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) {
|
||||
@@ -413,10 +422,27 @@ struct Counts {
|
||||
visited: u64,
|
||||
}
|
||||
|
||||
fn anchors_of(n: &Node) -> u64 {
|
||||
/// Which of a tracing's counts a read needs; the others are not worked out.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Metric {
|
||||
Paths,
|
||||
Anchors,
|
||||
Colors,
|
||||
}
|
||||
|
||||
/// The anchor points of `n` and every path in it, adding each object looked at below `n` to
|
||||
/// `visited`.
|
||||
fn anchors_of(n: &Node, visited: &mut u64) -> u64 {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.anchor_count() as u64,
|
||||
_ => n.children().map_or(0, |c| c.iter().map(|m| anchors_of(m)).sum()),
|
||||
_ => n.children().map_or(0, |c| {
|
||||
c.iter()
|
||||
.map(|m| {
|
||||
*visited += 1;
|
||||
anchors_of(m, visited)
|
||||
})
|
||||
.sum()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,8 +451,10 @@ fn anchors_of(n: &Node) -> u64 {
|
||||
/// are a clip group directly in the tracing that [`crate::cmd::is_seam_fills`] accepts, or, for a
|
||||
/// trace made before seam fills were clipped, the lowest item above the source image when it
|
||||
/// accepts that. A group nested deeper, or an unclipped group higher up, is counted. An Image
|
||||
/// Trace object inside `g` leaves out its own seam fills the same way.
|
||||
fn counts(g: &Node) -> Counts {
|
||||
/// Trace object inside `g` leaves out its own seam fills the same way. Only the count `metric`
|
||||
/// names is worked out; a compound path counts as one path, and the paths inside it are looked at
|
||||
/// (and counted in `visited`) only for its anchor points.
|
||||
fn counts(g: &Node, metric: Metric) -> Counts {
|
||||
let mut c = Counts::default();
|
||||
let mut paints = HashSet::new();
|
||||
let mut todo: Vec<&Arc<Node>> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default();
|
||||
@@ -443,12 +471,17 @@ fn counts(g: &Node) -> Counts {
|
||||
NodeKind::Path { clipping: true, .. } => {}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
c.paths += 1;
|
||||
c.anchors += anchors_of(n);
|
||||
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
|
||||
if paint != vectorcraft_color::Paint::None
|
||||
&& let Ok(key) = serde_json::to_string(&paint)
|
||||
{
|
||||
paints.insert(key);
|
||||
match metric {
|
||||
Metric::Paths => {}
|
||||
Metric::Anchors => c.anchors += anchors_of(n, &mut c.visited),
|
||||
Metric::Colors => {
|
||||
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
|
||||
if paint != vectorcraft_color::Paint::None
|
||||
&& let Ok(key) = serde_json::to_string(&paint)
|
||||
{
|
||||
paints.insert(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -472,23 +505,27 @@ fn seam_fills_of(g: &Node) -> HashSet<NodeId> {
|
||||
}
|
||||
|
||||
/// Reads the counts of the tracing `this` names with `f`.
|
||||
fn count(h: &Host, a: &[Data], f: fn(&Counts) -> u64) -> Answer {
|
||||
fn count(h: &Host, a: &[Data], metric: Metric) -> Answer {
|
||||
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?;
|
||||
let c = read_group(h, item, |_, g| Ok(counts(g)))?;
|
||||
let c = read_group(h, item, |_, g| Ok(counts(g, metric)))?;
|
||||
h.charge_call(c.visited)?;
|
||||
Ok(num(float(f(&c))))
|
||||
Ok(num(float(match metric {
|
||||
Metric::Paths => c.paths,
|
||||
Metric::Anchors => c.anchors,
|
||||
Metric::Colors => c.colors,
|
||||
})))
|
||||
}
|
||||
|
||||
fn tracing_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, |c| c.paths)
|
||||
count(h, a, Metric::Paths)
|
||||
}
|
||||
|
||||
fn tracing_anchors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, |c| c.anchors)
|
||||
count(h, a, Metric::Anchors)
|
||||
}
|
||||
|
||||
fn tracing_colors(h: &Host, a: &[Data]) -> Answer {
|
||||
count(h, a, |c| c.colors)
|
||||
count(h, a, Metric::Colors)
|
||||
}
|
||||
|
||||
fn tracing_areas(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
@@ -1123,6 +1123,33 @@ fn a_group_holding_an_image_cannot_take_the_tracing_name() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() {
|
||||
let base = folder("move-into-trace-name");
|
||||
let (mut s, _) = session(&base, false);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument, r = d.rasterItems[0], m = [];\
|
||||
d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); var g = d.pageItems[0];\
|
||||
g.name = 'Image Trace';\
|
||||
try { r.move(g, ElementPlacement.PLACEATEND); m.push('moved'); } catch (e) { m.push(e.message); }\
|
||||
try { r.duplicate(g, ElementPlacement.PLACEATEND); m.push('copied'); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m); vc.log(d.rasterItems.length); vc.log(g.typename);\
|
||||
r.move(g, ElementPlacement.PLACEATBEGINNING); vc.log(g.typename);",
|
||||
);
|
||||
let refused = json!("Only Image Trace can make a tracing");
|
||||
assert_eq!(out, [json!([refused, refused]), json!(1), json!("GroupItem"), json!("GroupItem")]);
|
||||
assert!(traces(&s).is_empty());
|
||||
let d = &s.active().unwrap().doc;
|
||||
let g = top(&s)[0];
|
||||
let kids: Vec<bool> = d.children(Some(g)).unwrap().iter().map(|n| matches!(n.kind, crate::doc::NodeKind::Image(_))).collect();
|
||||
assert_eq!(kids, [false, true], "the image went in above the rectangle");
|
||||
assert_eq!(undo_steps(&s), before + 1, "the run is one step");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retrace_keeps_the_tracing_opacity_and_blend_mode() {
|
||||
let base = folder("retrace-appearance");
|
||||
|
||||
+3
-1
@@ -3039,7 +3039,9 @@ through `$`:
|
||||
is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the
|
||||
document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Moving a tracing's visible,
|
||||
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`. An object of
|
||||
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. 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
|
||||
|
||||
@@ -1113,7 +1113,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. `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. 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: `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`). 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`.
|
||||
|
||||
Reference in new issue
Block a user