Merge main into feat/scripts-api-d5-swatches-symbols

This commit is contained in:
dotCooCoo committed 2026-11-30 21:05:57 -08:00
commit f31b19adfc
32 files changed
+1345 -281

No files matched your search

+91 -20
View File
@@ -657,10 +657,12 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
}
/// The ids of a document's page items, topmost first, each group or compound path before the
/// objects in it ([`State`] keeps the lists of the last documents read).
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
/// objects in it ([`State`] keeps the lists of the last documents read). Building the list again,
/// after an edit or for another document, counts against the run's host-call allowance as a list
/// of that many objects does ([`list_charge`]).
fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
return Ok(ids);
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes.iter().rev() {
@@ -678,9 +680,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
}
let mut ids = Vec::new();
walk(&st.doc.layers, &mut ids);
h.charge_call(list_charge(ids.len()))?;
let ids = Rc::new(ids);
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
ids
Ok(ids)
}
/// The bytes a list of `n` objects that a collection builds again counts against the run's
/// host-call allowance, as the selection's list counts them ([`selection_of`]).
pub(super) fn list_charge(n: usize) -> u64 {
16u64.saturating_mul(n as u64)
}
/// The objects directly in the layers and sublayers of a document: what deleting every page item
@@ -938,8 +947,8 @@ fn on_doc_steps<T>(
restored = restore_layer(h, uid, layer.0, &layer.1);
}
}
// The document that was active is active again before any error is given: `f`'s error first,
// then the selection's, then the switch back's.
// The document that was active is active again before any error is given: an error that ends
// the run first, then `f`'s error, then the selection's, then the switch back's.
let back = match active {
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
_ => Ok(()),
@@ -951,12 +960,35 @@ fn on_doc_steps<T>(
{
st.activated = activated;
}
first_error(r, restored, back)
}
/// [`on_doc`]'s result from `f`'s result `r`, then putting back the selection and the layer
/// (`restored`) and the active document (`back`): an error that ends the run first, since a
/// script could catch `f`'s ordinary error, then the first error in that order.
fn first_error<T>(
r: std::result::Result<T, HostError>,
restored: std::result::Result<(), HostError>,
back: std::result::Result<(), HostError>,
) -> std::result::Result<T, HostError> {
if !r.as_ref().is_err_and(ends_run) {
restored.as_ref().err().into_iter().chain(back.as_ref().err()).find(|e| ends_run(e)).map_or(Ok(()), |e| Err(e.clone()))?;
}
let v = r?;
restored?;
back?;
Ok(v)
}
/// Whether `e` ends the run, so that a script cannot catch it.
fn ends_run(e: &HostError) -> bool {
match e {
HostError::Abort(_) => true,
HostError::Marked { error, .. } => ends_run(error),
_ => false,
}
}
/// Marks stale the style objects whose styles a command the run ran removed or renamed, and notes
/// the swatches, symbols, styles and brushes it removed or renamed with the ones earlier commands
/// removed.
@@ -1071,13 +1103,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter
/// or a `\`) letters in one case.
/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
fn path_key(p: &str) -> String {
let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':');
let p = p.replace('\\', "/");
let p = p.trim_end_matches('/').to_string();
if windows { p.to_lowercase() } else { p }
let b = p.as_bytes();
let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':');
if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() }
}
/// `app.redraw()`: returns without changing anything. The app draws a frame between the run's
@@ -1561,6 +1593,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
})
}
/// `documents.addDocumentNoUI(startupPreset)`: a new document from the New Document profile
/// `startupPreset` names, as `addDocument(startupPreset)` makes it, without the New Document
/// dialog. Arguments after `startupPreset` are ignored.
fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer {
docs_add_document(h, &a[..a.len().min(2)])
}
/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page
/// <https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/> gives; the other settings are
/// left out. The settings stay with the run, which hands the script an object of the
@@ -1639,6 +1678,19 @@ fn preset_of(h: &Host, d: &Data) -> Option<usize> {
(i < h.dom.presets.borrow().len()).then_some(i)
}
/// `DocumentPreset.typename`: a `TypeError` for a preset from an earlier run, as its settings give.
fn preset_typename(h: &Host, a: &[Data]) -> Answer {
preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?;
Ok(text("DocumentPreset"))
}
/// `DocumentPreset.toString()`: `[DocumentPreset]`, or a `TypeError` for a preset from an earlier
/// run.
fn preset_to_string(h: &Host, a: &[Data]) -> Answer {
preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?;
Ok(text("[DocumentPreset]"))
}
/// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one.
fn preset_enum(key: &str) -> Option<&'static str> {
Some(match key {
@@ -2119,7 +2171,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
fn items_length(h: &Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
let n = with_doc(h, doc, |_, st| page_items(h, st).len());
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
Ok(num(float(n as u64)))
}
@@ -2160,7 +2212,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
r => r,
},
Data::Number(n) => match position(*n) {
Some(i) => Ok(item_at(h, doc, i)),
Some(i) => item_at(h, doc, i),
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
r => r,
@@ -2171,8 +2223,8 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
}
/// The object at position `i` of `pageItems`, or `undefined` past the end.
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
with_doc(h, doc, |_, st| Ok(page_items(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
@@ -2184,7 +2236,7 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
/// The first object of `pageItems` named `name`, or `Not found`.
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
with_doc(h, doc, |_, st| {
let ids = page_items(h, st);
let ids = page_items(h, st)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -2196,7 +2248,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
Data::String(_) => items_by_name(h, a),
Data::Number(n) => {
let doc = items_doc(h, a)?;
match position(*n).map(|i| item_at(h, doc, i)) {
match position(*n).map(|i| item_at(h, doc, i)).transpose()? {
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
Some(d) => Ok(d),
}
@@ -3008,8 +3060,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
new_preset(&h)
});
let mut members = vec![
("typename".to_string(), typename_of("DocumentPreset"), typed("string")),
("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])),
("typename".to_string(), get(link, preset_typename), typed("string")),
("toString".to_string(), method(link, preset_to_string), returns("string", &[])),
];
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k)))));
HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) }
@@ -3047,6 +3099,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
method(l, docs_add_document),
returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]),
),
("addDocumentNoUI", method(l, docs_add_document_no_ui), returns("Document", &[("startupPreset", "string")])),
("toString", class_text("Documents"), returns("string", &[])),
]),
Some(function(l, docs_at)),
@@ -3220,6 +3273,24 @@ mod tests {
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
}
/// A stop from putting back the selection or the active document is not hidden by the edit's
/// own error, which a script could catch; ordinary errors keep their order.
#[test]
fn an_edit_gives_a_stop_ahead_of_its_own_error() {
let error = |m: &str| HostError::Error(m.into());
let stop = || HostError::Abort("stop".into());
let marked = || HostError::Marked { error: Box::new(stop()), mark: 0 };
assert_eq!(first_error::<()>(Err(error("edit")), Err(stop()), Ok(())), Err(stop()));
assert_eq!(first_error::<()>(Err(error("edit")), Ok(()), Err(stop())), Err(stop()));
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(marked())), Err(marked()));
assert_eq!(first_error(Ok(1), Ok(()), Err(stop())), Err(stop()));
// The edit's own stop comes first, and with no stop the edit's error does.
assert_eq!(first_error::<()>(Err(HostError::Abort("edit".into())), Err(stop()), Ok(())), Err(HostError::Abort("edit".into())));
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(error("back"))), Err(error("edit")));
assert_eq!(first_error::<()>(Ok(()), Err(error("selection")), Err(error("back"))), Err(error("selection")));
assert_eq!(first_error(Ok(1), Ok(()), Ok(())), Ok(1));
}
#[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();
+13 -11
View File
@@ -460,18 +460,20 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
// ---- Document.pathItems ----
/// The ids of a document's paths, in the order of its page items.
fn path_items(h: &super::Host, st: &DocState) -> Rc<Vec<NodeId>> {
/// The ids of a document's paths, in the order of its page items. Building the list again counts
/// the page items it looks through against the run's host-call allowance.
fn path_items(h: &super::Host, st: &DocState) -> Result<Rc<Vec<NodeId>>, HostError> {
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
return ids;
return Ok(ids);
}
#[cfg(test)]
PATH_LISTS.with(|n| n.set(n.get() + 1));
let all = super::page_items(h, st);
let all = super::page_items(h, st)?;
h.charge_call(all.len() as u64)?;
let ids: Rc<Vec<NodeId>> =
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
super::keep_list(&h.dom.paths, st, &ids);
ids
Ok(ids)
}
pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
@@ -491,7 +493,7 @@ fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64)))
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
}
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
@@ -503,14 +505,14 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(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| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
}
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = path_items(h, st);
let ids = path_items(h, st)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -533,10 +535,10 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
let (ids, refused) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st);
let ids = path_items(h, st)?;
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
(ids, refused)
});
Ok::<_, HostError>((ids, refused))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
+4 -4
View File
@@ -1037,17 +1037,17 @@ fn symbol_duplicate(h: &Host, kind: Kind, a: &[Data]) -> Answer {
/// The ids of a document's symbol instances, in the order of its page items, and how many page
/// items it looked at.
fn instances(h: &Host, st: &DocState) -> (Vec<NodeId>, usize) {
let items = page_items(h, st);
fn instances(h: &Host, st: &DocState) -> std::result::Result<(Vec<NodeId>, usize), HostError> {
let items = page_items(h, st)?;
let ids = items.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))).collect();
(ids, items.len())
Ok((ids, items.len()))
}
/// The document of `SymbolItems` and its symbol instances; the page items scanned for them are
/// charged to the run.
fn instances_of(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Vec<NodeId>), HostError> {
let doc = doc_of(h, arg(a, 0), "SymbolItems")?;
let (ids, scanned) = with_doc(h, doc, |_, st| instances(h, st));
let (ids, scanned) = with_doc(h, doc, |_, st| instances(h, st))?;
h.charge_call(scanned as u64)?;
Ok((doc, ids))
}
+1 -1
View File
@@ -74,7 +74,7 @@ fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> Control
Ok(())
}),
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
let ids = page_items(h, st);
let ids = page_items(h, st)?;
h.charge_call(ids.len() as u64)?;
for id in ids.iter() {
if let Some(n) = st.doc.node(*id) {
+14 -11
View File
@@ -1233,18 +1233,21 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember {
}
/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the
/// document is unchanged.
fn frame_ids(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
/// document is unchanged. Building the list again counts the page items it looks through against
/// the run's host-call allowance.
fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow()
&& *uid == st.uid
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
{
return ids.clone();
return Ok(ids.clone());
}
let ids: Vec<NodeId> = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
let all = page_items(h, st)?;
h.charge_call(all.len() as u64)?;
let ids: Vec<NodeId> = all.iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
let ids = Rc::new(ids);
*h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone()));
ids
Ok(ids)
}
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
@@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
fn frames_length(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64)))
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
}
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
@@ -1265,14 +1268,14 @@ fn frames_at(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st);
let ids = frame_ids(h, st)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -1364,13 +1367,13 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st);
let ids = frame_ids(h, st)?;
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
(ids, refused, on_locked)
});
Ok::<_, HostError>((ids, refused, on_locked))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
+1 -1
View File
@@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostEr
{
return Ok(ids.clone());
}
let ids = frame_ids(h, st);
let ids = frame_ids(h, st)?;
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());