Scripts: point handles go stale after a revert; flush keeps only live selections

PathPoints and PathPoint handles carry the document's revert count. Writing point edits drops selected anchors and segments that no longer exist, in the same step as the edit. Overprint writes that the command skips throw, and changeFillGradients true with changePositions false throws until it is available.
This commit is contained in:
dotCooCoo committed 2026-11-28 22:03:07 -08:00
1 parent bb80534f3e
commit e9010cd363
2 files changed
+159 -19

No files matched your search

+46 -19
View File
@@ -54,7 +54,8 @@
//! are locked; assigning the value the path has runs no command.
//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
//! `changeStrokePattern` given as different values throw an error; gradients move with the art,
//! so `changeFillGradients` false throws an error that says it is not available yet.
//! so `changeFillGradients` false throws an error that says it is not available yet, as does
//! `changeFillGradients` true with `changePositions` false.
use std::rc::Rc;
use std::sync::Arc;
@@ -70,8 +71,8 @@ use vectorcraft_tools::params::gradient_params;
use super::{
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number,
on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc,
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, item_rect, later, method, named, num, number, on_doc, pair,
point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc,
};
use crate::{DocState, NodeId, NodeKind};
@@ -142,9 +143,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError
path_of(h, arg(a, 0))
}
/// The path of the run `run`, document `uid` and id parts `high` and `low`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result<Item, HostError> {
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) {
return Err(HostError::Error(STALE_ITEM.into()));
}
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
path_of(h, &path_ref(h, Item { doc, id }))
}
@@ -255,7 +259,27 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
}
let subpaths: Vec<Value> =
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::<Vec<_>>(), "closed": sp.closed})).collect();
edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
super::atomically(h, |h| {
if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) {
let selection = &mut st.selection;
if let Some(anchors) = selection.anchors.get_mut(&item.id) {
anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len()));
}
if let Some(segments) = selection.segments.get_mut(&item.id) {
segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count()));
if segments.is_empty() {
selection.segments.remove(&item.id);
}
}
if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) {
selection.key_anchor = None;
}
if selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || point_count(&subs) == 0 {
selection.remove(item.id);
}
}
edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))
})?;
Ok(())
}
@@ -293,8 +317,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
o.entry("ids").or_insert_with(|| json!([item.id.0]));
}
let result = keeping_paint(h, || edit_item(h, item, id, &params))?;
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set")
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == "objects" && *v == Data::Number(0.0)))
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0)));
}
@@ -603,8 +628,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
fn path_points(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let [high, low] = id_parts(item.id);
Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low]))
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
Ok(host_ref("PathPoints", &handle))
}
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
@@ -1091,6 +1116,9 @@ fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::R
if flags[2] == Some(false) {
return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2])));
}
if flags[0] == Some(false) && flags[2] == Some(true) {
return Err(HostError::Error(format!("{} true with {} false is not available yet", names[2], names[0])));
}
if let (Some(f), Some(s)) = (flags[1], flags[3])
&& f != s
{
@@ -1181,8 +1209,8 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer {
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
path_at(h, *run, *uid, *high, *low)
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
path_at(h, *run, *uid, *high, *low, *reverts)
}
fn points_length(h: &super::Host, a: &[Data]) -> Answer {
@@ -1196,8 +1224,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer {
}
fn point_ref(h: &super::Host, item: Item, i: usize) -> Data {
let [high, low] = id_parts(item.id);
host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))])
let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec();
handle.extend([float(i as u64), float(point_cuts(h, item))]);
host_ref("PathPoint", &handle)
}
/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change
@@ -1368,8 +1397,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer {
/// point of the path removed or replaced since `this` was read.
pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
if whole(*cuts) != Some(point_cuts(h, item)) {
return Err(HostError::Error(STALE_POINT.into()));
}
@@ -1576,9 +1605,7 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
out
})?;
h.charge_call(picked.len() as u64)?;
let [high, low] = id_parts(item.id);
let cuts = float(point_cuts(h, item));
let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect();
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
Ok(Data::Array(points))
}
+113
View File
@@ -329,6 +329,56 @@ fn removing_a_point_remaps_selection_and_clears_deleted_geometry() {
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)]));
}
#[test]
fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() {
for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] {
for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] {
let (mut s, a, b) = doc();
s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap();
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
let anchors = selected_anchors(&s, a);
let steps = undo_steps(&s);
let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}"));
assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] });
assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed);
let selection = &s.active().unwrap().selection;
assert!(selection.contains(b));
assert_eq!(selected_anchors(&s, a), anchors);
let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect();
assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] });
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, a).path_data().unwrap().subpaths[0].closed);
}
}
}
#[test]
fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() {
let (mut s, a, _) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let before = node(&s, a);
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\
p.name = 'changed'; vc.run('file.revert');\
try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\
var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\
fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);"
),
);
assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}");
assert_ne!(node(&s, a).path_data(), before.path_data());
s.execute("file.revert", &json!({})).unwrap();
}
}
#[test]
fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() {
let (mut s, a, _) = doc();
@@ -458,6 +508,46 @@ fn paint_writes_refuse_generated_graph_design_paths() {
}
}
#[test]
fn overprint_writes_refuse_generated_graph_design_paths() {
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
let (mut s, a, _) = doc();
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap();
s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap();
let graph = NodeId(
s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
let graph_node = node(&s, graph);
let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap();
let mut paths = Vec::new();
design.walk(&mut |n| {
if matches!(n.kind, NodeKind::Path { .. }) {
paths.push(n.id);
}
});
s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap();
let before = (art(&s), undo_steps(&s));
for property in ["fillOverprint", "strokeOverprint"] {
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\
try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);"
),
);
assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}");
assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}");
assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}");
}
}
}
#[test]
fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() {
let (mut s, a, b) = doc();
@@ -1087,6 +1177,29 @@ fn a_point_beyond_the_canvas_throws_when_it_is_assigned() {
assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written");
}
#[test]
fn transforms_refuse_moving_gradients_without_the_path() {
for transform in
["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"]
{
let (mut s, a, b) = doc();
s.execute(
"paint.setFill",
&json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
)
.unwrap();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s));
let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}"));
assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}");
assert!(
out[1].as_str().unwrap().contains("changeFillGradients true with changePositions false is not available yet"),
"{transform}: {out:?}"
);
assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}");
}
}
#[test]
fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() {
let mut s = Session::new();