diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs
index fb26b13c68..0a5ed93ba3 100644
--- a/crates/engine/src/cmd/newdoc.rs
+++ b/crates/engine/src/cmd/newdoc.rs
@@ -394,9 +394,8 @@ impl DocSettings {
if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn {
self.rows = 0;
}
- if self.grid_rows().is_some() {
- self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
- }
+ // While rows are set, `grid_columns` gives the columns they make; the stored columns stay as
+ // they were given, and are the ones a later layout without rows uses.
Ok(())
}
diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs
index 6fda66efe1..0753cc5263 100644
--- a/crates/engine/src/script/dom.rs
+++ b/crates/engine/src/script/dom.rs
@@ -6,9 +6,10 @@
//! describe them.
//!
//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the
-//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the
-//! document and the object up again. An object that was deleted, a document that was closed and an
-//! object from an earlier run of a named engine throw an error on every member. Every change runs
+//! document's [`crate::DocState::uid`] and, for art and layers, the document's
+//! [`crate::DocState::reverts`] and the object's id, and every read looks the document and the
+//! object up again. An object that was deleted, a document that was closed, an object from before
+//! File › Revert and an object from an earlier run of a named engine throw an error on every member. Every change runs
//! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each
//! changed document; a change that changes nothing runs no command. A change to a document that is
//! not the active one makes it active for the command and makes the other one active again after.
@@ -24,7 +25,9 @@
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
//! - `app.activeDocument` with no document open throws `No active document`.
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
-//! must be one of that document's that can be selected, or nothing changes.
+//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
+//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
+//! in the object.
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
//! leaves them out.
//! - `reflect` on an object or a class gives each member's type from the declaration that installs
@@ -33,6 +36,7 @@
//! more than one type.
use std::cell::{Cell, RefCell};
+use std::collections::HashSet;
use std::rc::Rc;
use std::sync::Arc;
@@ -93,16 +97,24 @@ 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, whether a call's own savepoint
-/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made.
+/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made, with the size
+/// of the values they hold now and the most they may hold: the run's heap.
#[derive(Default)]
pub(super) struct State {
coords: Cell,
items: RefCell>,
saving: Cell,
presets: RefCell>>,
+ preset_bytes: Cell,
+ preset_limit: u64,
}
impl State {
+ /// The state of a run whose heap is `heap_bytes`.
+ pub(super) fn new(heap_bytes: usize) -> Self {
+ Self { preset_limit: heap_bytes as u64, ..Self::default() }
+ }
+
/// Whether a call's own savepoint is open: its commands take none of their own.
pub(super) fn saving(&self) -> bool {
self.saving.get()
@@ -111,20 +123,25 @@ impl State {
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
/// document, the selection and the undo histories are as they were before it, with no undo step
-/// and no change to the document's saved state.
+/// and no change to the document's saved state, and the growth its commands were charged is not
+/// counted.
fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result {
if h.dom.saving.get() {
return f(h);
}
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
+ let mark = h.growth_mark();
h.dom.saving.set(true);
let r = f(h);
h.dom.saving.set(false);
let mut s = h.session.borrow_mut();
if r.is_ok() {
save.keep(&mut s);
- } else if !save.restore(&mut s) {
- return Err(HostError::Abort(HISTORY_LOST.to_string()));
+ } else {
+ h.put_growth_back(mark);
+ if !save.restore(&mut s) {
+ return Err(HostError::Abort(HISTORY_LOST.to_string()));
+ }
}
r
}
@@ -304,11 +321,17 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result bool {
+ whole(reverts) != Some(with_doc(h, doc, |_, st| st.reverts))
+}
+
/// The page item `d` names, which must still be in its document.
fn item_of(h: &Host, d: &Data) -> std::result::Result- {
let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) };
- let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) };
- let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
+ let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) };
+ let doc = find_doc(h, *run, *uid).filter(|doc| !reverted_since(h, *doc, *reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let s = h.session.borrow();
let st = &s.documents()[doc.index];
@@ -346,8 +369,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data {
fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
match st.doc.node(id) {
Some(n) => match typename(n) {
- Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]),
- None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]),
+ Some(t) => host_ref(t, &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]),
+ None => host_ref("Layer", &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]),
},
None => Data::Null,
}
@@ -509,6 +532,8 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
.map(|i| {
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
+ // A path with only segments selected gets them back below, with no anchors.
+ None if before.segments.contains_key(i) => Vec::new(),
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
};
json!({"id": i.0, "anchors": anchors})
@@ -963,17 +988,30 @@ fn new_preset(h: &Host) -> Answer {
return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets")));
}
let item = |k: &str, v: Data| (k.to_string(), v);
- presets.push(vec![
+ let fields = vec![
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
item("artboardRowsOrCols", num(1.0)),
item("artboardSpacing", num(20.0)),
item("height", num(792.0)),
item("numArtboards", num(1.0)),
item("width", num(612.0)),
- ]);
+ ];
+ hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| data_size(v)).sum())?;
+ presets.push(fields);
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
}
+/// Counts that the run's presets now hold `added` bytes of values in place of `replaced`, and
+/// refuses when they would hold more than the run's heap.
+fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result<(), HostError> {
+ let total = h.dom.preset_bytes.get().saturating_sub(replaced).saturating_add(added);
+ if total > h.dom.preset_limit {
+ return Err(HostError::Range(format!("the DocumentPreset settings would hold more than {} bytes", h.dom.preset_limit)));
+ }
+ h.dom.preset_bytes.set(total);
+ Ok(())
+}
+
/// The most `DocumentPreset` objects one run can make.
const MAX_PRESETS: usize = 10_000;
@@ -1026,8 +1064,12 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
let mut presets = h.dom.presets.borrow_mut();
let fields = &mut presets[i];
- match fields.iter_mut().find(|(k, _)| k == key) {
- Some((_, v)) => *v = value,
+ // The values the presets hold now count against the run's heap: a value assigned again
+ // replaces the one before it.
+ let at = fields.iter().position(|(k, _)| k == key);
+ hold_preset_bytes(&h, at.map_or(0, |n| data_size(&fields[n].1)), data_size(&value))?;
+ match at {
+ Some(n) => fields[n].1 = value,
None => fields.push((key.to_string(), value)),
}
Ok(Data::Undefined)
@@ -1157,28 +1199,33 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
}
/// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or
-/// `[]`. Every one must be an object of that document that can be selected.
+/// `[]`. Every one must be an object of that document that can be selected. `undefined`, such as
+/// an index past the end of `pageItems`, is refused and clears nothing.
fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result
, HostError> {
let list: Vec<&Data> = match v {
- Data::Null | Data::Undefined => Vec::new(),
+ Data::Null => Vec::new(),
+ Data::Undefined => return Err(HostError::Type("a selection is a page item, a list of them, null or []".into())),
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))),
Data::Array(a) => a.iter().collect(),
d => vec![d],
};
- let mut ids: Vec = Vec::with_capacity(list.len());
- for d in list {
- let item = item_of(h, d)?;
- let ok = item.doc.uid == doc.uid
- && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id));
- if !ok {
- let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
- return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
+ // The locked artboards are found once for the whole list, and repeated objects are kept once.
+ with_doc(h, doc, |_, st| {
+ let locks = st.doc.locked_artboards();
+ let mut seen: HashSet = HashSet::with_capacity(list.len());
+ let mut ids: Vec = Vec::with_capacity(list.len());
+ for d in list {
+ let item = item_of(h, d)?;
+ if item.doc.uid != doc.uid || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, item.id) {
+ let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
+ return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
+ }
+ if seen.insert(item.id) {
+ ids.push(item.id);
+ }
}
- if !ids.contains(&item.id) {
- ids.push(item.id);
- }
- }
- Ok(ids)
+ Ok(ids)
+ })
}
fn doc_set_selection(h: &Host, a: &[Data]) -> Answer {
@@ -1440,6 +1487,25 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
bounds(h, a, true)
}
+/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in
+/// the object.
+fn item_control(h: &Host, a: &[Data]) -> Answer {
+ let item = this_item(h, a)?;
+ let (r, f) = item_rect(h, item, true)?;
+ let r = with_doc(h, item.doc, |_, st| {
+ let mut r = r;
+ if let Some(n) = st.doc.node(item.id) {
+ n.walk(&mut |c| {
+ if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) {
+ r = r.union(handles);
+ }
+ });
+ }
+ r
+ });
+ Ok(f.bounds(h.dom.coords.get(), r))
+}
+
fn item_position(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, false)?;
@@ -1611,13 +1677,13 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
let how = placement_of(how)?;
let beside = matches!(how, Placement::Above | Placement::Below);
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
- let Some(&[run, uid, high, low]) = handle.as_deref() else {
+ let Some(&[run, uid, reverts, high, low]) = handle.as_deref() else {
if handle_of(target, "Document").is_some() {
return Err(HostError::Error("a document as the relative object is not available yet".into()));
}
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
};
- let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
+ let doc = find_doc(h, run, uid).filter(|doc| !reverted_since(h, *doc, reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if doc.uid != item.doc.uid {
return Err(HostError::Error(CROSS_DOCUMENT.into()));
}
@@ -1771,8 +1837,11 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
fn layer_name(h: &Host, a: &[Data]) -> Answer {
let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) };
- let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
+ let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
+ if reverted_since(h, doc, *reverts) {
+ return Err(HostError::Error(STALE_ITEM.into()));
+ }
let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX));
with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into())))
}
@@ -1962,7 +2031,7 @@ fn classes(link: &Link) -> Vec {
("height", property(l, item_height, item_set_height), typed("number")),
("geometricBounds", get(l, item_geometric), typed("Array")),
("visibleBounds", get(l, item_visible), typed("Array")),
- ("controlBounds", get(l, item_visible), typed("Array")),
+ ("controlBounds", get(l, item_control), typed("Array")),
("editable", get(l, item_editable), typed("boolean")),
("zOrderPosition", get(l, item_z_order_position), typed("number")),
("duplicate", method(l, item_duplicate), returns("PageItem", &placement)),
diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs
index d228ff848f..8e79b7bdda 100644
--- a/crates/engine/src/script/mod.rs
+++ b/crates/engine/src/script/mod.rs
@@ -1076,6 +1076,20 @@ impl Host {
self.pause.set(true);
Ok(())
}
+
+ /// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about
+ /// it, for [`Host::put_growth_back`].
+ fn growth_mark(&self) -> (u64, u64, bool) {
+ (self.objects.get(), self.bytes_kept.get(), self.waiting.get())
+ }
+
+ /// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added
+ /// it were put back.
+ fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) {
+ self.objects.set(objects);
+ self.bytes_kept.set(bytes);
+ self.waiting.set(waiting);
+ }
}
/// A run in progress.
@@ -1309,16 +1323,14 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> {
- let id = id.to_string();
- let params = params.clone();
let session = host.session.clone();
let started = clock();
let r = {
let mut s = session.borrow_mut();
- step(&mut s, host, &id, ¶ms)
+ step(&mut s, host, id, params)
};
// Only commands that exist are timed, so the table holds at most one row per command.
- if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
+ if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
let nanos = started.elapsed().as_nanos();
let mut times = host.commands.borrow_mut();
let row = times.entry(spec.id).or_insert((0, 0, 0));
@@ -1331,13 +1343,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())),
Err(e) => return Err(HostError::Error(e.to_string())),
};
+ let mark = host.growth_mark();
let crossed = host.charge_growth(objects, added).and_then(|()| {
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
host.charge_call(data_size(&data))?;
Ok(data)
});
- // A command whose result does not reach the script is put back, like one that failed.
+ // A command whose result does not reach the script is put back, like one that failed, and so is
+ // the growth it was charged.
+ if crossed.is_err() {
+ host.put_growth_back(mark);
+ }
if let Some(save) = save {
let mut s = session.borrow_mut();
if crossed.is_ok() {
@@ -2064,7 +2081,7 @@ impl Session {
eval_strict: Cell::new(None),
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
- dom: dom::State::default(),
+ dom: dom::State::new(heap_bytes),
});
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs
index 26632b7055..d0cb4e7ecd 100644
--- a/crates/engine/src/tests/script_dom.rs
+++ b/crates/engine/src/tests/script_dom.rs
@@ -229,6 +229,41 @@ fn selection_assignment_is_atomic_across_invalid_items() {
assert!(e.contains("Cannot select"), "{e}");
}
+/// An index past the end of `pageItems` gives `undefined`, which does not clear the selection;
+/// `null` and `[]` do.
+#[test]
+fn assigning_undefined_to_the_selection_throws_and_keeps_it() {
+ let (mut s, a, _) = doc();
+ s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
+ let caught = "var d = app.activeDocument, m = '';\
+ try { d.selection = d.pageItems[99]; } catch (e) { m = e.name; }\
+ vc.log(m); vc.log(d.selection.length);";
+ assert_eq!(log(&mut s, caught), vec![json!("TypeError"), json!(1)]);
+ assert_eq!(s.active().unwrap().selection.objects, vec![a]);
+ for clear in ["null", "[]"] {
+ s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
+ log(&mut s, &format!("app.activeDocument.selection = {clear};"));
+ assert!(s.active().unwrap().selection.objects.is_empty(), "{clear}");
+ }
+}
+
+/// `controlBounds` takes in a direction point that lies past the curve; `visibleBounds` does not.
+#[test]
+fn control_bounds_take_in_direction_points_past_the_curve() {
+ let (mut s, _, _) = doc();
+ s.execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})).unwrap();
+ let out = log(
+ &mut s,
+ "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.pageItems;\
+ vc.log(p[2].controlBounds); vc.log(p[2].visibleBounds); vc.log(p[0].controlBounds); vc.log(p[0].visibleBounds);",
+ );
+ let top = |v: &Value| v[1].as_f64().unwrap();
+ assert!((top(&out[0]) + 100.0).abs() < 1e-9, "{out:?}");
+ assert!(top(&out[1]) > -90.0, "{out:?}");
+ // A rectangle's direction points lie on its edges.
+ assert_eq!(out[2], out[3]);
+}
+
#[test]
fn an_inactive_document_changes_without_switching_tabs() {
let (mut s, a, _) = doc();
@@ -364,6 +399,17 @@ fn a_copy_that_cannot_be_placed_is_deleted() {
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
// The refused copy leaves no undo step and does not change the document's step.
assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step));
+ // Nor does it count toward the run's growth allowance: many refused copies stay within one
+ // that a few kept copies would pass.
+ crate::script::TEST_GROWTH.with(|g| g.set(Some(5)));
+ let r = run(
+ &mut s,
+ "var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], refused = 0;\
+ for (var k = 0; k < 20; k++) { try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { refused++; } }\
+ vc.log(refused);",
+ );
+ crate::script::TEST_GROWTH.with(|g| g.set(None));
+ assert_eq!(r.unwrap()["log"], json!([20]));
}
#[test]
@@ -482,6 +528,14 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap();
assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}");
}
+ // A change of spacing alone leaves the stored columns as they are, so leaving the rows later
+ // gives the same grid with or without it.
+ let to_row = json!({"artboardLayout": {"layout": "gridByRow"}});
+ let plain = stored.clone().with_params(&json!({"artboards": 9}), "file.new").unwrap();
+ let spaced = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": {"spacing": 20}}), "file.new").unwrap();
+ assert_eq!((plain.grid_columns(), spaced.grid_columns()), (3, 3));
+ let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
+ assert_eq!(plain.grid_columns(), spaced.grid_columns());
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
assert!(e.contains("rows must be 1 or more"), "{e}");
for layout in ["gridByRow", "row", "column"] {
@@ -549,6 +603,26 @@ fn an_edit_keeps_the_order_of_a_mixed_selection() {
assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors));
}
+/// A path with segments selected and no anchors gets the segments back, not every anchor.
+#[test]
+fn an_edit_keeps_a_path_with_only_a_segment_selected() {
+ let (mut s, a, b) = doc();
+ rect(&mut s, 200.0, 200.0, 20.0, 20.0);
+ s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
+ s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap();
+ s.doc_mut().unwrap().selection.anchors.remove(&b);
+ let before = s.active().unwrap().selection.clone();
+ log(&mut s, "app.activeDocument.pageItems[2].duplicate();");
+ let sel = &s.active().unwrap().selection;
+ assert_eq!((&sel.objects, &sel.segments, sel.anchors.get(&a)), (&before.objects, &before.segments, before.anchors.get(&a)));
+ // The segment brings back its own two end points, as `select.segments` selects them, and none
+ // of the path's other anchors: the journaled restore selects none of them first.
+ assert_eq!(sel.anchors.get(&b).map(|k| k.len()), Some(2), "{sel:?}");
+ let restore = s.journal.iter().rev().find(|(id, _)| id == "select.anchorsMany").map(|(_, p)| p.clone()).unwrap();
+ let path = restore["items"].as_array().unwrap().iter().find(|i| i["id"] == json!(b.0)).cloned().unwrap();
+ assert_eq!(path["anchors"], json!([]), "{restore}");
+}
+
#[test]
fn assigning_the_selection_clears_a_layers_panel_target() {
let (mut s, a, _) = doc();
@@ -733,6 +807,28 @@ fn a_document_preset_is_an_instance_of_its_class() {
assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]);
}
+/// The values the presets hold count against the run's heap, a value assigned again in place of
+/// the one before it.
+#[test]
+fn document_preset_values_are_bounded_by_the_runs_heap() {
+ use crate::script::TEST_ENGINE_HEAP;
+ TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20)));
+ let mut s = Session::new();
+ let big = "var s = 'a'; while (s.length < (1 << 19)) s += s;";
+ let again =
+ format!("#targetengine presets\n{big} var p = new DocumentPreset(); for (var k = 0; k < 40; k++) p.title = s + k; vc.log(p.title.length);");
+ assert_eq!(log(&mut s, &again), vec![json!(524_290)]);
+ let many = format!(
+ "#targetengine presets\n{big} var m = '';\
+ try {{ for (var k = 0; k < 40; k++) {{ var p = new DocumentPreset(); p.title = s; }} }} catch (e) {{ m = e.name + ': ' + e.message; }}\
+ vc.log(k < 40); vc.log(m);"
+ );
+ let out = log(&mut s, &many);
+ TEST_ENGINE_HEAP.with(|h| h.set(None));
+ assert_eq!(out[0], json!(true), "{out:?}");
+ assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}");
+}
+
#[test]
fn the_same_document_or_item_is_the_same_object() {
let (mut s, a, _) = doc();
@@ -928,20 +1024,52 @@ fn wrappers_go_stale_after_delete_and_undo() {
assert!(e.contains("Stale page item"), "{e}");
}
+/// File › Revert loads objects with the ids they were saved with: an object or a layer read before
+/// the revert does not name the loaded one.
+#[test]
+fn wrappers_go_stale_after_revert() {
+ let (mut s, a, _) = doc();
+ let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("saved.vectorcraft");
+ s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
+ for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] {
+ let source = format!("var i = app.activeDocument.pageItems[0], l = i.parent; i.name = 'before'; vc.run('file.revert'); {read};");
+ let e = failure(&mut s, &source);
+ assert!(e.contains("Stale page item"), "{read}: {e}");
+ }
+ // Objects read after the revert are the loaded ones.
+ let out = log(
+ &mut s,
+ "var p = app.activeDocument.pageItems; p[0].name = 'before'; vc.run('file.revert');\
+ app.activeDocument.pageItems[0].name = 'loaded'; vc.log(app.activeDocument.pageItems.length);",
+ );
+ assert_eq!(out, vec![json!(2)]);
+ assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("loaded"));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
#[test]
fn remove_all_refuses_locked_art_before_deleting_anything() {
let (mut s, a, b) = doc();
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
- let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();");
- assert!(e.contains(&b.0.to_string()), "{e}");
- assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2);
+ // The script catches the error and finds both objects still there before the run ends, so the
+ // run's own rollback cannot hide a deletion.
+ let caught = "var p = app.activeDocument.pageItems, m = '';\
+ try { p.removeAll(); } catch (e) { m = e.message; }\
+ vc.log(m); vc.log(p.length);";
+ let out = log(&mut s, caught);
+ assert!(out[0].as_str().unwrap().contains(&b.0.to_string()), "{out:?}");
+ assert_eq!(out[1], json!(2));
+ assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some());
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
// A locked object inside an unlocked group stops it too.
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
- let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();");
- assert!(e.contains(&g.to_string()), "{e}");
+ let out = log(&mut s, caught);
+ assert!(out[0].as_str().unwrap().contains(&g.to_string()), "{out:?}");
+ assert_eq!(out[1], json!(3));
assert!(s.active().unwrap().doc.node(b).is_some());
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);");
@@ -1002,8 +1130,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() {
let (mut s, _, _) = doc();
let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id()));
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
- let p = path.to_string_lossy().replace('\\', "\\\\");
- let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));");
+ let p = path.to_string_lossy().to_string();
+ let (p, other) = (serde_json::to_string(&p).unwrap(), serde_json::to_string(&format!("{p}.other")).unwrap());
+ let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));");
let out = log(&mut s, &query);
assert_eq!(out, vec![json!(true), json!(false)]);
// Read roots that leave out the document's file: the same path does not count.
diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs
index 2af2fc130f..7380cc574c 100644
--- a/crates/js/src/host_classes.rs
+++ b/crates/js/src/host_classes.rs
@@ -349,6 +349,10 @@ fn reflected_members(class: &HostClass) -> Result, String> {
if out.iter().any(|r| *r.name == **name) {
return Err(format!("the host class {} names the member {name} twice", class.name));
}
+ // The prototype's `constructor` is the class's own constructor.
+ if name == "constructor" {
+ return Err(format!("the host class {} names a member constructor, which is the name of its constructor", class.name));
+ }
let access = match member {
HostMember::Get(_) => Access::ReadOnly,
HostMember::Property { .. } => Access::ReadWrite,
diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs
index a84c221d3a..0b6b7fffff 100644
--- a/crates/js/src/reflect.rs
+++ b/crates/js/src/reflect.rs
@@ -227,6 +227,7 @@ fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[I
let methods = info_array(interp, methods)?;
interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?;
let find = native(interp, "find", find, 1, NativeKind::Plain, false)?;
+ interp.object_mut(find)?.extensible = false;
interp.temp_roots.push(Value::Object(find));
let r = interp.new_object();
interp.temp_roots.push(Value::Object(r));
diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs
index 3e8827cf4f..e28247e162 100644
--- a/crates/js/src/reflect_tests.rs
+++ b/crates/js/src/reflect_tests.rs
@@ -112,13 +112,20 @@ fn a_reflection_cannot_be_changed() {
[typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()";
assert_eq!(text(&mut r, tries), "object,Object,number,1,,object");
// In strict mode each one throws a TypeError.
- for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] {
+ for write in
+ ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find", "x.find.extra = 1"]
+ {
assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}");
}
assert_eq!(
- text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"),
- "true true true"
+ text(
+ &mut r,
+ "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments) + ' ' + Object.isFrozen(x.find)"
+ ),
+ "true true true true"
);
+ // The frozen `find` still finds.
+ assert_eq!(text(&mut r, "x.find('a').name"), "a");
}
#[test]
@@ -239,4 +246,11 @@ fn info_for_a_member_a_class_does_not_have_is_refused() {
class.members.push(("size".into(), HostMember::Get(constant(1.0))));
let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err();
assert!(e.message.contains("names the member size twice"), "{}", e.message);
+ // `constructor` is the class's own constructor, so no member may take its name.
+ let mut r = realm();
+ let mut class = classes().remove(0);
+ class.members.push(("constructor".into(), HostMember::Get(constant(1.0))));
+ let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err();
+ assert!(e.message.contains("names a member constructor"), "{}", e.message);
+ assert_eq!(text(&mut r, "typeof Item"), "undefined");
}
diff --git a/docs/mcp.md b/docs/mcp.md
index eff8b953f8..8219fb3d83 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -2631,7 +2631,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot
`file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset
`file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()`
(https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset`
- starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and
+ starts with the defaults that page gives. The values a run's `DocumentPreset` objects hold together may not take
+ more than the run's heap; an assignment past that throws a `RangeError`, and a value assigned again replaces the
+ one before it in that count. A preset's `documentBleedLink`, `documentBleedOffsetRect` and
`transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when
the preset it is given holds one of them with a value other than `null`, and makes no document. A
`presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a
@@ -2648,7 +2650,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot
or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they
were), `opacity` (0 to
100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the
- visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`,
+ visible bounds, widened to take in the direction points of every path in the object), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`,
`move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`
(https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs
`edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same
@@ -2670,16 +2672,16 @@ app through the global object `vc`, and writes to the Script Console and runs ot
is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem`
for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each
changed document. A value that changes nothing runs no command, and a change to another document leaves the active
- tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine
- kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a
+ tab as it was. A bad value throws an error and changes nothing. An object that was deleted, that was read before
+ `file.revert` reloaded its document, or that a named engine kept from an earlier run, throws `Stale page item`. `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` and delete nothing. Setting `width` or `height` scales the object along
the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw
`Not found`; and
`app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item,
- a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with
- nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path,
+ a list of at most 10,000, `null` or `[]`; `undefined`, such as an index past the end of `pageItems`, throws a
+ `TypeError`, and an object that cannot be selected throws `Cannot select`, both with nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path,
letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when
the automation read roots allow its file, and that check can look the document's file up on disk. A path with
`..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application,