diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2ef5503fb0..4bfaa33968 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1570,6 +1570,15 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } +/// The answer of an indexer called with a name, from `found`, the collection's `getByName`: a +/// name nothing has gives `undefined` for `name in collection` ([`probing`]) and throws otherwise. +fn by_name_or_probe(a: &[Data], found: Answer) -> Answer { + match found { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + } +} + /// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. fn items_at(h: &Host, a: &[Data]) -> Answer { if layers::is_scoped(a) { @@ -1577,10 +1586,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { } let doc = items_doc(h, a)?; if let Data::String(_) = arg(a, 1) { - return match items_by_name(h, a) { - Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), - r => r, - }; + return by_name_or_probe(a, items_by_name(h, a)); } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index ed88917fd9..121c9a339f 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -537,8 +537,12 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("Layers")) } +/// `layers[i]`, and `layers["name"]` as `getByName` reads it. fn layers_at(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; + if let Data::String(_) = arg(a, 1) { + return super::by_name_or_probe(a, layers_by_name(h, a)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) @@ -689,8 +693,12 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer { Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } +/// `collection[i]`, and `collection["name"]` as `getByName` reads it. fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + if let Data::String(_) = arg(a, 1) { + return super::by_name_or_probe(a, art_by_name(h, a, kind)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) @@ -826,15 +834,20 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer { } /// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the -/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. -/// → the new object. +/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. A +/// Live Paint group takes none. → the new object. fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; if let Some(c) = c { - let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let (compound, live) = with_doc(h, doc, |_, st| { + (st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })), super::paths::is_live_paint_group(st, c)) + }); if compound { return Err(HostError::Error("a compound path holds only paths".into())); } + if live { + return Err(HostError::Error(super::paths::LIVE_PAINT_CONTAINER.into())); + } } let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); if kind == Kind::Compound @@ -1232,8 +1245,12 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result { .ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1)))) } +/// `artboards[i]`, and `artboards["name"]` as `getByName` reads it. fn boards_at(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return super::by_name_or_probe(a, boards_by_name(h, a)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id)))) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ffe1a23264..c4fb82be2f 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -462,8 +462,12 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { }) } +/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { let (doc, c) = items_scope(h, a)?; + if let Data::String(_) = arg(a, 1) { + return super::by_name_or_probe(a, items_by_name(h, a)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) @@ -493,6 +497,8 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or /// locked path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// A compound path's `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its +/// last path does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let (doc, c) = items_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { @@ -505,7 +511,8 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": c.is_some()}); + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?; } Ok(Data::Undefined) } @@ -520,22 +527,35 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { /// locked layer or group. pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group"; +/// The error of an object made in a Live Paint group, which would join the group's paths instead +/// of staying in the group's own list. +pub const LIVE_PAINT_CONTAINER: &str = "Cannot add an object to a Live Paint group"; + +/// Whether `id` is a Live Paint group, which takes no new objects from the object model. +pub(super) fn is_live_paint_group(st: &DocState, id: NodeId) -> bool { + st.doc.node(id).is_some_and(vectorcraft_tools::builder::is_live_paint) +} + /// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the /// selection and the current layer kept. With a layer or group `container`, the container's layer /// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made /// outside the container then moves on top of its contents in the same step; a container that is /// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`] -/// before anything is made. → the new path. +/// before anything is made, and a Live Paint group throws [`LIVE_PAINT_CONTAINER`]. → the new path. fn make_in( h: &super::Host, doc: Doc, container: Option, make: impl FnOnce(&super::Host) -> std::result::Result, ) -> Answer { - if let Some(c) = container - && !with_doc(h, doc, |_, st| editable(&st.doc, c)) - { - return Err(HostError::Error(CONTAINER_LOCKED.into())); + if let Some(c) = container { + let (open, live) = with_doc(h, doc, |_, st| (editable(&st.doc, c), is_live_paint_group(st, c))); + if !open { + return Err(HostError::Error(CONTAINER_LOCKED.into())); + } + if live { + return Err(HostError::Error(LIVE_PAINT_CONTAINER.into())); + } } let made = match container { // Making a path can take more than one command (a stroke, a reversal): a failure of a later @@ -1314,11 +1334,13 @@ fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc> { /// 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. +/// makes a new node. The first look at a path of a document also keeps the document as it is then, +/// when no look kept it before ([`see_all_points`]). fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { - let node = { + let (node, doc) = { 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()) + let st = s.documents().iter().find(|d| d.uid == key.0); + (st.and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()), st.map(|st| st.doc.clone())) }; // A path that is gone makes its points stale, so that an undo that brings it back leaves them // stale. @@ -1328,9 +1350,15 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { } return; }; - let changed = match h.dom.point_nodes.borrow_mut().insert(key, node.clone()) { + let old = h.dom.point_nodes.borrow_mut().insert(key, node.clone()); + let changed = match old { Some(old) => !Arc::ptr_eq(&old, &node) && old.path_data().map(|pd| &pd.subpaths) != node.path_data().map(|pd| &pd.subpaths), - None => false, + None => { + if let Some(doc) = doc { + h.dom.point_docs.borrow_mut().entry(key.0).or_insert(doc); + } + false + } }; if changed && !own() { cut_key(h, key); @@ -1338,52 +1366,106 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { } /// [`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. +/// change that a later command reverses still makes the points stale. Only the paths of documents +/// that changed since the last look are looked at, and of those only the paths in the parts of the +/// document that changed ([`changed_ids`]), so an edit of one path does not look at every other +/// path the run read. 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. 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; - } + if h.dom.point_nodes.borrow().is_empty() { + return; + } + // The documents that changed since the last look, as they were then (`None`: gone, or not + // kept), kept as they are now. + type Kept = Option>; + let changed: Vec<(u64, Kept, Kept)> = { 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; + let mut changed = Vec::new(); + h.dom.point_docs.borrow_mut().retain(|uid, kept| match s.documents().iter().find(|d| d.uid == *uid) { + Some(st) if Arc::ptr_eq(kept, &st.doc) => true, + Some(st) => { + changed.push((*uid, Some(std::mem::replace(kept, st.doc.clone())), Some(st.doc.clone()))); + true } - 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); - } + None => { + changed.push((*uid, None, None)); + false } - } - seen.keys().copied().filter(|(uid, _)| changed.contains(uid)).collect() + }); + changed }; 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)) + for (uid, was, now) in changed { + let keys: Vec<(u64, u64)> = { + let seen = h.dom.point_nodes.borrow(); + match (&was, &now) { + (Some(was), Some(now)) => changed_ids(was, now).into_iter().map(|id| (uid, id.0)).filter(|k| seen.contains_key(k)).collect(), + _ => seen.keys().copied().filter(|(u, _)| *u == uid).collect(), } - _ => false, }; - see_points(h, (uid, id), own); + if keys.is_empty() { + continue; + } + // The objects under the one the object model is changing, as it is now. + let mut inside = std::collections::HashSet::new(); + if let (Some(e), Some(now)) = (editing, &now) + && e.doc.uid == uid + && let Some(n) = node_arc(now, e.id) + { + let mut stack = vec![n]; + while let Some(n) = stack.pop() { + inside.insert(n.id); + stack.extend(n.children().map_or(&[][..], Vec::as_slice)); + } + } + for key in keys { + see_points(h, key, || inside.contains(&NodeId(key.1))); + } } } +/// The ids of the objects that differ between `was` and `now`, two versions of a document that +/// share the objects they have in common: each object that is not the same object in both, and +/// everything in it. Lists that keep their objects in place are compared object by object, and +/// the rest by the part between the objects they start and end with in common. +fn changed_ids(was: &crate::Document, now: &crate::Document) -> Vec { + type Nodes<'a> = &'a [Arc]; + fn all(nodes: Nodes<'_>, out: &mut Vec) { + let mut stack: Vec<&Arc> = nodes.iter().collect(); + while let Some(n) = stack.pop() { + out.push(n.id); + stack.extend(n.children().map_or(&[][..], Vec::as_slice)); + } + } + let mut out = Vec::new(); + let mut work: Vec<(Nodes<'_>, Nodes<'_>)> = vec![(&was.layers, &now.layers)]; + while let Some((a, b)) = work.pop() { + let start = a.iter().zip(b).take_while(|(x, y)| Arc::ptr_eq(x, y)).count(); + let end = a[start..].iter().rev().zip(b[start..].iter().rev()).take_while(|(x, y)| Arc::ptr_eq(x, y)).count(); + let (a, b) = (&a[start..a.len() - end], &b[start..b.len() - end]); + if a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.id == y.id) { + for (x, y) in a.iter().zip(b) { + if Arc::ptr_eq(x, y) { + continue; + } + out.push(y.id); + match (x.children(), y.children()) { + (Some(xc), Some(yc)) => work.push((xc, yc)), + (xc, yc) => { + all(xc.map_or(&[][..], Vec::as_slice), &mut out); + all(yc.map_or(&[][..], Vec::as_slice), &mut out); + } + } + } + } else { + all(a, &mut out); + all(b, &mut out); + } + } + out +} + 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) }; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9c372156a1..7b8ee73568 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2252,14 +2252,24 @@ impl Session { self.script_key = Some(key); None } - // The point changes written as the script ended went past the growth allowance. - Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => { - job.finished = true; - JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); - self.script_key = Some(key); - None + Ok(Ok(Progress::Done(_))) => { + // What the script added must fit the allowance the last answer gave, which one + // answer can leave short of what the script had already added. + if !job.host.waiting.get() + && let Err(e) = job.host.charge_growth(0, 0) + { + return Some(self.script_failed(job, &end_flush_error(e))); + } + // The point changes written as the script ended, or what it added before, went past + // the growth allowance. + if job.host.waiting.get() { + job.finished = true; + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + return None; + } + Some(self.script_ended(job)) } - Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)), } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 09c856dbcf..de4dacfb62 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1870,6 +1870,66 @@ fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { assert!(msg.contains("Stale page item"), "{msg}"); } +/// A collection read with a name gives what its `getByName` gives, in a layer's or a group's +/// collections as in the document's, and a name nothing has is not `in` it. +#[test] +fn collections_read_with_a_name_give_the_named_object() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.groupItems[0], r = g.pageItems[0]; r.name = 'Logo'; g.name = 'G';\ + vc.log([g.pageItems['Logo'] === r, g.pathItems['Logo'] === r, d.pathItems['Logo'] === r, d.groupItems['G'] === g,\ + d.layers[0].groupItems['G'] === g, d.layers['Layer 1'] === d.layers[0], d.artboards[d.artboards[0].name] === d.artboards[0]]);\ + vc.log(['Logo' in g.pageItems, 'missing' in g.pageItems, 'missing' in g.pathItems, 'missing' in d.layers, 'missing' in d.artboards]);\ + var m = ''; try { g.pageItems['missing']; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out[0], json!([true, true, true, true, true, true, true]), "{out:?}"); + assert_eq!(out[1], json!([true, false, false, false, false]), "{out:?}"); + assert_eq!(out[2], json!("Not found"), "{out:?}"); +} + +/// A compound path's `pathItems.removeAll()` leaves it, empty, as `remove()` of its last path +/// does. +#[test] +fn clearing_the_paths_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let out = log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length]);"); + assert_eq!(out, vec![json!(["CompoundPathItem", 0])]); + let d = &s.active().unwrap().doc; + assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); +} + +/// A Live Paint group's collections make nothing in it: what they made would join the group's +/// paths instead of being one of its objects. +#[test] +fn collections_of_a_live_paint_group_make_nothing() { + const REFUSED: &str = "Cannot add an object to a Live Paint group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], m = [];\ + try { g.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\ + try { g.pathItems.add(); } catch (e) { m.push(e.message); }\ + try { g.groupItems.add(); } catch (e) { m.push(e.message); }\ + try { g.compoundPathItems.add(); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(refused.len(), 4, "{out:?}"); + assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + #[test] fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 2a4e67e7fc..6845a10123 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -1423,6 +1423,39 @@ fn a_finished_run_past_its_last_allowance_asks_again() { assert_eq!(questions, 3, "asked mid-run, as the script ended, and again for the third allowance"); } +/// A script that ends with nothing left to write, past the allowance the person's last answer +/// gave, is asked again before its changes are kept. +#[test] +fn a_run_that_ends_past_its_last_allowance_with_nothing_to_write_asks_again() { + TEST_GROWTH.with(|g| g.set(Some(20))); + // 21 rectangles go past the first allowance, and the 45 the document opens go past the + // second and stay within twice it, which leaves them past the third. + let rects: String = (0..45).map(|i| format!(r#""#)).collect(); + let svg = format!(r#"{rects}"#); + let data = vectorcraft_format::base64_encode(svg.as_bytes()); + let source = format!( + "for (var i = 0; i < 21; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\ + vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}});" + ); + let mut s = two_docs(); + s.script_frames = true; + run(&mut s, &source).unwrap(); + let mut questions = 0; + let done = loop { + assert!(questions < 10); + if s.script_waiting() { + questions += 1; + s.script_continue(); + } + if let Some(r) = s.script_pump() { + break r; + } + }; + TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(questions, 3, "asked for the rectangles, for the document, and again as the script ended"); +} + #[test] fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { TEST_GROWTH.with(|g| g.set(Some(20))); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index dcd9e4a695..3313299073 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -189,10 +189,13 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(crate::heap::host_handle_bytes(handle.len())))?; + let handle_bytes = crate::heap::host_handle_bytes(handle.len()); + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(handle_bytes))?; let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); + // The heap counts the object; its handle is counted here, as a collection counts it. + self.heap.bytes = self.heap.bytes.saturating_add(handle_bytes); self.host_objects.insert(made, id); Ok(Value::Object(id)) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 2e72ea124f..17ee28d49e 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -698,6 +698,20 @@ fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() { assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap)); } +/// A new object of a host class adds its handle to the heap's total as well as itself, so objects +/// made one after another count each other's handles before a collection does. +#[test] +fn an_object_of_a_host_class_counts_its_handle_toward_the_heap() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + let interp = r.interp(); + let handle: Vec = (0..64).map(f64::from).collect(); + let before = interp.heap.bytes; + interp.write_host_ref(&host_ref("Thing", &handle)).unwrap(); + let added = interp.heap.bytes - before; + assert!(added >= crate::heap::OBJECT_BYTES + crate::heap::host_handle_bytes(handle.len()), "{added}"); +} + #[test] fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { let mut r = realm(1_000_000); diff --git a/docs/mcp.md b/docs/mcp.md index b64bddc9cd..bab3a91147 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2779,7 +2779,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot object that is hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds - it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). An object with nothing in it, such + it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). The compound path's + `pathItems.removeAll()` also leaves it, empty. An object with nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws @@ -2896,8 +2897,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because - artboards were inserted, removed or reordered before it. An index outside the list throws a - `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws + artboards were inserted, removed or reordered before it. `insert`, `remove` and `setActiveArtboardIndex` throw a + `RangeError` for an index outside the list. Reading an index past the last artboard gives `undefined` from + `artboards[i]` and throws `Not found` from `artboards.index(i)`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` and `GroupItems.createFromFile` throw an error that says they are not available yet. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; @@ -2927,7 +2929,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot run's one undo step. VectorCraft's own rules: a layer's or group's `pathItems` list the paths directly in it, topmost first, leaving out paths in its groups, compound paths and sublayers; a layer or group that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot add a path to a hidden or locked layer or - group` and no path is made. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + group` and no path is made. A Live Paint group's `pathItems`, `groupItems` and `compoundPathItems` throw + `Cannot add an object to a Live Paint group` from their `add()` and the shape methods, and nothing is made. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`,