Scripts: a path point read before a command changes its path is stale

A PathPoint read before vc.run('path.setAnchors', ...) replaced its
path's points stayed valid, so a later write changed the replacement's
point at the same index. The object model now keeps each path whose
points the script read and checks it after every command and when a
point is used. When the path's points differ from the ones it last saw,
or the path is gone, the points read before throw `Stale path point`.
This covers any command run with vc.run, an undo, and a change that a
later command reverses. Points stay valid through the object model's
own changes to the path or to an object that holds it, such as
translate().

docs/mcp.md and the module doc state the rule.
This commit is contained in:
dotCooCoo committed 2026-11-21 18:06:28 -08:00
1 parent 07d673898f
commit bd945697e8
5 files changed
+173 -11

No files matched your search

+26 -6
View File
@@ -89,8 +89,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// What the object model keeps for one run: its coordinate system, the last list of a document's
/// page items, kept while that document is unchanged, the point changes of a path not written yet,
/// how many times it removed or replaced each path's points, and whether a call's own savepoint
/// ([`atomically`]) is open.
/// how many times each path's points went stale and each path as the run last saw its points, and
/// whether a call's own savepoint ([`atomically`]) is open.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
@@ -100,9 +100,18 @@ pub(super) struct State {
/// A path and its subpaths with the point changes the run has made to it and not written yet
/// ([`flush`]).
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
/// How many times the run has removed or replaced points of each path, by document uid and
/// path id ([`paths`]).
/// How many times the points the run read of each path went stale, by document uid and path id
/// ([`paths`]).
point_cuts: RefCell<std::collections::HashMap<(u64, u64), u64>>,
/// Each path whose points the run read, as the run last saw it, by document uid and path id
/// ([`paths`]).
point_nodes: RefCell<std::collections::HashMap<(u64, u64), Arc<crate::doc::Node>>>,
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
/// points it read ([`paths`]).
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
/// change.
editing: Cell<Option<Item>>,
saving: Cell<bool>,
}
@@ -169,6 +178,12 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
paths::flush(h)
}
/// Notes the changes a command made to the points of the paths the run has read
/// ([`paths::see_all_points`]).
pub(super) fn see_points(h: &Host) {
paths::see_all_points(h)
}
fn get(link: &Link, f: Member) -> HostMember {
HostMember::Get(function(link, f))
}
@@ -621,9 +636,14 @@ fn on_doc<T>(
Ok(v)
}
/// Runs `id` with `params` on the item's document, its selection kept.
/// Runs `id` with `params` on the item's document, its selection kept. The points the run read of
/// the item's paths stay valid through the change ([`paths::see_all_points`]).
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = on_doc(h, item.doc.uid, true, |h| command(h, id, params));
h.dom.editing.set(kept);
r
}
/// Reads the document of `doc` with `f`.
+102 -4
View File
@@ -30,7 +30,10 @@
//! Removing the last points leaves the path, with no points.
//! - A point whose index is past the end of its path throws `Stale path point`, and so does a
//! point read before the run removed a point of its path or replaced its points
//! (`PathPoint.remove()`, `PathPoints.removeAll()`, `setEntirePath`).
//! (`PathPoint.remove()`, `PathPoints.removeAll()`, `setEntirePath`), or before anything other
//! than the object model changed the path's points (a command run with `vc.run`, such as
//! `path.setAnchors`, `object.move` or `edit.undo`). Points stay valid through the object
//! model's other changes to the path or to an object that holds it, such as `translate()`.
//! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole
//! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that
//! says it is not available yet. `rotateAbout` and `scaleAbout` default to
@@ -41,6 +44,7 @@
//! so `changeFillGradients` false throws an error that says it is not available yet.
use std::rc::Rc;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
@@ -1071,19 +1075,113 @@ fn point_ref(h: &super::Host, item: Item, i: usize) -> Data {
host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))])
}
/// How many times the run has removed or replaced points of `item`.
/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change
/// made to them since the run last saw them.
fn point_cuts(h: &super::Host, item: Item) -> u64 {
h.dom.point_cuts.borrow().get(&(item.doc.uid, item.id.0)).copied().unwrap_or(0)
let key = (item.doc.uid, item.id.0);
see_points(h, key, || false);
h.dom.point_cuts.borrow().get(&key).copied().unwrap_or(0)
}
/// Notes that the run removed or replaced points of `item`, which makes the points read before
/// stale.
fn cut_points(h: &super::Host, item: Item) {
cut_key(h, (item.doc.uid, item.id.0));
}
/// [`cut_points`] for the path of document uid and path id `key`.
fn cut_key(h: &super::Host, key: (u64, u64)) {
let mut cuts = h.dom.point_cuts.borrow_mut();
let n = cuts.entry((item.doc.uid, item.id.0)).or_insert(0);
let n = cuts.entry(key).or_insert(0);
*n = n.saturating_add(1);
}
/// The node of `id` in `d`, as the document holds it.
fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc<crate::doc::Node>> {
let at = d.index_path(id)?;
let (first, rest) = at.split_first()?;
let mut cur = d.layers.get(*first)?;
for &i in rest {
cur = cur.children()?.get(i)?;
}
Some(cur)
}
/// Keeps the path of document uid and path id `key` as it is now, the first time the run reads its
/// points and after each later look. When its points differ from the ones the run last saw, the
/// points read before go stale, unless `own`: the object model made the change
/// ([`see_all_points`]), which `own` is asked only after a change. The kept node is shared with
/// the document, so a node whose pointer is unchanged has unchanged points, and any change to it
/// makes a new node.
fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
let node = {
let s = h.session.borrow();
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned())
};
// A path that is gone makes its points stale, so that an undo that brings it back leaves them
// stale.
let Some(node) = node else {
if h.dom.point_nodes.borrow_mut().remove(&key).is_some() {
cut_key(h, key);
}
return;
};
let changed = match h.dom.point_nodes.borrow_mut().insert(key, node.clone()) {
Some(old) => !Arc::ptr_eq(&old, &node) && old.path_data().map(|pd| &pd.subpaths) != node.path_data().map(|pd| &pd.subpaths),
None => false,
};
if changed && !own() {
cut_key(h, key);
}
}
/// [`see_points`] for each path whose points the run has read, after each command, so that a
/// change that a later command reverses still makes the points stale. Paths under the object that
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid. A document that is the one the run last looked
/// at is skipped, as are its paths.
pub(super) fn see_all_points(h: &super::Host) {
let keys: Vec<(u64, u64)> = {
let seen = h.dom.point_nodes.borrow();
if seen.is_empty() {
return;
}
let s = h.session.borrow();
let mut docs = h.dom.point_docs.borrow_mut();
// The documents that changed since the last look, kept as they are now.
let mut changed = std::collections::HashSet::new();
for (uid, _) in seen.keys() {
if changed.contains(uid) {
continue;
}
match s.documents().iter().find(|d| d.uid == *uid) {
Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => {}
Some(st) => {
docs.insert(*uid, st.doc.clone());
changed.insert(*uid);
}
None => {
docs.remove(uid);
changed.insert(*uid);
}
}
}
seen.keys().copied().filter(|(uid, _)| changed.contains(uid)).collect()
};
let editing = h.dom.editing.get();
for (uid, id) in keys {
let own = || match editing {
Some(e) if e.doc.uid == uid => {
let s = h.session.borrow();
let id = NodeId(id);
id == e.id || s.documents().iter().find(|d| d.uid == uid).and_then(|st| st.doc.ancestry(id)).is_some_and(|a| a.contains(&e.id))
}
_ => false,
};
see_points(h, (uid, id), own);
}
}
fn points_at(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
+3
View File
@@ -1350,6 +1350,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
return Err(HostError::Abort(HISTORY_LOST.to_string()));
}
}
if crossed.is_ok() {
dom::see_points(host);
}
crossed.map(|data| (data, value))
}
@@ -284,6 +284,44 @@ fn points_read_before_a_removal_or_replacement_go_stale() {
);
}
#[test]
fn points_read_before_a_command_changes_the_path_go_stale() {
let (mut s, a, _) = doc();
let source = format!(
"function A(x, y) {{ return {{x: x, y: y, in: [x, y], out: [x, y], smooth: false}}; }}\
var p = app.activeDocument.pathItems[0], id = {id}, first = p.pathPoints[1];\
vc.run('path.setAnchors', {{id: id, subpaths: [{{anchors: [A(0, 0), A(20, 0), A(20, 20), A(0, 20)], closed: true}}]}});\
try {{ first.anchor = [1, 1]; }} catch (e) {{ vc.log(e.message); }} try {{ first.anchor; }} catch (e) {{ vc.log(e.message); }}\
var second = p.pathPoints[1]; vc.log(second.anchor);\
vc.run('stroke.set', {{ids: [id], weight: 3}}); vc.log(second.anchor);\
p.translate(5, 0); vc.log(second.anchor);\
vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); try {{ second.anchor; }} catch (e) {{ vc.log(e.message); }}\
var third = p.pathPoints[1]; vc.log(third.anchor);\
vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); vc.run('edit.undo');\
try {{ third.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);\
var fourth = p.pathPoints[1]; vc.run('edit.clear', {{ids: [id]}}); vc.run('edit.undo');\
try {{ fourth.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);",
id = a.0
);
let out = log(&mut s, &source);
assert_eq!(
out,
vec![
json!("Stale path point"),
json!("Stale path point"),
json!([20, 300]),
json!([20, 300]),
json!([25, 300]),
json!("Stale path point"),
json!([30, 300]),
json!("Stale path point"),
json!(4),
json!("Stale path point"),
json!(4)
]
);
}
#[test]
fn fill_color_round_trips_rgb_cmyk_gray_lab() {
let (mut s, a, _) = doc();
+4 -1
View File
@@ -2716,7 +2716,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot
points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and
`pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point
whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed
a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`). Color components left out
a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`), or before anything other
than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`,
`object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an
object that holds it, such as `translate()`. Color components left out
count as 0, `new
cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of
range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest