Merge feat/scripts-api-d1a-app-documents into feat/scripts-api-d7a-variables

# Conflicts:
#	crates/engine/src/script/dom.rs
This commit is contained in:
dotCooCoo committed 2026-11-22 12:03:26 -08:00
commit 1da34ab336
9 files changed
+258 -30

No files matched your search

+107 -16
View File
@@ -28,6 +28,7 @@
//! - Members the help pages list that are not here yet throw an error that says so.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
@@ -99,14 +100,16 @@ pub(super) enum Coords {
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
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, the settings of each `DocumentPreset` the run made, and the
/// `Variable` and `Dataset` objects it gave out.
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is
/// open, the settings of each `DocumentPreset` the run made, and the `Variable` and `Dataset`
/// objects it gave out.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
items: RefCell<Option<ItemList>>,
items: RefCell<Vec<ItemList>>,
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
presets: RefCell<Vec<Vec<(String, Data)>>>,
vars: variables::Handles,
@@ -142,6 +145,57 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
/// A document's uid, the document as it was, and the ids of its page items then.
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
/// How many documents' lists [`State`] keeps at once, of each kind.
const ITEM_LISTS: usize = 4;
/// The kept list of the document `uid` as `doc` is, if there is one.
fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc<Document>) -> Option<Rc<Vec<NodeId>>> {
lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone())
}
/// Keeps `list` in place of any earlier list of the same document, dropping the least recently
/// kept list beyond [`ITEM_LISTS`].
fn keep_items(lists: &mut Vec<ItemList>, list: ItemList) {
lists.retain(|(u, _, _)| *u != list.0);
if lists.len() >= ITEM_LISTS {
lists.remove(0);
}
lists.push(list);
}
/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each
/// object of a layer or sublayer is measured once while the document and its new art stay as they
/// are, so the members of a group are answered with one measurement of the group.
fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool {
if !st.doc.artboards.iter().any(|a| a.locked) {
return false;
}
let Some(object) = st.doc.layer_object(id).map(|n| n.id) else {
return false;
};
let new_art = st.doc.new_art.get();
let mut lists = h.dom.locked.borrow_mut();
let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) {
Some(at) => at,
None => {
lists.retain(|(u, ..)| *u != st.uid);
if lists.len() >= ITEM_LISTS {
lists.remove(0);
}
lists.push((st.uid, st.doc.clone(), new_art, HashMap::new()));
lists.len() - 1
}
};
match lists.get_mut(at) {
Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)),
None => st.doc.on_locked_artboard(object),
}
}
type Answer = std::result::Result<Data, HostError>;
/// A member function: the run's host and the call's arguments, `this` first.
@@ -349,13 +403,11 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
}
}
/// The ids of a document's page items in paint order ([`State`] keeps the last list).
/// The ids of a document's page items in paint order ([`State`] keeps the lists of the last
/// documents read).
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
if let Some((uid, doc, ids)) = &*h.dom.items.borrow()
&& *uid == st.uid
&& Arc::ptr_eq(doc, &st.doc)
{
return ids.clone();
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes {
@@ -373,7 +425,7 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
let mut ids = Vec::new();
walk(&st.doc.layers, &mut ids);
let ids = Rc::new(ids);
*h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone()));
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
ids
}
@@ -896,6 +948,9 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
None | Some(Data::Null) => Vec::new(),
Some(d) => {
let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?;
// The settings are charged as data passed to the call before they are copied.
let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::<u64>();
h.charge_call(bytes)?;
h.dom.presets.borrow()[i].clone()
}
};
@@ -1009,8 +1064,11 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
let l = link.clone();
let get: HostFunction = Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16)?;
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
// The value handed back is charged as the setter charges it, before it is copied.
let i = preset_of(&h, arg(&a, 0));
let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v)));
h.charge_call(16 + bytes)?;
let i = i.ok_or_else(not_preset)?;
let presets = h.dom.presets.borrow();
Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone()))
});
@@ -1391,7 +1449,13 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v}))
// A value the getter reports for the item's opacity sends the opacity it has, and
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
// replaces the one the graph keeps for its series or kind.
let item = this_item(h, a)?;
let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0));
let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v);
set_props(h, a, |_| false, json!({"opacity": v}))
}
fn item_selected(h: &Host, a: &[Data]) -> Answer {
@@ -1529,9 +1593,11 @@ fn item_set_height(h: &Host, a: &[Data]) -> Answer {
resize(h, a, false)
}
/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group,
/// or on a locked artboard.
fn item_editable(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id))))
Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id))))
}
/// The item's place in its parent's stacking order, from 1 at the bottom.
@@ -1964,4 +2030,29 @@ mod tests {
assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into())));
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
}
#[test]
fn page_item_lists_are_kept_for_several_documents() {
let docs: Vec<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
let ids = |n: u64| Rc::new(vec![NodeId(n)]);
let mut lists = Vec::new();
keep_items(&mut lists, (1, docs[0].clone(), ids(1)));
keep_items(&mut lists, (2, docs[1].clone(), ids(2)));
// Reading two documents in turn keeps both lists.
assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1)));
assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2)));
// A changed document has no kept list, and its new list replaces the old one.
let changed = Arc::new(Document::new(100.0, 100.0));
assert_eq!(kept_items(&lists, 1, &changed), None);
keep_items(&mut lists, (1, changed.clone(), ids(3)));
assert_eq!(lists.len(), 2);
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
// Past the limit, the list kept longest ago goes.
for (uid, d) in (10..).zip(&docs[2..]) {
keep_items(&mut lists, (uid, d.clone(), ids(uid)));
}
assert_eq!(lists.len(), ITEM_LISTS);
assert_eq!(kept_items(&lists, 2, &docs[1]), None);
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
}
}
+12 -1
View File
@@ -1046,7 +1046,7 @@ impl Host {
}
let bridge = self.bridge.get().saturating_add(bytes);
self.bridge.set(bridge);
if bridge > MAX_BRIDGE_BYTES {
if bridge > bridge_bytes() {
return Err(self.over(OVER_BRIDGE));
}
let n = self.calls_this_slice.get() + 1;
@@ -2511,6 +2511,15 @@ fn growth_objects() -> u64 {
GROWTH_OBJECTS
}
/// The data a run may pass to and from commands.
fn bridge_bytes() -> u64 {
#[cfg(test)]
if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) {
return n;
}
MAX_BRIDGE_BYTES
}
/// The limits of a command's result on its way to the script.
fn result_limits() -> DataLimits {
#[cfg(test)]
@@ -2528,6 +2537,8 @@ thread_local! {
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].