From fed96731e242d9df4286b258acb1fcd03ea07637 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:10:20 -0800 Subject: [PATCH 01/41] Scripts: Document.placedItems and rasterItems with place, relink, embed and image data Scripts get Document.placedItems and Document.rasterItems, the linked and embedded images of a document, with length, [i], index, getByName and removeAll. PlacedItems.add() gives a PlacedItem whose file, assigned once, places an image linked through file.place. PlacedItem has file, relink(file) (links.relink), embed() (links.embed), matrix and boundingBox. RasterItem has bitsPerChannel, channels, imageColorSpace and transparent, read from the header of the encoded pixels, and colorizedGrayscale, embedded, file, status, matrix and boundingBox. Assigning matrix runs object.transform. The ImageColorSpace and RasterLinkState enumerations are added. A file to place or relink must be a File the script may read, checked as app.open checks its file, of at most 256 MiB, holding an image; its size is read first, and the error does not name a path the script may not read. Reading file of an image linked outside the script's read scope throws Script file access denied. A matrix with a value that is not finite, no area, or a corner outside the canvas throws with nothing changed. After embed() the PlacedItem is stale and rasterItems lists the image under the same id; a missing linked file stays linked and throws. A run keeps at most 1,024 PlacedItems.add() results. contentVariable, trace, colorants, colorize and overprint throw an error that says they are not available yet. --- crates/engine/src/script/dom.rs | 31 +- crates/engine/src/script/dom/images.rs | 672 +++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 415 ++++++++++++ crates/js/src/file_classes.rs | 14 + crates/js/src/host.rs | 6 + crates/js/src/lib.rs | 2 +- docs/mcp.md | 24 + docs/target-app-parity.md | 1 + 9 files changed, 1156 insertions(+), 10 deletions(-) create mode 100644 crates/engine/src/script/dom/images.rs create mode 100644 crates/engine/src/tests/script_dom_images.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8e6c46e87d..cd96ea46c5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod images; mod save_open; /// The error for a member read or called with no document open. @@ -97,6 +98,8 @@ pub(super) struct State { /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, presets: RefCell>>, + /// What the placed and raster items keep ([`images::State`]). + images: images::State, } impl State { @@ -287,15 +290,22 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result 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 id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let Some((class, handle)) = host_ref_parts(d).filter(|(c, _)| ITEM_CLASSES.contains(c)) else { + return Err(HostError::Type("this is not a page item".into())); + }; + let (run, uid, id) = match handle.as_slice() { + [run, uid, high, low] => (*run, *uid, id_of(*high, *low)), + [run, uid, _, _, slot] => (*run, *uid, Some(images::pending_id(h, *run, *uid, *slot)?)), + _ => 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 id = id.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; - if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { + if st.doc.node(id).is_none_or(|n| typename(n) != Some(class)) { return Err(HostError::Error(STALE_ITEM.into())); } Ok(Item { doc, id }) @@ -1593,7 +1603,8 @@ struct Destination { fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { 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 pending = images::pending_as_item(h, target)?.map(|p| p.to_vec()); + let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer")); let Some(&[run, uid, 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())); @@ -1807,7 +1818,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1870,6 +1881,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "Document", m)), ); document.extend(save_open::document_members(l)); + document.extend(images::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1933,7 +1945,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| !images::CLASSES.contains(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(images::classes(l)); classes.extend(save_open::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs new file mode 100644 index 0000000000..bf79f77013 --- /dev/null +++ b/crates/engine/src/script/dom/images.rs @@ -0,0 +1,672 @@ +//! Placed and raster art in the script object model: `Document.placedItems` and +//! `Document.rasterItems`, and the members of `PlacedItem` and `RasterItem`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! A `PlacedItem` is an image linked to its file, and a `RasterItem` an image whose pixels are in +//! the document. Placing runs `file.place` with `link`, relinking `links.relink` and embedding +//! `links.embed`, so each joins the run's transaction. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `PlacedItems.add()` gives a placed item with no file. Its `file` may be assigned once, which +//! places the file linked; after that, and on every other placed item, `file` is read-only and +//! `relink(file)` changes it. Every other member of an item with no file throws +//! [`FILE_REQUIRED`]; an item with no file is not in the document and is dropped when the run +//! ends. +//! - A file to place or relink is a `File` the script may read ([`crate::file_access::ScriptGate`]) +//! that holds an image, of at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is. +//! - `PlacedItem.file` throws `Script file access denied`, without the path, when the script may +//! not read the linked file. +//! - `embed()` turns the placed item into a raster item with the same id: the placed item is stale +//! after it, and `rasterItems` lists the raster item. An image whose file is missing throws +//! [`MISSING_LINK`] and stays linked. +//! - `bitsPerChannel`, `channels`, `imageColorSpace` and `transparent` come from the header of the +//! image's encoded pixels; `transparent` is true for an image with an alpha channel or a +//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only +//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file. +//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of +//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a +//! matrix with no area or one that puts a corner of the image outside the canvas is refused. +//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_geom::{Affine, Point}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; + +use super::{ + Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, editable, find_doc, + float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error of a member of a `PlacedItems.add()` result whose `file` was not assigned. +pub const FILE_REQUIRED: &str = "PlacedItem.file is required"; +/// The error of assigning `file` to a placed item that has one. +pub const FILE_READ_ONLY: &str = "PlacedItem.file is read-only: use relink"; +/// The error of embedding an image whose linked file cannot be found. +pub const MISSING_LINK: &str = "Linked image is missing"; +/// The error of placing or relinking a file that is not an image. +pub const NOT_AN_IMAGE: &str = "The file is not an image"; +/// The largest file a script places or relinks, in bytes. +pub const MAX_PLACED_BYTES: u64 = 256 << 20; +/// The most `PlacedItems.add()` results one run keeps. +pub const MAX_PENDING: usize = 1024; +/// The error of the `matrix` of an image drawn distorted. +const DISTORTED: &str = "the image is distorted and has no matrix"; +/// The smallest determinant a `matrix` takes, in square points a square pixel. +const MIN_DETERMINANT: f64 = 1e-12; +/// The members of a `Matrix` record, in the order of an affine matrix's six numbers. +const MATRIX_KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; + +/// The enumerations the members here give values of, as the help page +/// lists them. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("ImageColorSpace", &["CMYK", "DeviceN", "Grayscale", "Indexed", "LAB", "RGB", "Separation"]), + ("RasterLinkState", &["DATAFROMFILE", "DATAMODIFIED", "NODATA"]), +]; + +/// The classes this module defines, in place of the plain page item classes. +pub(super) const CLASSES: &[&str] = &["PlacedItem", "RasterItem"]; + +/// A document's uid, the document as it was, and the ids of its linked and embedded images then. +type Lists = (u64, Arc, Rc>, Rc>); + +/// What a run keeps for placed and raster items: the `PlacedItems.add()` results and the last +/// lists of a document's images. +#[derive(Default)] +pub(super) struct State { + pending: RefCell>, + lists: RefCell>, +} + +/// A `PlacedItems.add()` result: its document, and its image once `file` placed one. +struct Pending { + uid: u64, + bound: Option, +} + +/// The slot of a `PlacedItems.add()` result in this run, from its handle. +fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result { + let stale = || HostError::Error(STALE_ITEM.into()); + if whole(run) != Some(h.run) { + return Err(stale()); + } + let k = whole(slot).and_then(|k| usize::try_from(k).ok()).ok_or_else(stale)?; + let uid = whole(uid).ok_or_else(stale)?; + match h.dom.images.pending.borrow().get(k) { + Some(p) if p.uid == uid => Ok(k), + _ => Err(stale()), + } +} + +/// The id of the image a `PlacedItems.add()` result placed. +pub(super) fn pending_id(h: &Host, run: f64, uid: f64, slot: f64) -> Result { + let k = slot_of(h, run, uid, slot)?; + match h.dom.images.pending.borrow().get(k).and_then(|p| p.bound) { + Some(id) => Ok(id), + None => Err(HostError::Error(FILE_REQUIRED.into())), + } +} + +/// The handle's run, uid and slot when `d` is a `PlacedItems.add()` result. Its handle has five +/// numbers, where a page item's has four. +fn pending_handle(d: &Data) -> Option<[f64; 3]> { + match host_ref_parts(d) { + Some(("PlacedItem", handle)) => match handle.as_slice() { + [run, uid, _, _, slot] => Some([*run, *uid, *slot]), + _ => None, + }, + _ => None, + } +} + +/// The page item handle (run, uid and the two halves of the id) of the image a +/// `PlacedItems.add()` result `d` placed, or `None` when `d` is not such a result. +pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result, HostError> { + let Some([run, uid, slot]) = pending_handle(d) else { return Ok(None) }; + let [high, low] = super::id_parts(pending_id(h, run, uid, slot)?); + Ok(Some([run, uid, high, low])) +} + +/// The ids of a document's linked (`placed`) or embedded images in paint order. +fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { + let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; + if let Some(l) = &*h.dom.images.lists.borrow() + && l.0 == st.uid + && Arc::ptr_eq(&l.1, &st.doc) + { + return Ok(pick(l)); + } + let all = page_items(h, st); + h.charge_call(all.len() as u64)?; + let (mut linked, mut embedded) = (Vec::new(), Vec::new()); + for id in all.iter() { + if let Some(NodeKind::Image(im)) = st.doc.node(*id).map(|n| &n.kind) { + if im.link.is_some() { linked.push(*id) } else { embedded.push(*id) } + } + } + let l = (st.uid, st.doc.clone(), Rc::new(linked), Rc::new(embedded)); + let out = pick(&l); + *h.dom.images.lists.borrow_mut() = Some(l); + Ok(out) +} + +fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> { + match d { + Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v), + _ => None, + } +} + +fn id_value(d: Option<&Data>) -> Option { + match d { + Some(Data::Number(n)) => whole(*n).map(NodeId), + Some(Data::Array(a)) => id_value(a.first()), + _ => None, + } +} + +// ---- PlacedItems and RasterItems ---- + +fn collection(placed: bool) -> &'static str { + if placed { "PlacedItems" } else { "RasterItems" } +} + +fn list_doc(h: &Host, a: &[Data], placed: bool) -> Result { + doc_of(h, arg(a, 0), collection(placed)) +} + +fn list_length(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let n = with_doc(h, doc, |_, st| images(h, st, placed).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn list_at(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + 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(images(h, st, placed)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn list_by_name(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + 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 = images(h, st, placed)?; + 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())) + }) +} + +fn list_index(h: &Host, a: &[Data], placed: bool) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a, placed), + Data::Number(_) => match list_at(h, a, placed)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `removeAll()`: deletes every image of the collection in one command. A hidden or locked one, or +/// one in a hidden or locked layer or group, stops it before anything is deleted. +fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = images(h, st, placed)?; + let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused)) + })?; + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {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::>()})))?; + } + Ok(Data::Undefined) +} + +/// `PlacedItems.add()`: a placed item with no file yet, which assigning `file` places. +fn placed_add(h: &Host, a: &[Data]) -> Answer { + let doc = list_doc(h, a, true)?; + let mut pending = h.dom.images.pending.borrow_mut(); + if pending.len() >= MAX_PENDING { + return Err(HostError::Range(format!("a run makes at most {MAX_PENDING} placed items with PlacedItems.add"))); + } + pending.push(Pending { uid: doc.uid, bound: None }); + Ok(host_ref("PlacedItem", &[float(h.run), float(doc.uid), 0.0, 0.0, float(pending.len() as u64 - 1)])) +} + +macro_rules! both { + ($($placed:ident, $raster:ident => $f:ident;)*) => { + $( + fn $placed(h: &Host, a: &[Data]) -> Answer { + $f(h, a, true) + } + fn $raster(h: &Host, a: &[Data]) -> Answer { + $f(h, a, false) + } + )* + }; +} + +both! { + placed_length, raster_length => list_length; + placed_at, raster_at => list_at; + placed_by_name, raster_by_name => list_by_name; + placed_index, raster_index => list_index; + placed_remove_all, raster_remove_all => list_remove_all; +} + +fn placed_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, list_doc(h, a, true)?.uid)) +} + +fn raster_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, list_doc(h, a, false)?.uid)) +} + +fn doc_placed(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("PlacedItems", &[float(h.run), float(doc.uid)])) +} + +fn doc_raster(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("RasterItems", &[float(h.run), float(doc.uid)])) +} + +// ---- files ---- + +/// Whether the script's commands may read `path` now ([`crate::file_access::ScriptGate`]). +fn may_read(h: &Host, path: &str) -> bool { + let documents = h.session.borrow().documents().iter().filter_map(|d| d.path.clone()).collect(); + let gate = h.disk.borrow().gate(documents); + crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok() +} + +/// The real path of the `File` `d` gives as an image to place or relink: one the script may read +/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of +/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no +/// error names the path. +fn image_path(h: &Host, d: &Data, what: &str) -> Result { + let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?; + if path.len() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(super::super::files::PATH_TOO_LONG.into())); + } + let unc = path.starts_with("\\\\") || path.starts_with("//"); + if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") { + return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); + } + let real = h.disk.borrow().open_target(path).map_err(|m| HostError::Error(m.into()))?; + let meta = std::fs::metadata(&real).map_err(|_| HostError::Error(super::super::files::NOT_FOUND.into()))?; + if !meta.is_file() { + return Err(HostError::Error(super::super::files::NOT_REGULAR.into())); + } + if meta.len() > MAX_PLACED_BYTES { + return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20))); + } + let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned(); + // What the file holds, read the way `file.place` reads it, before the document changes. + let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?; + if field(&info, "pixelWidth").is_none() { + return Err(HostError::Error(NOT_AN_IMAGE.into())); + } + Ok(path) +} + +// ---- PlacedItem ---- + +/// The item `this` names when it is a `cls` (`PlacedItem` or `RasterItem`). +fn this_of(h: &Host, a: &[Data], cls: &str) -> Result { + match host_ref_parts(arg(a, 0)) { + Some((c, _)) if c == cls => item_of(h, arg(a, 0)), + _ => Err(HostError::Type(format!("this is not a {cls}"))), + } +} + +/// Reads the image of the `cls` `this` names with `f`. +fn read_image(h: &Host, a: &[Data], cls: &str, f: impl FnOnce(&DocState, &crate::doc::Node, &crate::doc::ImageObject) -> Answer) -> Answer { + let item = this_of(h, a, cls)?; + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => match &n.kind { + NodeKind::Image(im) => f(st, n, im), + _ => Err(HostError::Error(STALE_ITEM.into())), + }, + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn placed_file(h: &Host, a: &[Data]) -> Answer { + if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) { + let k = slot_of(h, run, uid, slot)?; + if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) { + return Ok(Data::Null); + } + } + let path = read_image(h, a, "PlacedItem", |_, _, im| Ok(text(im.link.as_ref().map(|l| l.path.clone()).unwrap_or_default())))?; + let Data::String(path) = path else { return Ok(Data::Null) }; + if !may_read(h, &path) { + return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); + } + Ok(file_ref(&path)) +} + +/// `file = File`: places the file, linked, for a `PlacedItems.add()` result that has none. +fn placed_set_file(h: &Host, a: &[Data]) -> Answer { + let Some([run, uid, slot]) = pending_handle(arg(a, 0)) else { + if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PlacedItem") { + this_of(h, a, "PlacedItem")?; + return Err(HostError::Error(FILE_READ_ONLY.into())); + } + return Err(HostError::Type("this is not a PlacedItem".into())); + }; + let k = slot_of(h, run, uid, slot)?; + if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_some()) { + return Err(HostError::Error(FILE_READ_ONLY.into())); + } + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let path = image_path(h, arg(a, 1), "PlacedItem.file")?; + let placed = on_doc(h, doc.uid, true, |h| command(h, "file.place", &json!({"path": path, "link": true})))?; + let ids: Vec = match field(&placed, "ids") { + Some(Data::Array(ids)) => ids.iter().filter_map(|d| id_value(Some(d))).map(|i| i.0).collect(), + _ => Vec::new(), + }; + let id = id_value(field(&placed, "image")).or_else(|| id_value(field(&placed, "ids"))); + let linked = |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); + match id.filter(|id| linked(*id)) { + Some(id) => { + if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) { + p.bound = Some(id); + } + Ok(Data::Undefined) + } + None => { + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids})))?; + } + Err(HostError::Error(NOT_AN_IMAGE.into())) + } + } +} + +/// `relink(file)`: `links.relink` of the item to the image in `file`. +fn placed_relink(h: &Host, a: &[Data]) -> Answer { + let item = this_of(h, a, "PlacedItem")?; + let path = image_path(h, arg(a, 1), "relink's file")?; + edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?; + Ok(Data::Undefined) +} + +/// `embed()`: `links.embed` of the item, which becomes a raster item. +fn placed_embed(h: &Host, a: &[Data]) -> Answer { + let item = this_of(h, a, "PlacedItem")?; + let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?; + if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") { + return Err(HostError::Error(MISSING_LINK.into())); + } + let r = edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?; + let embedded = match field(&r, "embedded") { + Some(Data::Array(ids)) => ids.iter().any(|d| id_value(Some(d)) == Some(item.id)), + _ => false, + }; + if !embedded { + return Err(HostError::Error(MISSING_LINK.into())); + } + Ok(Data::Undefined) +} + +// ---- both ---- + +/// `matrix`: the image's pixels to script coordinates. +fn matrix(h: &Host, a: &[Data], cls: &str) -> Answer { + read_image(h, a, cls, |st, n, im| { + if n.is_distorted_image() { + return Err(HostError::Error(DISTORTED.into())); + } + let f = frame(st)?; + let [a0, b0, c0, d0, e0, f0] = im.xf.as_coeffs(); + let m = match h.dom.coords.get() { + Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0], + Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top], + }; + let mut items = vec![("typename".to_string(), text("Matrix"))]; + items.extend(MATRIX_KEYS.iter().zip(m).map(|(k, v)| (k.to_string(), num(v)))); + Ok(Data::Object(items)) + }) +} + +/// The six numbers of the `Matrix` record `d`, `mValueA` to `mValueTY`, each finite. +fn matrix_value(d: &Data) -> Result<[f64; 6], HostError> { + let mut m = [0.0; 6]; + for (k, out) in MATRIX_KEYS.iter().zip(m.iter_mut()) { + *out = match field(d, k) { + Some(Data::Number(n)) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("matrix must be a Matrix with a finite {k}"))), + }; + } + Ok(m) +} + +/// Whether `m` gives a pixel an area of at least [`MIN_DETERMINANT`]. +fn area_of(m: Affine) -> bool { + let det = m.determinant(); + !det.is_nan() && det.abs() >= MIN_DETERMINANT +} + +/// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix. +/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted +/// image is refused before anything changes; the matrix the image has already changes nothing. +fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { + let m = matrix_value(arg(a, 1))?; + let item = this_of(h, a, cls)?; + let delta = with_doc(h, item.doc, |_, st| { + let Some((n, im)) = st.doc.node(item.id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some((n, im)) } else { None }) else { + return Err(HostError::Error(STALE_ITEM.into())); + }; + if n.is_distorted_image() { + return Err(HostError::Error(DISTORTED.into())); + } + let f = frame(st)?; + let target = Affine::new(match h.dom.coords.get() { + Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]], + Coords::Artboard => [m[0], m[1], m[2], m[3], m[4] + f.left, m[5] + f.top], + }); + if !area_of(target) { + return Err(HostError::Range("the matrix gives the image no area".into())); + } + let (w, ht) = (f64::from(im.width), f64::from(im.height)); + let limit = crate::MAX_COORD * 2.0; + let corners = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].map(|(x, y)| target * Point::new(x, y)); + if corners.iter().any(|p| !(p.x.abs() <= limit && p.y.abs() <= limit)) { + return Err(HostError::Range("the matrix puts the image outside the canvas".into())); + } + let old = im.xf; + if old.as_coeffs().iter().zip(target.as_coeffs()).all(|(o, t)| (o - t).abs() <= 1e-9) { + return Ok(None); + } + if !area_of(old) { + return Err(HostError::Error("the image has no area to transform".into())); + } + Ok(Some((target * old.inverse()).as_coeffs())) + })?; + if let Some(d) = delta { + edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?; + } + Ok(Data::Undefined) +} + +/// `boundingBox`: the pixel rectangle at one point a pixel, `[left, top, right, bottom]`. +fn bounding_box(h: &Host, a: &[Data], cls: &str) -> Answer { + read_image(h, a, cls, |_, _, im| { + let (w, ht) = (f64::from(im.width), f64::from(im.height)); + Ok(Data::Array(match h.dom.coords.get() { + Coords::Document => vec![num(0.0), num(ht), num(w), num(0.0)], + Coords::Artboard => vec![num(0.0), num(0.0), num(w), num(ht)], + })) + }) +} + +fn placed_matrix(h: &Host, a: &[Data]) -> Answer { + matrix(h, a, "PlacedItem") +} + +fn raster_matrix(h: &Host, a: &[Data]) -> Answer { + matrix(h, a, "RasterItem") +} + +fn placed_set_matrix(h: &Host, a: &[Data]) -> Answer { + set_matrix(h, a, "PlacedItem") +} + +fn raster_set_matrix(h: &Host, a: &[Data]) -> Answer { + set_matrix(h, a, "RasterItem") +} + +fn placed_box(h: &Host, a: &[Data]) -> Answer { + bounding_box(h, a, "PlacedItem") +} + +fn raster_box(h: &Host, a: &[Data]) -> Answer { + bounding_box(h, a, "RasterItem") +} + +// ---- RasterItem ---- + +/// The header of the raster item's encoded pixels. +fn header(h: &Host, a: &[Data], f: impl FnOnce(&craft_image_codecs::RasterInspection) -> Data) -> Answer { + read_image(h, a, "RasterItem", |st, _, im| { + let blob = st.doc.images.get(&im.key).ok_or_else(|| HostError::Error("the image's pixels are not in the document".into()))?; + match craft_image_codecs::inspect_raster(&blob.bytes) { + Ok(Some(i)) => Ok(f(&i)), + _ => Err(HostError::Error("the image's header does not describe its pixels".into())), + } + }) +} + +fn raster_bits(h: &Host, a: &[Data]) -> Answer { + header(h, a, |i| num(f64::from(i.bits_per_sample))) +} + +fn raster_channels(h: &Host, a: &[Data]) -> Answer { + header(h, a, |i| num(f64::from(i.channels))) +} + +fn raster_transparent(h: &Host, a: &[Data]) -> Answer { + use craft_image_codecs::RasterColorType as T; + header(h, a, |i| Data::Bool(matches!(i.color_type, T::GrayAlpha | T::Rgba | T::CmykAlpha) || i.transparent_index.is_some())) +} + +fn raster_color_space(h: &Host, a: &[Data]) -> Answer { + use craft_image_codecs::RasterColorType as T; + let space = header(h, a, |i| { + text(match i.color_type { + T::Bitmap | T::Gray | T::GrayAlpha => "ImageColorSpace.Grayscale", + T::Rgb | T::Rgba => "ImageColorSpace.RGB", + T::Cmyk | T::CmykAlpha => "ImageColorSpace.CMYK", + T::Indexed => "ImageColorSpace.Indexed", + T::Lab => "ImageColorSpace.LAB", + T::Other => "", + }) + })?; + match space { + Data::String(s) if s.is_empty() => Err(HostError::Error("the image's header does not describe its color space".into())), + d => Ok(d), + } +} + +fn raster_colorized(h: &Host, a: &[Data]) -> Answer { + read_image(h, a, "RasterItem", |st, n, im| { + let gray = st.doc.images.get(&im.key).is_some_and(|b| b.gray_source().is_some()); + Ok(Data::Bool(gray && n.extras().colorize.is_some())) + }) +} + +fn raster_embedded(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(Data::Bool(true)) +} + +/// `embedded = true` changes nothing; a raster item cannot be linked by assigning `false`. +fn raster_set_embedded(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + match arg(a, 1) { + Data::Bool(true) => Ok(Data::Undefined), + Data::Bool(false) => Err(HostError::Error("a raster item cannot be linked by setting embedded to false".into())), + _ => Err(HostError::Type("embedded must be true or false".into())), + } +} + +fn raster_file(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(Data::Null) +} + +fn raster_status(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(text("RasterLinkState.NODATA")) +} + +/// `Document.placedItems` and `Document.rasterItems`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("placedItems", get(l, doc_placed)), ("rasterItems", get(l, doc_raster))]) +} + +/// The collections, `PlacedItem` and `RasterItem`, after `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let placed_list = named(vec![ + ("typename", typename_of("PlacedItems")), + ("length", get(l, placed_length)), + ("parent", get(l, placed_parent)), + ("index", method(l, placed_index)), + ("getByName", method(l, placed_by_name)), + ("removeAll", method(l, placed_remove_all)), + ("add", method(l, placed_add)), + ]); + let raster_list = named(vec![ + ("typename", typename_of("RasterItems")), + ("length", get(l, raster_length)), + ("parent", get(l, raster_parent)), + ("index", method(l, raster_index)), + ("getByName", method(l, raster_by_name)), + ("removeAll", method(l, raster_remove_all)), + ]); + let mut placed = named(vec![ + ("file", property(l, placed_file, placed_set_file)), + ("relink", method(l, placed_relink)), + ("embed", method(l, placed_embed)), + ("matrix", property(l, placed_matrix, placed_set_matrix)), + ("boundingBox", get(l, placed_box)), + ]); + placed.extend(["contentVariable", "trace"].into_iter().map(|m| later(l, "PlacedItem", m))); + let mut raster = named(vec![ + ("bitsPerChannel", get(l, raster_bits)), + ("channels", get(l, raster_channels)), + ("colorizedGrayscale", get(l, raster_colorized)), + ("embedded", property(l, raster_embedded, raster_set_embedded)), + ("file", get(l, raster_file)), + ("imageColorSpace", get(l, raster_color_space)), + ("matrix", property(l, raster_matrix, raster_set_matrix)), + ("status", get(l, raster_status)), + ("transparent", get(l, raster_transparent)), + ("boundingBox", get(l, raster_box)), + ]); + raster.extend(["colorants", "colorize", "contentVariable", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); + vec![ + class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), + class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), + class("PlacedItem", Some("PageItem"), placed, None), + class("RasterItem", Some("PageItem"), raster, None), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 436d74cf75..a1b22fc087 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_images; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs new file mode 100644 index 0000000000..6b3f3d3cac --- /dev/null +++ b/crates/engine/src/tests/script_dom_images.rs @@ -0,0 +1,415 @@ +//! Placed and raster items in the script object model: placing a file with `PlacedItems.add()`, +//! relinking, embedding, the encoded image's header, and the file checks. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder for the script and an `outside` folder the +/// script may not read, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-dom-images-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A `w`×`h` 8-bit gray PNG. +fn gray_png(w: u32, h: u32) -> Vec { + let raw = vec![128u8; (w * h) as usize]; + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +fn js_path(p: &Path) -> String { + p.to_string_lossy().replace('\\', "\\\\").replace('\'', "\\'") +} + +/// A session with one 400 × 300 pt document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// Runs `text` as `main/main.jsx` in `base`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn log(s: &mut Session, base: &Path, text: &str) -> Vec { + let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The images of the active document: (id, linked path). +fn images(s: &Session) -> Vec<(NodeId, Option)> { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((n.id, im.link.as_ref().map(|l| l.path.clone()))); + } + }); + out +} + +/// Places `path` linked (`link`) with the engine's own command, outside any script. +fn place(s: &mut Session, path: &Path, link: bool) -> NodeId { + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": link})).unwrap(); + NodeId(r["ids"][0].as_u64().unwrap()) +} + +#[test] +fn placed_add_file_links_one_image() { + let base = folder("add"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(40, 20)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems.add(); vc.log(p.file); vc.log(d.placedItems.length);\ + var m = ''; try {{ p.width; }} catch (e) {{ m = e.message; }} vc.log(m);\ + p.file = new File('{}'); vc.log(d.placedItems.length); vc.log(p.typename); vc.log(p.file.name);\ + vc.log(p.width); vc.log(d.placedItems[0].file.name); vc.log(d.rasterItems.length);\ + try {{ p.file = new File('{}'); }} catch (e) {{ m = e.message; }} vc.log(m);", + js_path(&png), + js_path(&png) + ), + ); + assert_eq!(out[..3], [json!(null), json!(0), json!("PlacedItem.file is required")]); + assert_eq!(out[3..9], [json!(1), json!("PlacedItem"), json!("a.png"), json!(40), json!("a.png"), json!(0)]); + assert_eq!(out[9], json!("PlacedItem.file is read-only: use relink")); + let imgs = images(&s); + assert_eq!(imgs.len(), 1); + assert_eq!(imgs[0].1.as_deref().map(Path::new), Some(png.as_path())); + assert_eq!(undo_steps(&s), 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_file_refuses_bad_values_without_changing_the_document() { + let base = folder("bad"); + std::fs::write(base.join("main/notes.txt"), "hello").unwrap(); + std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap(); + let big = std::fs::File::create(base.join("main/big.png")).unwrap(); + big.set_len((256 << 20) + 1).unwrap(); + drop(big); + let mut s = session(); + let cases = [ + ("'a.png'", "must be a File"), + ("{}", "must be a File"), + (&format!("new File('{}')", js_path(&base.join("main/notes.txt"))), "not an image"), + (&format!("new File('{}')", js_path(&base.join("outside/b.png"))), "Script file access denied"), + (&format!("new File('{}')", js_path(&base.join("main/big.png"))), "larger than 256 MiB"), + (&format!("new File('{}')", js_path(&base.join("main/none.png"))), "does not exist"), + (&format!("new Folder('{}')", js_path(&base.join("main"))), "must be a File"), + ]; + for (value, message) in cases { + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = {value};")); + assert!(e.contains(message), "{value}: {e}"); + assert!(!e.contains("outside"), "{value}: {e}"); + assert!(images(&s).is_empty(), "{value}"); + assert_eq!(undo_steps(&s), 0, "{value}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_plain_object_shaped_like_a_file_is_not_one() { + let base = folder("forged"); + std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap(); + let mut s = session(); + let forged = js_path(&base.join("outside/b.png")); + let e = failure(&mut s, &base, &format!("var f = {{}}; f['\\u0000fileRef'] = '{forged}'; app.activeDocument.placedItems.add().file = f;")); + assert!(e.contains("not plain data"), "{e}"); + assert!(images(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_forged_or_altered_file_does_not_change_the_path() { + let base = folder("forged-proto"); + let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + std::fs::write(&c, gray_png(30, 10)).unwrap(); + let mut s = session(); + let forged = js_path(&c); + let make = format!( + "var f = Object.create(File.prototype); f.__vcPath = '{forged}';\ + Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});\ + Object.defineProperty(f, 'path', {{value: '{forged}', enumerable: true}});" + ); + for target in ["app.activeDocument.placedItems.add().file = f;", "app.activeDocument.placedItems[0].relink(f);"] { + if target.contains("relink") { + place(&mut s, &a, true); + } + let e = failure(&mut s, &base, &format!("{make} {target}")); + assert!(e.contains("must be a File") && !e.contains("c.png"), "{target}: {e}"); + } + let id = images(&s)[0].0; + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + let alter = format!( + "f.__vcPath = '{forged}'; Object.defineProperty(f, '__vcPath', {{value: '{forged}'}});\ + Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});" + ); + let out = log( + &mut s, + &base, + &format!( + "var f = new File('{}'); {alter} var p = app.activeDocument.placedItems.add(); p.file = f; vc.log(p.file.name);\ + f = new File('{}'); {alter} p.relink(f); vc.log(p.file.name);", + js_path(&b), + js_path(&a) + ), + ); + assert_eq!(out, vec![json!("b.png"), json!("a.png")]); + let paths: Vec<_> = images(&s).into_iter().map(|(_, p)| p).collect(); + assert_eq!(paths.len(), 2); + assert!(paths.iter().all(|p| p.as_deref().map(Path::new) == Some(a.as_path())), "{paths:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_placed_items_add_result_is_a_relative_object() { + let base = folder("relative"); + let (a, b) = (base.join("main/a.png"), base.join("main/b.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + let mut s = session(); + let first = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, q = d.placedItems[0], p = d.placedItems.add(), m = '';\ + try {{ q.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m = e.message; }} vc.log(m);\ + p.file = new File('{}'); q.move(p, ElementPlacement.PLACEBEFORE);", + js_path(&b) + ), + ); + assert_eq!(out, vec![json!("PlacedItem.file is required")]); + let order: Vec = images(&s).into_iter().map(|(id, _)| id).collect(); + assert_eq!(order.len(), 2); + assert_eq!(order[1], first, "{order:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_file_that_is_not_an_image_is_refused_before_placing() { + let base = folder("text"); + let notes = base.join("main/notes.txt"); + std::fs::write(¬es, "hello").unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!("try {{ app.activeDocument.placedItems.add().file = new File('{}'); }} catch (e) {{ vc.log(e.message); }}", js_path(¬es)), + ); + assert_eq!(out, vec![json!("The file is not an image")]); + assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, |c| c.len()), 0); + assert_eq!(undo_steps(&s), 0); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_items_add_is_bounded() { + let base = folder("pending"); + let mut s = session(); + let e = failure(&mut s, &base, "var p = app.activeDocument.placedItems; for (var i = 0; i < 1025; i++) p.add();"); + assert!(e.contains("at most 1024"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn relink_denied_path_preserves_old_link() { + let base = folder("relink"); + let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + std::fs::write(&c, gray_png(30, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&c))); + assert!(e.contains("Script file access denied") && !e.contains("c.png"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + let before = undo_steps(&s); + let out = log(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0]; p.relink(new File('{}')); vc.log(p.file.name);", js_path(&b))); + assert_eq!(out, vec![json!("b.png")]); + assert_eq!(images(&s), vec![(id, Some(b.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn embed_reclassifies_and_stales_wrapper() { + let base = folder("embed"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0]; p.embed(); var m = '';\ + try { p.name; } catch (e) { m = e.message; } vc.log(m);\ + vc.log(d.placedItems.length); var r = d.rasterItems[0]; vc.log(r.typename);\ + vc.log(r.embedded); vc.log(r.file); vc.log(r.status === RasterLinkState.NODATA); r.embedded = true;\ + try { r.embedded = false; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out[..6], [json!("Stale page item"), json!(0), json!("RasterItem"), json!(true), json!(null), json!(true)]); + assert!(out[6].as_str().unwrap().contains("cannot be linked"), "{out:?}"); + assert_eq!(images(&s), vec![(id, None)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn missing_link_embed_reports_error() { + let base = folder("missing"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + std::fs::remove_file(&a).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, &base, "app.activeDocument.placedItems[0].embed();"); + assert!(e.contains("Linked image is missing"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn raster_metadata_uses_encoded_header_not_rgb_fallback() { + let base = folder("meta"); + let (g, c) = (base.join("main/g.png"), base.join("main/c.png")); + std::fs::write(&g, gray_png(6, 4)).unwrap(); + std::fs::write(&c, super::links::png(3, 2, [10, 20, 30])).unwrap(); + let mut s = session(); + place(&mut s, &g, false); + place(&mut s, &c, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems, t = [];\ + for (var i = 0; i < r.length; i++) t.push([r[i].imageColorSpace, r[i].channels, r[i].bitsPerChannel, r[i].transparent, r[i].colorizedGrayscale]);\ + vc.log(t); vc.log(r[0].boundingBox); vc.log(r[1].imageColorSpace === ImageColorSpace.RGB); var m = r[1].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);", + ); + assert_eq!(out[0], json!([["ImageColorSpace.Grayscale", 1, 8, false, false], ["ImageColorSpace.RGB", 4, 8, true, false]])); + assert_eq!(out[1], json!([0, 4, 6, 0])); + assert_eq!(out[2], json!(true)); + let m = out[3].as_array().unwrap(); + assert_eq!(m[0], json!("Matrix")); + assert!(m[1].as_f64().unwrap() > 0.0 && m[2].as_f64().unwrap() < 0.0, "{m:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_matrix_assignment_transforms_the_image() { + let base = folder("matrix"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, false); + let before = undo_steps(&s); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0], m = r.matrix;\ + m.mValueA = 0; m.mValueB = 2; m.mValueC = -3; m.mValueD = 0; m.mValueTX = 50; m.mValueTY = 60; r.matrix = m;\ + var n = r.matrix; vc.log([n.mValueA, n.mValueB, n.mValueC, n.mValueD, n.mValueTX, n.mValueTY]); r.matrix = n;", + ); + let got: Vec = out[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + for (g, w) in got.iter().zip([0.0, 2.0, -3.0, 0.0, 50.0, 60.0]) { + assert!((g - w).abs() < 1e-6, "{got:?}"); + } + let xf = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf.as_coeffs(), + _ => panic!("not an image"), + }; + assert!((xf[1] + 2.0).abs() < 1e-6 && (xf[2] + 3.0).abs() < 1e-6, "{xf:?}"); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &base, "var r = app.activeDocument.rasterItems[0]; r.matrix = r.matrix;"); + assert_eq!(undo_steps(&s), before + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_matrix_refuses_bad_values_without_changing_the_image() { + let base = folder("matrix-bad"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, true); + let xf = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf, + _ => panic!("not an image"), + }; + let (was, before) = (xf(&s), undo_steps(&s)); + let cases = [ + ("m.mValueA = NaN;", "mValueA is not a finite number"), + ("m.mValueTY = -Infinity;", "mValueTY is not a finite number"), + ("m.mValueB = '1';", "finite mValueB"), + ("delete m.mValueTX;", "finite mValueTX"), + ("m = 5;", "finite mValueA"), + ("m.mValueA = 0; m.mValueD = 0;", "no area"), + ("m.mValueA = 1e300;", "outside the canvas"), + ("m.mValueTX = 9e6;", "outside the canvas"), + ("m.mValueA = 1e6;", "outside the canvas"), + ]; + for (change, message) in cases { + let e = failure(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0], m = p.matrix; {change} p.matrix = m;")); + assert!(e.contains(message), "{change}: {e}"); + assert_eq!(xf(&s), was, "{change}"); + assert_eq!(undo_steps(&s), before, "{change}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_file_getter_hides_out_of_scope_link() { + let base = folder("hide"); + let b = base.join("outside/secret.png"); + std::fs::write(&b, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &b, true); + let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);"); + assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn stale_and_foreign_placed_items_are_refused() { + let base = folder("stale"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.placedItems[0], m = []; p.remove();\ + try { p.relink(null); } catch (e) { m.push(e.message); }\ + try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\ + try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]); + assert!(s.active().unwrap().doc.node(id).is_none()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index e46fd9f77d..f36fa28f2c 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -1133,6 +1133,20 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { Ok(()) } +/// The [`crate::Data`] that stands for a `File` of `path` ([`FILE_REF_KEY`]), in the platform's +/// form. A member of a host class ([`crate::HostClass`]) gives one to hand the script a new `File`. +pub fn file_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + +impl Interp { + /// A new `File` for `path`, which a member of a host class gave ([`file_ref`]). + pub(crate) fn write_file_ref(&mut self, path: &str) -> JsResult { + let proto = classes(self)?.file_proto; + instance(self, proto, Value::str(path)) + } +} + /// Adds `File` and `Folder` to the global object, their work done by the host functions in /// `items` ([`crate::Realm::define_file_classes`]). pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index a639dbd0cb..061486b380 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -362,6 +362,12 @@ impl Interp { Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { self.write_host_ref(&Data::Object(items))? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, Data::String(_))] if k == crate::FILE_REF_KEY) => { + match items.as_slice() { + [(_, Data::String(path))] => self.write_file_ref(path)?, + _ => Value::Undefined, + } + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 45f6aa61e4..84a6401f55 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -81,7 +81,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use file_classes::{FILE_REF_KEY, file_ref_path}; +pub use file_classes::{FILE_REF_KEY, file_ref, file_ref_path}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; diff --git a/docs/mcp.md b/docs/mcp.md index 6de9cf9859..0da6d93d43 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2726,6 +2726,30 @@ app through the global object `vc`, and writes to the Script Console and runs ot an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. +- `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked + images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones, + in paint order, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` + gives a `PlacedItem` with no file; assigning a `File` to its `file` runs `file.place` with `link: true`, and every + other member of it throws `PlacedItem.file is required` until then. A `PlacedItem` + (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/) has `file`, `relink(file)` (`links.relink`), `embed()` + (`links.embed`), `matrix` and `boundingBox`. A `RasterItem` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/) + has `bitsPerChannel`, `channels`, `imageColorSpace` and `transparent`, read from the header of its encoded pixels, + and `colorizedGrayscale`, `embedded`, `file`, `status`, `matrix` and `boundingBox`. The enumeration values are + strings such as `"ImageColorSpace.Grayscale"` and `"RasterLinkState.NODATA"` + (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). VectorCraft's own rules: `file` is assigned + once, on a `placedItems.add()` result, and is read-only after (`PlacedItem.file is read-only: use relink`). A file + to place or relink must be a `File` the script may read, checked as `app.open` checks its file, of at most + 256 MiB, holding an image; its size is read before its contents, and anything else throws an error with nothing + changed (`Script file access denied` names no path). Reading `file` of an image whose file the script may not read + throws `Script file access denied`. After `embed()` the object is stale and `rasterItems` has the image under the + same id; an image whose file is missing throws `Linked image is missing` and stays linked. `RasterItem.file` is + `null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true + for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY` + that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning + `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of + the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point + a pixel. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the + end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0f5208319d..636c828ea4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Tracing, rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From dd35352874a29bb8358b5a06c5353b040a6665a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 16:12:11 -0800 Subject: [PATCH 02/41] Scripts: an embedded image's held PlacedItem stays stale and the raster item is a new object A read of a host class on another branch of the same family with the same handle makes a new object instead of switching the held object's class. A class and its ancestors and descendants still share one object, so a placed image read through placedItems and through pageItems is the same object, and each branch's held object keeps its identity on later reads. After p.embed() or links.embed, reading rasterItems or pageItems gives a new RasterItem object, and the PlacedItem object the script held throws Stale page item. --- crates/engine/src/tests/script_dom.rs | 7 +- crates/engine/src/tests/script_dom_images.rs | 18 +++++ crates/js/src/host_classes.rs | 69 +++++++++++++++----- crates/js/src/host_tests.rs | 24 +++++++ crates/js/src/interp.rs | 6 +- docs/mcp.md | 4 +- 6 files changed, 105 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..5bf276e3b9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -619,7 +619,7 @@ fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { } #[test] -fn a_held_image_stays_the_same_object_when_it_is_embedded() { +fn a_held_image_is_stale_when_it_is_embedded() { let dir = super::links::Folder::new("dom-embed"); let photo = dir.file("photo.png"); super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); @@ -629,11 +629,12 @@ fn a_held_image_stays_the_same_object_when_it_is_embedded() { &mut s, &format!( "var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\ - var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);", + var j = app.activeDocument.pageItems[0], m = ''; try {{ i.typename; }} catch (e) {{ m = e.message; }}\ + vc.log([i === j, m, j.typename, j instanceof RasterItem, i instanceof PlacedItem]);", id.0 ), ); - assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]); + assert_eq!(out, vec![json!("PlacedItem"), json!([false, "Stale page item", "RasterItem", true, true])]); } #[test] diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 6b3f3d3cac..a498a0244c 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -278,6 +278,24 @@ fn embed_reclassifies_and_stales_wrapper() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn embed_gives_raster_item_a_new_object() { + let base = folder("embed-new"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], q = d.pageItems[0]; vc.log(p === q); p.embed();\ + var r = d.rasterItems[0]; vc.log(p === r); vc.log(r.typename); vc.log(d.pageItems[0] === r); var m = '';\ + try { p.name; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(true), json!(false), json!("RasterItem"), json!(true), json!("Stale page item")]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn missing_link_embed_reports_error() { let base = folder("missing"); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..67a44b9872 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -9,8 +9,9 @@ //! of a host class from its own data. A class's prototype and constructor are frozen. While a //! script holds the object for a class and handle, each read of that class and handle gives the //! same object. Classes that descend from the same class without a parent share their objects: a -//! read of another of them with the same handle gives the object the script holds, now of the -//! class that read names. +//! read of an ancestor or descendant of the held object's class with the same handle gives the +//! object the script holds, now of the class that read names. A read of a class on another branch +//! gives a new object, and the held object keeps its class. //! //! Every member function gets the object it is called on (`this`) as its first argument, or //! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a @@ -72,6 +73,20 @@ pub(crate) struct Entry { /// The class without a parent this class descends from (itself for such a class), as an index /// into the realm's classes. family: u32, + /// The class's parent, as an index into the realm's classes. + parent: Option, +} + +/// Whether class `a` is class `b` or descends from it, both indexes into `classes`. +fn descends(classes: &[Entry], a: u32, b: u32) -> bool { + let mut at = Some(a); + while let Some(c) = at { + if c == b { + return true; + } + at = classes.get(c as usize).and_then(|e| e.parent); + } + false } impl Entry { @@ -83,8 +98,9 @@ impl Entry { /// A family of classes ([`Entry::family`]) and the bits of a handle. type MadeKey = (u32, Box<[u64]>); -/// The object made for each family of classes and handle ([`Interp::host_objects`]). -pub(crate) type Made = std::collections::HashMap; +/// The objects made for each family of classes and handle ([`Interp::host_objects`]), one for each +/// branch of the family a read named, oldest first. +pub(crate) type Made = std::collections::HashMap>; /// Whether `id` is still the object made for `key`, and not a freed cell or another object that /// was given its cell. @@ -99,7 +115,10 @@ fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey /// Drops the entries of `made` whose objects the last collection freed. pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) { - made.retain(|key, id| is_made(heap, classes, *id, key)); + made.retain(|key, ids| { + ids.retain(|id| is_made(heap, classes, *id, key)); + !ids.is_empty() + }); } /// The [`Data`] that stands for the object of host class `class` with `handle`. @@ -142,10 +161,24 @@ impl Interp { let (proto, family) = (entry.proto, entry.family); let class = u32::try_from(class).unwrap_or(u32::MAX); let made = (family, handle.iter().map(|n| n.to_bits()).collect::>()); - if let Some(&id) = self.host_objects.get(&made) - && is_made(&self.heap, &self.host_classes, id, &made) - { - // An object of another class of the family becomes one of `class`. + // The held object of `class` itself, or else the newest of an ancestor or descendant class, + // which becomes one of `class`. An object of a class on another branch of the family keeps + // its class, and a read of `class` with no such object gives a new object. + let mut found = None; + for &id in self.host_objects.get(&made).map(Vec::as_slice).unwrap_or_default() { + if !is_made(&self.heap, &self.host_classes, id, &made) { + continue; + } + let Class::Host(h) = &self.object(id)?.class else { continue }; + if h.class == class { + found = Some(id); + break; + } + if descends(&self.host_classes, h.class, class) || descends(&self.host_classes, class, h.class) { + found = Some(id); + } + } + if let Some(id) = found { let o = self.object_mut(id)?; if let Class::Host(h) = &mut o.class && h.class != class @@ -159,7 +192,13 @@ impl Interp { let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); - self.host_objects.insert(made, id); + if let Some(ids) = self.host_objects.get_mut(&made) { + let (heap, classes) = (&self.heap, &self.host_classes); + ids.retain(|&old| old != id && is_made(heap, classes, old, &made)); + ids.push(id); + } else { + self.host_objects.insert(made, vec![id]); + } Ok(Value::Object(id)) } @@ -223,10 +262,10 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); - let (parent, family) = match &class.parent { - None => (i.intrinsics.object_proto, own), - Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => (e.proto, e.family), + let (parent, family, parent_class) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((at, e)) => (e.proto, e.family, u32::try_from(at).ok()), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; @@ -236,7 +275,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family, parent: parent_class }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..13aa5f8560 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -661,6 +661,30 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +#[test] +fn a_read_of_a_class_on_another_branch_gives_a_new_object() { + let mut r = realm(1_000_000); + let class = |name: &str, parent: Option<&str>| HostClass { + name: name.into(), + parent: parent.map(Into::into), + members: Vec::new(), + index: None, + construct: None, + }; + let get: HostFunction = Rc::new(|a| match a.get(1) { + Some(Data::String(name)) => Ok(host_ref(name, &[1.0])), + _ => Ok(Data::Null), + }); + let mut maker = class("Maker", None); + maker.members.push(("get".into(), HostMember::Method(get))); + let classes = vec![class("Base", None), class("Left", Some("Base")), class("Right", Some("Base")), class("Leaf", Some("Left")), maker]; + r.define_host_classes(classes, vec![("maker".into(), host_ref("Maker", &[]))]).unwrap(); + let script = "function get(n) { return maker.get(n); } var l = get('Left'), b = get('Base'), f = get('Leaf'); var r = get('Right'); \ + [l === b, b === f, f instanceof Leaf, r === l, r instanceof Right, l instanceof Leaf, get('Leaf') === l, \ + get('Right') === r, get('Base') === r].join()"; + assert_eq!(r.run(script).unwrap(), JsValue::String("true,true,true,false,true,true,true,true,true".into())); +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 63e6251dd7..2ee18f4cc1 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -257,9 +257,9 @@ pub(crate) struct Interp { pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. pub(crate) write_hosted: bool, - /// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of - /// the same one give the same object. It is not a root: an entry whose object was collected is - /// dropped after each collection. + /// The objects made for each family of classes and handle ([`crate::host_classes`]), so that two reads of + /// the same one give the same object. It is not a root: an object that was collected is dropped + /// after each collection. pub(crate) host_objects: crate::host_classes::Made, /// The clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, diff --git a/docs/mcp.md b/docs/mcp.md index 0da6d93d43..1c4b23e213 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2659,8 +2659,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `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 - `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the - same object when the image is embedded: the next read gives that object, now a `RasterItem`. The + `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. When a placed image is embedded, an + object a script holds for it is stale, and the next read gives a new `RasterItem` object. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. From 15153de8491f7f58b64447dbb5570fbaf1e9d394 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:56:25 -0800 Subject: [PATCH 03/41] Scripts: members not available yet on placed and raster items check the item first Reading or assigning PlacedItem.trace or contentVariable, or RasterItem.colorants, colorize, contentVariable, overprint or trace, now throws Stale page item for a removed or embedded item and PlacedItem.file is required for an unbound PlacedItems.add() result, as the PageItem members already do, before the not available yet error. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/tests/script_dom_images.rs | 21 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cd96ea46c5..18a394c125 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -170,7 +170,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "PlacedItem" | "RasterItem" => { item_of(&h, arg(&a, 0))?; } _ => {} diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index a498a0244c..674d098eb5 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -431,3 +431,24 @@ fn stale_and_foreign_placed_items_are_refused() { assert!(s.active().unwrap().doc.node(id).is_none()); let _ = std::fs::remove_dir_all(base); } + +#[test] +fn members_not_available_yet_check_the_image_first() { + let base = folder("later"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ + try { n.trace; } catch (e) { m.push(e.message); }\ + p.embed(); try { p.trace; } catch (e) { m.push(e.message); }\ + var r = d.rasterItems[0]; try { r.colorize; } catch (e) { m.push(e.message); }\ + r.remove(); try { r.overprint; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "RasterItem.colorize is not available yet", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} From dc7d5ccfd77f9ec869b6cbb23fc03ca37d0d26ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:29:28 -0800 Subject: [PATCH 04/41] Tests: the script host name tables list the placed and raster item names PlacedItem and RasterItem leave the bare classes, and the tables list Document.placedItems and rasterItems, the PlacedItems, RasterItems, PlacedItem and RasterItem members, and the ImageColorSpace and RasterLinkState enumerations. PlacedItem.file= and relink read the image file they are given, so they stay inside the document. --- .../tests/it/script_host_vs_scriptcheck.rs | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a0794be35c..931023a427 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -44,7 +44,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.close` throws "not available yet". `app.open` reads the file it is given. +/// documents; `Document.close` throws "not available yet". `app.open` reads the file it is given, +/// and `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -77,7 +78,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + PageItems PlacedItem PlacedItems RasterItem RasterItems RulerUnits ZOrderMethod", ), ("Application.", "prototype"), ( @@ -99,8 +100,8 @@ const INSIDE: &[(&str, &str)] = &[ ( "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= placedItems rasterItems \ + rulerOrigin rulerOrigin= rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -117,6 +118,19 @@ const INSIDE: &[(&str, &str)] = &[ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("PlacedItems.", "prototype"), + ("PlacedItems.prototype.", "add constructor getByName index length parent removeAll typename"), + ("PlacedItem.", "prototype"), + ("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace trace="), + ("RasterItems.", "prototype"), + ("RasterItems.prototype.", "constructor getByName index length parent removeAll typename"), + ("RasterItem.", "prototype"), + ( + "RasterItem.prototype.", + "bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \ + contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \ + trace trace= transparent", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), @@ -145,12 +159,16 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of placed and raster items. + ("", "ImageColorSpace RasterLinkState"), + ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), + ("RasterLinkState.", "DATAFROMFILE DATAMODIFIED NODATA"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types /// and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ + PlacedDocumentItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's From bbc85020e0c30be72a7dc0ede143f69ef078e596 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:51:00 -0800 Subject: [PATCH 05/41] Scripts: PlacedItem.file checks the script's own read scope, not open documents Reading file of a placed image linked to a file outside the script's read scope throws Script file access denied even when that file is also open as a document, whose file the script's commands may read. --- crates/engine/src/script/dom/images.rs | 6 +++--- crates/engine/src/tests/script_dom_images.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index bf79f77013..dc5417c318 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -289,10 +289,10 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer { // ---- files ---- -/// Whether the script's commands may read `path` now ([`crate::file_access::ScriptGate`]). +/// Whether the script may read `path` now by its own read scope and the read roots +/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read. fn may_read(h: &Host, path: &str) -> bool { - let documents = h.session.borrow().documents().iter().filter_map(|d| d.path.clone()).collect(); - let gate = h.disk.borrow().gate(documents); + let gate = h.disk.borrow().gate(Vec::new()); crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok() } diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 674d098eb5..1c1a78d864 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -411,6 +411,20 @@ fn image_file_getter_hides_out_of_scope_link() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() { + let base = folder("hidedoc"); + let b = base.join("outside/secret.png"); + std::fs::write(&b, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &b, true); + // The linked file is also the file of an open document, which the script's commands may read. + s.doc_mut().unwrap().path = Some(b.to_string_lossy().into_owned()); + let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);"); + assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn stale_and_foreign_placed_items_are_refused() { let base = folder("stale"); From f0a1e6398f0a1cdb2da853085e79b28ffd02a258 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:04:35 -0800 Subject: [PATCH 06/41] Scripts: image removeAll keeps art on a locked artboard; setters check the item first placedItems.removeAll() and rasterItems.removeAll() checked only whether each image and its layers and groups were shown and unlocked, then passed the ids to edit.clear, which deletes named objects without checking artboard locks. Both now throw "cannot delete objects on a locked artboard" with the image ids and delete nothing, as pageItems.removeAll() does. Assigning matrix read the value before the item, so a stale image or an add() result without a file threw the matrix error. Assigning file to an add() result that was placed and then embedded threw "PlacedItem.file is read-only: use relink". Both now check the item first and throw "Stale page item" or "PlacedItem.file is required". A File that a host class member returns now charges its new path string to the script heap, in the same reservation as the File object. docs/gaps.md G6 and the M13 row in docs/roadmap.md list the placed and raster image classes; docs/mcp.md states the removeAll and setter rules. --- crates/engine/src/script/dom/images.rs | 21 +++++--- crates/engine/src/tests/script_dom_images.rs | 56 ++++++++++++++++++++ crates/js/src/file_classes.rs | 17 ++++-- crates/js/src/host_tests.rs | 18 +++++++ docs/gaps.md | 3 +- docs/mcp.md | 5 +- docs/roadmap.md | 2 +- 7 files changed, 110 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index dc5417c318..25aaaaa0ad 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -40,8 +40,9 @@ use vectorcraft_geom::{Affine, Point}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; use super::{ - Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, editable, find_doc, - float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, with_doc, + Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, + editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, + with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -218,19 +219,26 @@ fn list_index(h: &Host, a: &[Data], placed: bool) -> Answer { } /// `removeAll()`: deletes every image of the collection in one command. A hidden or locked one, or -/// one in a hidden or locked layer or group, stops it before anything is deleted. +/// one in a hidden or locked layer or group, stops it before anything is deleted, and so does one on +/// a locked artboard. fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer { let doc = list_doc(h, a, placed)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = images(h, st, placed)?; let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused)) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused, on_locked)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {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::>()})))?; } @@ -374,6 +382,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { }; let k = slot_of(h, run, uid, slot)?; if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_some()) { + this_of(h, a, "PlacedItem")?; return Err(HostError::Error(FILE_READ_ONLY.into())); } let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -469,8 +478,8 @@ fn area_of(m: Affine) -> bool { /// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted /// image is refused before anything changes; the matrix the image has already changes nothing. fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { - let m = matrix_value(arg(a, 1))?; let item = this_of(h, a, cls)?; + let m = matrix_value(arg(a, 1))?; let delta = with_doc(h, item.doc, |_, st| { let Some((n, im)) = st.doc.node(item.id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some((n, im)) } else { None }) else { return Err(HostError::Error(STALE_ITEM.into())); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 1c1a78d864..594582e9f9 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -425,6 +425,62 @@ fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() { let _ = std::fs::remove_dir_all(base); } +/// Assigning `file` or `matrix` checks the item before the value: an `add()` result with no file +/// throws `PlacedItem.file is required`, and one that was embedded throws `Stale page item`. +#[test] +fn assignments_check_the_item_before_the_value() { + let base = folder("receiver"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, n = d.placedItems.add(), p = d.placedItems.add(), m = [];\ + try {{ n.matrix = null; }} catch (e) {{ m.push(e.message); }}\ + p.file = new File('{0}'); p.embed();\ + try {{ p.file = new File('{0}'); }} catch (e) {{ m.push(e.message); }}\ + try {{ p.matrix = null; }} catch (e) {{ m.push(e.message); }}\ + try {{ d.rasterItems[0].matrix = null; }} catch (e) {{ m.push(e.name); }}\ + vc.log(m);", + js_path(&a) + ), + ); + assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "Stale page item", "TypeError"])]); + let _ = std::fs::remove_dir_all(base); +} + +/// `removeAll()` deletes no image when one is on a locked artboard, in both collections. +#[test] +fn remove_all_keeps_images_on_a_locked_artboard() { + let base = folder("locked-board"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let linked = place(&mut s, &a, true); + let embedded = place(&mut s, &a, false); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, &base, "app.activeDocument.placedItems.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", linked.0)), "{e}"); + let e = failure(&mut s, &base, "app.activeDocument.rasterItems.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", embedded.0)), "{e}"); + assert_eq!(images(&s).len(), 2); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + let out = log(&mut s, &base, "var d = app.activeDocument; d.placedItems.removeAll(); d.rasterItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn stale_and_foreign_placed_items_are_refused() { let base = folder("stale"); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index b6bf5a3388..cb5d838b3f 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -195,10 +195,20 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult JsResult { + new_instance(i, proto, fs, false) +} + +/// [`instance`], which also charges the heap for the string of `fs` when `charge_path` is set, for +/// a path string made for the new object alone. +fn new_instance(i: &mut Interp, proto: ObjId, fs: Value, charge_path: bool) -> JsResult { let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) }; let line_feed = host_value(i, "lineFeed")?; i.rooted(&[fs, line_feed.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?; + let path_bytes = string_bytes(path.len()); + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + path_bytes)?; + if charge_path { + i.heap.bytes = i.heap.bytes.saturating_add(path_bytes); + } let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto))); i.rooted(&[Value::Object(o)], |i| { set_slot(i, o, ERROR, Value::str(""))?; @@ -1153,10 +1163,11 @@ pub fn file_ref(path: &str) -> crate::Data { } impl Interp { - /// A new `File` for `path`, which a member of a host class gave ([`file_ref`]). + /// A new `File` for `path`, which a member of a host class gave ([`file_ref`]). The new string + /// of the path is charged to the heap, as [`crate::Data::String`] is when it is written. pub(crate) fn write_file_ref(&mut self, path: &str) -> JsResult { let proto = classes(self)?.file_proto; - instance(self, proto, Value::str(path)) + new_instance(self, proto, Value::str(path), true) } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 13aa5f8560..c7190dc726 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -685,6 +685,24 @@ fn a_read_of_a_class_on_another_branch_gives_a_new_object() { assert_eq!(r.run(script).unwrap(), JsValue::String("true,true,true,false,true,true,true,true,true".into())); } +/// The path of a `File` a member of a host class gives is charged to the heap. +#[test] +fn the_path_of_a_file_a_host_class_gives_is_charged_to_the_heap() { + let bytes_after = |len: usize| { + let mut r = realm(1_000_000); + let current: HostFunction = Rc::new(|_| Ok(Data::String("d".into()))); + r.define_file_classes(vec![("current".into(), HostItem::Function(current))]).unwrap(); + let file: HostFunction = Rc::new(move |_| Ok(file_ref(&"p".repeat(len)))); + let members = vec![("file".to_string(), HostMember::Method(file))]; + let maker = HostClass { name: "Maker".into(), parent: None, members, index: None, construct: None }; + r.define_host_classes(vec![maker], vec![("maker".into(), host_ref("Maker", &[]))]).unwrap(); + assert_eq!(r.run("var f = maker.file(); f instanceof File"), Ok(JsValue::Bool(true))); + r.interp().heap.bytes + }; + let (short, long) = (bytes_after(1), bytes_after(100_000)); + assert!(long >= short + 2 * 99_999, "{short} {long}"); +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..fc32f5b719 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + documents, each document's selection and its page items, and its linked and embedded images (`placedItems` and + `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 98735f67e2..27b004237d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2751,7 +2751,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point - a pixel. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the + a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete + objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the + item before the value, so a stale item throws `Stale page item` and an `add()` result without a file throws + `PlacedItem.file is required` whatever the value. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..1e4ca34d9b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, and its linked and embedded images (`PlacedItem` and `RasterItem`); the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 91bd652bd707accb87e902f3f53169311c305a20 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:43:47 -0800 Subject: [PATCH 07/41] Docs: placed image file assignment places the image on an add() result Assigning `file` to a `placedItems.add()` result without a file checks the file and places the image; only assigning `matrix` to such a result throws `PlacedItem.file is required`. A stale item throws `Stale page item` for both setters. --- docs/mcp.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 27b004237d..72826fb91d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2753,9 +2753,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the - item before the value, so a stale item throws `Stale page item` and an `add()` result without a file throws - `PlacedItem.file is required` whatever the value. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the - end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. + item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` + result without a file throws `PlacedItem.file is required` whatever the value, and assigning `file` to one checks + the file and places the image. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a + file is dropped at the end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not + available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global From 022d0ce7e886bc698e43b2a5389e6277f48b8cd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:14:32 -0800 Subject: [PATCH 08/41] Scripts: PlacedItem.trace and RasterItem.trace make an Image Trace object with its tracing options `PlacedItem.trace()` and `RasterItem.trace()` run `imageTrace.make` with the Default preset and return the Image Trace object as a `PluginItem`. Its `tracing` is a `TracingObject` with the source image, the path, anchor and color counts, the image's resolution, `expandTracing()`, `releaseTracing()` and a `TracingOptions` object. Assigning an option or loading a preset traces the image again, keeping its source image and view; a value the tracing already has runs no command. Option values are checked for type and range before any trace, and nothing changes when one is refused. Options with no VectorCraft setting and `expandTracing(true)` throw. `storeToPreset` returns `false` for a built-in preset name or `Custom` and throws for any other name. A tracing that was expanded, released, deleted or traced again by a command is stale. The source image is reached through `sourceArt` and is not listed in `pageItems`, `placedItems` or `rasterItems`, and the name of a tracing cannot be changed from a script. With a script running, `imageTrace.make` stops at the run's stop request. Setting `File.hidden` stores the new path with `set_path`, since the path is held in the object's class on this branch. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd.rs | 4 + crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/trace.rs | 24 +- crates/engine/src/script/dom.rs | 33 +- crates/engine/src/script/dom/images.rs | 4 +- crates/engine/src/script/dom/tracing.rs | 741 ++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 4 +- crates/engine/src/tests/script_dom_tracing.rs | 541 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 33 +- crates/js/src/file_classes.rs | 2 +- docs/mcp.md | 33 +- docs/target-app-parity.md | 3 +- 13 files changed, 1404 insertions(+), 21 deletions(-) create mode 100644 crates/engine/src/script/dom/tracing.rs create mode 100644 crates/engine/src/tests/script_dom_tracing.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..170c0b4b2b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -921,6 +921,10 @@ pub use buildcmds::{TraceRun, Traced, image_trace_target}; /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; +/// Whether an object is an Image Trace object, the source image of one, or the seam fills group in +/// one. +pub(crate) use buildcmds::{is_seam_fills, is_trace_group, is_trace_source}; + /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 692545d828..4ad46157aa 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -41,10 +41,10 @@ pub use live_paint::live_paint_gaps; pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation}; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_copy_region, sb_merge, sb_regions}; -pub(crate) use trace::TracePresetChanges; pub use trace::{ TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target, }; +pub(crate) use trace::{TracePresetChanges, is_seam_fills, is_trace_group, is_trace_source}; use trace::{ trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view, }; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index c3e7a84296..14a6ac10e2 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -17,12 +17,17 @@ thread_local! { // ---------- Image Trace ---------- -fn is_trace_group(n: &Node) -> bool { +pub(crate) fn is_trace_group(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some(TRACE_NAME) && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } +/// Whether object `id` of `d` is the source image an Image Trace object keeps as its first child. +pub(crate) fn is_trace_source(d: &Document, id: NodeId) -> bool { + d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id)) +} + /// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]). const SEAM_FILLS_NAME: &str = "Seam Fills"; @@ -32,7 +37,7 @@ const SEAM_FILLS_NAME: &str = "Seam Fills"; /// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made /// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one /// of stroked paths without fills. (Auto Grouping groups hold filled paths.) -fn is_seam_fills(n: &Node) -> bool { +pub(crate) fn is_seam_fills(n: &Node) -> bool { let path = |m: &Arc| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); let stroke_only = |m: &Arc| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None; let fill_only = |m: &Arc| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None; @@ -774,8 +779,12 @@ pub fn image_trace_target(s: &Session, p: &Value) -> Result { fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box)> { let roots = root_ids(s, p)?; let d = &s.doc()?.doc; + // The source image an Image Trace object keeps is traced through that object, so it is never + // the object traced, and naming only such images is an error. + let source = |r: &NodeId| is_trace_source(d, *r); roots .iter() + .filter(|r| !source(r)) .find_map(|r| { let n = d.node(*r)?; match &n.kind { @@ -787,7 +796,10 @@ fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box None, } }) - .ok_or_else(|| bad(c, "select an image (or an Image Trace group)")) + .ok_or_else(|| match roots.iter().find(|r| source(r)) { + Some(r) => bad(c, format!("object {} is the source image of an Image Trace object: trace that object", r.0)), + None => bad(c, "select an image (or an Image Trace group)"), + }) } /// What command `c` with params `p` traces, and how, from the session: everything but the trace. @@ -1076,10 +1088,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result traced, - _ => trace_now(&inputs, &trace, &|_, _| true)?, + _ => trace_now(&inputs, &trace, &|_, _| stop.as_ref().is_none_or(|i| !i.is_set()))?, }; let TraceInputs { target, image: img, .. } = inputs; let mut warnings = keep_warnings(&trace, &res); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 18a394c125..87f348a24c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -40,11 +40,14 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod images; mod save_open; +mod tracing; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. pub const STALE_ITEM: &str = "Stale page item"; +/// The error for a new name given to a `PluginItem`. +const TRACING_NAME: &str = "The name of a tracing cannot be changed"; /// The error for a document that was closed, or that came from an earlier run. pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. @@ -74,6 +77,7 @@ const ITEM_CLASSES: &[&str] = &[ "RepeatItem", "PlacedDocumentItem", "IntertwineItem", + "PluginItem", ]; /// `app.coordinateSystem`. @@ -100,6 +104,8 @@ pub(super) struct State { presets: RefCell>>, /// What the placed and raster items keep ([`images::State`]). images: images::State, + /// What the tracings keep ([`tracing::State`]). + tracing: tracing::State, } impl State { @@ -303,6 +309,7 @@ fn item_of(h: &Host, d: &Data) -> std::result::Result { }; let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id }; let s = h.session.borrow(); let st = &s.documents()[doc.index]; if st.doc.node(id).is_none_or(|n| typename(n) != Some(class)) { @@ -316,6 +323,7 @@ fn typename(n: &crate::doc::Node) -> Option<&'static str> { Some(match &n.kind { NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } if crate::cmd::is_trace_group(n) => "PluginItem", NodeKind::Group { .. } => "GroupItem", NodeKind::Path { .. } => "PathItem", NodeKind::Compound { .. } => "CompoundPathItem", @@ -361,7 +369,10 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { NodeKind::RulerGuide { .. } => {} NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { out.push(n.id); - walk(children, out); + // The source image an Image Trace object keeps hidden as its first child is + // reached through that object's `tracing`. + let source = usize::from(crate::cmd::is_trace_group(n)); + walk(children.get(source..).unwrap_or_default(), out); } _ => out.push(n.id), } @@ -391,9 +402,11 @@ fn top_items(d: &Document) -> Vec { out } -/// Whether `n` and every object inside it are shown and unlocked. +/// Whether `n` and every object inside it are shown and unlocked. The source image an Image Trace +/// object keeps hidden as its first child is part of that object and is not counted. fn all_editable(n: &crate::doc::Node) -> bool { - n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c))) + let source = usize::from(crate::cmd::is_trace_group(n)); + n.visible && !n.locked && n.children().is_none_or(|c| c.iter().skip(source).all(|c| all_editable(c))) } /// Whether the object and every layer and group it is in are shown and unlocked. @@ -1336,6 +1349,13 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer { if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } + // An Image Trace object is known by its name, so renaming one would end the tracing. + let item = this_item(h, a)?; + let tracing = + with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| crate::cmd::is_trace_group(n) && n.name.as_deref() != Some(&**name))); + if tracing { + return Err(HostError::Error(TRACING_NAME.into())); + } set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) } @@ -1818,7 +1838,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1945,8 +1965,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().filter(|c| !images::CLASSES.contains(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None))); + let own = |c: &&&str| images::CLASSES.contains(c) || tracing::CLASSES.contains(c); + classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None))); classes.extend(images::classes(l)); + tracing::add_trace(&mut classes, l); + classes.extend(tracing::classes(l)); classes.extend(save_open::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index dc5417c318..00303f2975 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -649,7 +649,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("matrix", property(l, placed_matrix, placed_set_matrix)), ("boundingBox", get(l, placed_box)), ]); - placed.extend(["contentVariable", "trace"].into_iter().map(|m| later(l, "PlacedItem", m))); + placed.push(later(l, "PlacedItem", "contentVariable")); let mut raster = named(vec![ ("bitsPerChannel", get(l, raster_bits)), ("channels", get(l, raster_channels)), @@ -662,7 +662,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("transparent", get(l, raster_transparent)), ("boundingBox", get(l, raster_box)), ]); - raster.extend(["colorants", "colorize", "contentVariable", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); + raster.extend(["colorants", "colorize", "contentVariable", "overprint"].into_iter().map(|m| later(l, "RasterItem", m))); vec![ class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs new file mode 100644 index 0000000000..f8642f3b7d --- /dev/null +++ b/crates/engine/src/script/dom/tracing.rs @@ -0,0 +1,741 @@ +//! Tracing in the script object model: `PlacedItem.trace()` and `RasterItem.trace()`, the +//! `PluginItem` an Image Trace object is, its `TracingObject` and its `TracingOptions`, as the help +//! pages , +//! and +//! describe them. +//! +//! An Image Trace object is a group that holds its source image, hidden, as its first object. +//! Tracing runs `imageTrace.make`, expanding `imageTrace.expand`, releasing `imageTrace.release` +//! and a change of view `imageTrace.setView`, so each joins the run's transaction and its work +//! counts against the run's limits. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `trace()` returns once the trace is made, so the counts can be read at once. It traces with +//! the Default preset. +//! - The traced image stays the same object: `sourceArt` gives it, and `releaseTracing()` gives it +//! back. `trace()` on an image that is the source of a tracing throws [`ALREADY_TRACED`], and on +//! a linked image whose file is missing throws `Linked image is missing`. +//! - `pathCount` counts the traced paths, without the seam fills an Abutting trace adds, +//! `anchorCount` their anchor points and `usedColorCount` the different paints they are filled +//! and stroked with, as the tracing is when they are read. `areaCount` throws. `imageResolution` +//! is the source image's pixels per inch as it is placed; an image placed at a different +//! resolution across and down has none. +//! - Assigning an option, or `loadFromPreset(name)`, traces again unless the options are already +//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its +//! `TracingOptions` follow it. A tracing that another command traced again, expanded or +//! released, or whose source image was deleted, is stale. +//! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or +//! `"Document Library"`. `minArea` is the Noise setting in pixels: an area smaller than it is not +//! traced. `tracingMode` has no value for the Flat Logo mode. The options with no VectorCraft +//! setting throw [`not_implemented`]. +//! - `viewRaster` and `viewVector` take only the pairs of the Image Trace views +//! ([`VIEWS`]); the Split view has neither. +//! - `storeToPreset(name)` gives `false` for a built-in preset and `Custom`; a script cannot change +//! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`] +//! bytes and none of `/`, `\`, `:` or control characters. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; + +use super::{ + Answer, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, find_doc, float, get, id_of, item_of, item_ref, + method, named, num, number, on_doc, property, text, typename_of, whole, with_doc, +}; +use crate::doc::{Node, TraceView}; +use crate::{NodeId, NodeKind}; + +/// The error of `trace()` on an image that is the source of a tracing. +pub const ALREADY_TRACED: &str = "The image is the source art of a tracing"; +/// The error of options that trace with neither fills nor strokes. +pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes"; +/// The error of `expandTracing(true)`. +pub const VIEWED_EXPAND: &str = "TracingObject.expandTracing(true) is not implemented"; +/// The longest preset name `loadFromPreset` and `storeToPreset` take, in bytes. +pub const MAX_PRESET_NAME: usize = 256; +/// The most times one run traces a tracing again through its options. +pub const MAX_RETRACES: usize = 10_000; +/// The largest `minArea`: the most pixels the tracer traces ([`vectorcraft_trace::MAX_PIXELS`]). +pub const MAX_MIN_AREA: u64 = vectorcraft_trace::MAX_PIXELS; + +/// The enumerations the members here give values of, as the help page +/// lists them. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("TracingModeType", &["TRACINGMODEBLACKANDWHITE", "TRACINGMODECOLOR", "TRACINGMODEGRAY"]), + ( + "ViewRasterType", + &["TRACINGVIEWRASTERADJUSTEDIMAGE", "TRACINGVIEWRASTERNOIMAGE", "TRACINGVIEWRASTERORIGINALIMAGE", "TRACINGVIEWRASTERTRANSPARENTIMAGE"], + ), + ( + "ViewVectorType", + &["TRACINGVIEWVECTORNOTRACINGRESULT", "TRACINGVIEWVECTOROUTLINES", "TRACINGVIEWVECTOROUTLINESWITHTRACING", "TRACINGVIEWVECTORTRACINGRESULT"], + ), +]; + +/// The classes this module defines. +pub(super) const CLASSES: &[&str] = &["PluginItem"]; + +/// Each Image Trace view with the `viewRaster` and `viewVector` that give it. +const VIEWS: &[(TraceView, &str, &str)] = &[ + (TraceView::Result, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"), + (TraceView::ResultWithOutlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINESWITHTRACING"), + (TraceView::Outlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"), + (TraceView::OutlinesWithSource, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"), + (TraceView::Source, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTORNOTRACINGRESULT"), +]; + +/// Each `tracingMode` with its Image Trace mode. +const MODES: &[(&str, &str)] = &[ + ("TracingModeType.TRACINGMODEBLACKANDWHITE", "blackAndWhite"), + ("TracingModeType.TRACINGMODEGRAY", "grayscale"), + ("TracingModeType.TRACINGMODECOLOR", "color"), +]; + +/// Each `palette` name with its Image Trace palette. +const PALETTES: &[(&str, &str)] = &[("", "automatic"), ("Limited", "limited"), ("Full Tone", "fullTone"), ("Document Library", "documentLibrary")]; + +/// The options with no VectorCraft setting. +const NOT_IMPLEMENTED: &[&str] = &[ + "cornerAngle", + "livePaintOutput", + "maxStrokeWeight", + "minStrokeLength", + "outputToSwatches", + "pathFitting", + "preprocessBlur", + "resample", + "resampleResolution", +]; + +/// What a run keeps for tracings: for each document uid and Image Trace object a script traced +/// again through its options, the id of the object that replaced it. +#[derive(Default)] +pub(super) struct State { + next: RefCell>, +} + +/// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put +/// it back put back the same object), else the Image Trace object that replaced it when this run +/// traced it again, else `id`. +pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { + let held = h.session.borrow().documents().iter().find(|d| d.uid == uid).is_some_and(|d| d.doc.node(id).is_some()); + if held { + return id; + } + h.dom.tracing.next.borrow().get(&(uid, id.0)).map_or(id, |n| NodeId(*n)) +} + +/// Records that `new` replaced `old` in the document `uid`: every object that led to `old` leads to +/// `new` now. +fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { + let mut next = h.dom.tracing.next.borrow_mut(); + for ((u, _), to) in next.iter_mut() { + if *u == uid && *to == old.0 { + *to = new.0; + } + } + next.insert((uid, old.0), new.0); +} + +/// The error of a member with no VectorCraft setting. +pub fn not_implemented(class: &str, name: &str) -> String { + format!("{class}.{name} is not implemented") +} + +fn out_of_range(name: &str, range: &str) -> HostError { + HostError::Range(format!("TracingOptions.{name} is out of range: {range}")) +} + +fn invalid(name: &str) -> HostError { + HostError::Error(format!("TracingOptions.{name} has an invalid value")) +} + +fn stale() -> HostError { + HostError::Error(STALE_ITEM.into()) +} + +fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> { + match d { + Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v), + _ => None, + } +} + +/// The first id of a command's result `key`: a number or a list of them, read exactly. +fn result_id(v: &Value, key: &str) -> Option { + match &v[key] { + Value::Array(a) => a.first().and_then(Value::as_u64).map(NodeId), + n => n.as_u64().map(NodeId), + } +} + +/// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject` +/// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document. +fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 4]), HostError> { + let Some((c, handle)) = host_ref_parts(d).filter(|(c, _)| *c == cls) else { + return Err(HostError::Type(format!("this is not a {cls}"))); + }; + let &[run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) }; + let doc = find_doc(h, run, uid).ok_or_else(stale)?; + let id = follow(h, doc.uid, id_of(high, low).ok_or_else(stale)?); + let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::cmd::is_trace_group)); + if !live { + return Err(stale()); + } + Ok((Item { doc, id }, [run, uid, high, low])) +} + +/// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps. +fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 4]), HostError> { + match host_ref_parts(arg(a, 0)) { + Some(("PluginItem", handle)) => { + let item = item_of(h, arg(a, 0))?; + match handle.as_slice() { + &[run, uid, high, low] => Ok((item, [run, uid, high, low])), + _ => Err(HostError::Type("this is not a PluginItem".into())), + } + } + _ => Err(HostError::Type("this is not a PluginItem".into())), + } +} + +/// Reads the Image Trace object of `item` with `f`. +fn read_group(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result) -> Result { + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => f(st, n), + None => Err(stale()), + }) +} + +/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`. +/// The selection stays as it was, with that object in place of `item`. +fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result { + let before = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); + on_doc(h, item.doc.uid, false, |h| { + let (_, r) = command_value(h, id, params)?; + let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?; + let (want, now) = { + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + let mut want: Vec = Vec::new(); + for i in before.iter().map(|i| if *i == item.id { new } else { *i }) { + if st.doc.node(i).is_some() && !want.contains(&i) { + want.push(i); + } + } + (want, st.selection.objects.clone()) + }; + if now != want { + if want.is_empty() { + command(h, "select.none", &json!({}))?; + } else { + command(h, "select.set", &json!({"ids": want.iter().map(|i| i.0).collect::>()}))?; + } + } + Ok(new) + }) +} + +/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its +/// script objects follow the new one. +fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), HostError> { + if h.dom.tracing.next.borrow().len() >= MAX_RETRACES { + return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); + } + params.insert("id".into(), json!(item.id.0)); + let new = replace(h, item, "imageTrace.make", &Value::Object(params), "id")?; + replaced(h, item.doc.uid, item.id, new); + Ok(()) +} + +// ---- PlacedItem and RasterItem ---- + +/// `trace()`: `imageTrace.make` of the image with the Default preset → its `PluginItem`. +fn image_trace(h: &Host, a: &[Data], cls: &str) -> Answer { + let item = match host_ref_parts(arg(a, 0)) { + Some((c, _)) if c == cls => item_of(h, arg(a, 0))?, + _ => return Err(HostError::Type(format!("this is not a {cls}"))), + }; + let (source, linked) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let source = crate::cmd::is_trace_source(d, item.id); + let linked = matches!(d.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some()); + (source, linked) + }); + if source { + return Err(HostError::Error(ALREADY_TRACED.into())); + } + if linked { + let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?; + if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") { + return Err(HostError::Error(super::images::MISSING_LINK.into())); + } + } + let id = replace(h, item, "imageTrace.make", &json!({"id": item.id.0}), "id")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +fn placed_trace(h: &Host, a: &[Data]) -> Answer { + image_trace(h, a, "PlacedItem") +} + +fn raster_trace(h: &Host, a: &[Data]) -> Answer { + image_trace(h, a, "RasterItem") +} + +// ---- PluginItem ---- + +fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer { + plugin_of(h, a)?; + Ok(Data::Bool(true)) +} + +fn plugin_tracing(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = plugin_of(h, a)?; + Ok(host_ref("TracingObject", &handle)) +} + +// ---- TracingObject ---- + +/// What a tracing's counts are made of. +#[derive(Default)] +struct Counts { + paths: u64, + anchors: u64, + colors: u64, + /// The objects looked at. + visited: u64, +} + +fn anchors_of(n: &Node) -> u64 { + match &n.kind { + NodeKind::Path { path, .. } => path.anchor_count() as u64, + _ => n.children().map_or(0, |c| c.iter().map(|m| anchors_of(m)).sum()), + } +} + +/// The traced paths of the Image Trace object `g`, their anchor points and paints: every path +/// and compound path in it but its source image, the seam fills and clipping paths. +fn counts(g: &Node) -> Counts { + let mut c = Counts::default(); + let mut paints = HashSet::new(); + let mut todo: Vec<&Arc> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default(); + while let Some(n) = todo.pop() { + c.visited += 1; + if crate::cmd::is_seam_fills(n) { + continue; + } + match &n.kind { + NodeKind::Path { clipping: true, .. } => {} + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + c.paths += 1; + c.anchors += anchors_of(n); + for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] { + if paint != vectorcraft_color::Paint::None + && let Ok(key) = serde_json::to_string(&paint) + { + paints.insert(key); + } + } + } + _ => todo.extend(n.children().into_iter().flatten()), + } + } + c.colors = paints.len() as u64; + c +} + +/// Reads the counts of the tracing `this` names with `f`. +fn count(h: &Host, a: &[Data], f: fn(&Counts) -> u64) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let c = read_group(h, item, |_, g| Ok(counts(g)))?; + h.charge_call(c.visited)?; + Ok(num(float(f(&c)))) +} + +fn tracing_paths(h: &Host, a: &[Data]) -> Answer { + count(h, a, |c| c.paths) +} + +fn tracing_anchors(h: &Host, a: &[Data]) -> Answer { + count(h, a, |c| c.anchors) +} + +fn tracing_colors(h: &Host, a: &[Data]) -> Answer { + count(h, a, |c| c.colors) +} + +fn tracing_areas(h: &Host, a: &[Data]) -> Answer { + tracing_of(h, arg(a, 0), "TracingObject")?; + Err(HostError::Error(not_implemented("TracingObject", "areaCount"))) +} + +/// `imageResolution`: the source image's pixels per inch, 72 over the size of a pixel in points. +fn tracing_resolution(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + read_group(h, item, |_, g| { + let source = g.children().and_then(|c| c.first()).ok_or_else(stale)?; + let NodeKind::Image(im) = &source.kind else { return Err(stale()) }; + let none = || HostError::Error("the source image has no single resolution".into()); + if source.is_distorted_image() { + return Err(none()); + } + let [xa, xb, ya, yb, ..] = im.xf.as_coeffs(); + let (across, down) = (xa.hypot(xb), ya.hypot(yb)); + if across <= 1e-12 || down <= 1e-12 || (across - down).abs() > 1e-9 * across.max(down) { + return Err(none()); + } + Ok(num(72.0 / across)) + }) +} + +fn tracing_parent(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))) +} + +fn tracing_source(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + read_group(h, item, |st, g| g.children().and_then(|c| c.first()).map(|s| item_ref(h, st, s.id)).ok_or_else(stale)) +} + +fn tracing_options(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(host_ref("TracingOptions", &handle)) +} + +/// `expandTracing(viewed?)`: `imageTrace.expand` → the `GroupItem` that takes the tracing's place. +fn tracing_expand(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::Undefined | Data::Bool(false) => {} + Data::Bool(true) => { + tracing_of(h, arg(a, 0), "TracingObject")?; + return Err(HostError::Error(VIEWED_EXPAND.into())); + } + _ => return Err(HostError::Type("viewed must be true or false".into())), + } + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let id = replace(h, item, "imageTrace.expand", &json!({"ids": [item.id.0]}), "ids")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. +fn tracing_release(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +// ---- TracingOptions ---- + +/// The tracing `this` names, the settings it was traced with, its view and its preset's name. +fn options_of(h: &Host, a: &[Data]) -> Result<(Item, Map, TraceView, String), HostError> { + let (item, _) = tracing_of(h, arg(a, 0), "TracingOptions")?; + read_group(h, item, |_, g| { + let trace = g.extras().trace.as_deref(); + let params = trace.and_then(|t| t.get("params")).and_then(Value::as_object).cloned(); + let params = params.ok_or_else(|| HostError::Error("the tracing has no recorded options".into()))?; + let preset = trace.and_then(|t| t.get("preset")).and_then(Value::as_str).unwrap_or_default().to_string(); + Ok((item, params, g.trace_view(), preset)) + }) +} + +/// Reads the setting `key` of the tracing `this` names with `f`. +fn read_option(h: &Host, a: &[Data], key: &str, f: impl FnOnce(&Value) -> Answer) -> Answer { + let (_, params, ..) = options_of(h, a)?; + f(params.get(key).unwrap_or(&Value::Null)) +} + +/// Traces again with the setting `key` at `value`, unless it is at that value already. +fn write_option(h: &Host, a: &[Data], key: &str, value: Value) -> Answer { + let (item, mut params, ..) = options_of(h, a)?; + if params.get(key) == Some(&value) { + return Ok(Data::Undefined); + } + params.insert(key.into(), value); + let on = |k: &str| params.get(k).and_then(Value::as_bool) == Some(true); + if !on("fills") && !on("strokes") { + return Err(HostError::Error(NEEDS_FILLS_OR_STROKES.into())); + } + let mut p = Map::new(); + p.insert("params".into(), Value::Object(params)); + retrace(h, item, p)?; + Ok(Data::Undefined) +} + +/// A whole number from `lo` to `hi` for the option `name`. +fn whole_in(d: &Data, name: &str, lo: u64, hi: u64) -> Result { + let n = number(d, &format!("TracingOptions.{name}"))?; + if n.fract() != 0.0 || n < float(lo) || n > float(hi) { + return Err(out_of_range(name, &format!("a whole number from {lo} to {hi}"))); + } + whole(n).ok_or_else(|| out_of_range(name, &format!("a whole number from {lo} to {hi}"))) +} + +fn as_number(v: &Value) -> Answer { + v.as_f64().map(num).ok_or_else(|| HostError::Error("the tracing's options are damaged".into())) +} + +fn as_bool(v: &Value) -> Answer { + v.as_bool().map(Data::Bool).ok_or_else(|| HostError::Error("the tracing's options are damaged".into())) +} + +fn options_mode(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "mode", |v| { + let mode = v.as_str().unwrap_or_default(); + match MODES.iter().find(|(_, m)| *m == mode) { + Some((name, _)) => Ok(text(*name)), + None => Err(HostError::Error("TracingOptions.tracingMode has no value for this tracing's mode".into())), + } + }) +} + +fn options_set_mode(h: &Host, a: &[Data]) -> Answer { + let mode = match arg(a, 1) { + Data::String(s) => MODES.iter().find(|(n, _)| n == s).map(|(_, m)| *m), + _ => None, + }; + let mode = mode.ok_or_else(|| HostError::Type("TracingOptions.tracingMode must be a TracingModeType value".into()))?; + write_option(h, a, "mode", json!(mode)) +} + +fn options_threshold(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "threshold", as_number) +} + +fn options_set_threshold(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "threshold", 0, 255)?; + write_option(h, a, "threshold", json!(v)) +} + +fn options_max_colors(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "colors", as_number) +} + +fn options_set_max_colors(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "maxColors", 2, 256)?; + write_option(h, a, "colors", json!(v)) +} + +fn options_min_area(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "noise", as_number) +} + +fn options_set_min_area(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "minArea", 0, MAX_MIN_AREA)?; + write_option(h, a, "noise", json!(v)) +} + +fn options_fills(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "fills", as_bool) +} + +fn options_set_fills(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.fills")?; + write_option(h, a, "fills", json!(v)) +} + +fn options_strokes(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "strokes", as_bool) +} + +fn options_set_strokes(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.strokes")?; + write_option(h, a, "strokes", json!(v)) +} + +fn options_ignore_white(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "ignoreWhite", as_bool) +} + +fn options_set_ignore_white(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.ignoreWhite")?; + write_option(h, a, "ignoreWhite", json!(v)) +} + +fn options_palette(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "palette", |v| { + let palette = v.as_str().unwrap_or_default(); + match PALETTES.iter().find(|(_, p)| *p == palette) { + Some((name, _)) => Ok(text(*name)), + None => Err(HostError::Error("the tracing's options are damaged".into())), + } + }) +} + +fn options_set_palette(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("TracingOptions.palette must be a string".into())) }; + let palette = PALETTES.iter().find(|(n, _)| n == name).map(|(_, p)| *p).ok_or_else(|| invalid("palette"))?; + write_option(h, a, "palette", json!(palette)) +} + +/// The view's `viewRaster` (`raster`) or `viewVector`. +fn view_part(view: TraceView, raster: bool) -> Answer { + let name = if raster { "viewRaster" } else { "viewVector" }; + VIEWS + .iter() + .find(|(v, ..)| *v == view) + .map(|(_, r, v)| text(if raster { *r } else { *v })) + .ok_or_else(|| HostError::Error(format!("TracingOptions.{name} has no value for the Split view"))) +} + +fn options_view(h: &Host, a: &[Data], raster: bool) -> Answer { + let (_, _, view, _) = options_of(h, a)?; + view_part(view, raster) +} + +/// Shows the view `viewRaster` (`raster`) or `viewVector` makes with the other one as it is. +fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer { + let (name, kind) = if raster { ("viewRaster", "ViewRasterType") } else { ("viewVector", "ViewVectorType") }; + let given = match arg(a, 1) { + Data::String(s) if ENUMS.iter().any(|(e, members)| *e == kind && members.iter().any(|m| *s == format!("{kind}.{m}"))) => s.clone(), + _ => return Err(HostError::Type(format!("TracingOptions.{name} must be a {kind} value"))), + }; + let (item, _, view, _) = options_of(h, a)?; + let Data::String(other) = view_part(view, !raster)? else { return Err(invalid(name)) }; + let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v }; + let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?; + if *to != view { + edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?; + } + Ok(Data::Undefined) +} + +fn options_view_raster(h: &Host, a: &[Data]) -> Answer { + options_view(h, a, true) +} + +fn options_set_view_raster(h: &Host, a: &[Data]) -> Answer { + options_set_view(h, a, true) +} + +fn options_view_vector(h: &Host, a: &[Data]) -> Answer { + options_view(h, a, false) +} + +fn options_set_view_vector(h: &Host, a: &[Data]) -> Answer { + options_set_view(h, a, false) +} + +fn options_preset(h: &Host, a: &[Data]) -> Answer { + let (_, _, _, preset) = options_of(h, a)?; + Ok(text(preset)) +} + +fn options_parent(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = tracing_of(h, arg(a, 0), "TracingOptions")?; + Ok(host_ref("TracingObject", &handle)) +} + +/// A preset name given to `method`: a string of at most [`MAX_PRESET_NAME`] bytes without `/`, +/// `\`, `:` or control characters, trimmed. +fn preset_name<'a>(d: &'a Data, method: &str) -> Result<&'a str, HostError> { + let Data::String(name) = d else { return Err(HostError::Type(format!("TracingOptions.{method} needs a preset name, as a string"))) }; + if name.len() > MAX_PRESET_NAME { + return Err(HostError::Range(format!("TracingOptions.{method}: a preset name has at most {MAX_PRESET_NAME} bytes"))); + } + if name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) { + return Err(HostError::Error(format!("TracingOptions.{method}: a preset name cannot hold / \\ : or control characters"))); + } + let name = name.trim(); + if name.is_empty() { + return Err(HostError::Error(format!("TracingOptions.{method}: the preset name is empty"))); + } + Ok(name) +} + +/// `loadFromPreset(name)`: traces again with the built-in or saved preset `name` → `true`. +fn options_load(h: &Host, a: &[Data]) -> Answer { + let name = preset_name(arg(a, 1), "loadFromPreset")?; + let (item, params, _, preset) = options_of(h, a)?; + let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone())); + let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?; + let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(¶ms); + if !(same && preset.eq_ignore_ascii_case(name)) { + let mut p = Map::new(); + p.insert("preset".into(), json!(name)); + retrace(h, item, p)?; + } + Ok(Data::Bool(true)) +} + +/// `storeToPreset(name)`: `false` for a built-in preset or `Custom`; any other name runs +/// `imageTrace.presets.save`, which a script cannot run. +fn options_store(h: &Host, a: &[Data]) -> Answer { + let name = preset_name(arg(a, 1), "storeToPreset")?; + let (_, params, ..) = options_of(h, a)?; + if vectorcraft_trace::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") { + return Ok(Data::Bool(false)); + } + command(h, "imageTrace.presets.save", &json!({"name": name, "params": params}))?; + Ok(Data::Bool(true)) +} + +/// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw, +/// after the check that the tracing `this` names is still there. +fn missing(link: &Link, name: &'static str) -> (String, HostMember) { + let message = not_implemented("TracingOptions", name); + let l = link.clone(); + let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16)?; + tracing_of(&h, arg(&a, 0), "TracingOptions")?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + +/// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`. +pub(super) fn add_trace(classes: &mut [HostClass], l: &Link) { + for c in classes.iter_mut() { + match c.name.as_str() { + "PlacedItem" => c.members.push(("trace".into(), method(l, placed_trace))), + "RasterItem" => c.members.push(("trace".into(), method(l, raster_trace))), + _ => {} + } + } +} + +/// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`. +pub(super) fn classes(l: &Link) -> Vec { + let plugin = named(vec![("isTracing", get(l, plugin_is_tracing)), ("tracing", get(l, plugin_tracing))]); + let tracing = named(vec![ + ("typename", typename_of("TracingObject")), + ("anchorCount", get(l, tracing_anchors)), + ("areaCount", get(l, tracing_areas)), + ("imageResolution", get(l, tracing_resolution)), + ("parent", get(l, tracing_parent)), + ("pathCount", get(l, tracing_paths)), + ("sourceArt", get(l, tracing_source)), + ("tracingOptions", get(l, tracing_options)), + ("usedColorCount", get(l, tracing_colors)), + ("expandTracing", method(l, tracing_expand)), + ("releaseTracing", method(l, tracing_release)), + ]); + let mut options = named(vec![ + ("typename", typename_of("TracingOptions")), + ("parent", get(l, options_parent)), + ("preset", get(l, options_preset)), + ("tracingMode", property(l, options_mode, options_set_mode)), + ("threshold", property(l, options_threshold, options_set_threshold)), + ("fills", property(l, options_fills, options_set_fills)), + ("strokes", property(l, options_strokes, options_set_strokes)), + ("maxColors", property(l, options_max_colors, options_set_max_colors)), + ("palette", property(l, options_palette, options_set_palette)), + ("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white)), + ("minArea", property(l, options_min_area, options_set_min_area)), + ("viewRaster", property(l, options_view_raster, options_set_view_raster)), + ("viewVector", property(l, options_view_vector, options_set_view_vector)), + ("loadFromPreset", method(l, options_load)), + ("storeToPreset", method(l, options_store)), + ]); + options.extend(NOT_IMPLEMENTED.iter().map(|m| missing(l, m))); + vec![ + class("PluginItem", Some("PageItem"), plugin, None), + class("TracingObject", None, tracing, None), + class("TracingOptions", None, options, None), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d1db3ccda6..0f140243ee 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -174,6 +174,7 @@ mod script_dialogs; mod script_dollar; mod script_dom; mod script_dom_images; +mod script_dom_tracing; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 1c1a78d864..87a775dbe4 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -457,8 +457,8 @@ fn members_not_available_yet_check_the_image_first() { &mut s, &base, "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ - try { n.trace; } catch (e) { m.push(e.message); }\ - p.embed(); try { p.trace; } catch (e) { m.push(e.message); }\ + try { n.contentVariable; } catch (e) { m.push(e.message); }\ + p.embed(); try { p.contentVariable; } catch (e) { m.push(e.message); }\ var r = d.rasterItems[0]; try { r.colorize; } catch (e) { m.push(e.message); }\ r.remove(); try { r.overprint; } catch (e) { m.push(e.message); }\ vc.log(m);", diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs new file mode 100644 index 0000000000..9479139027 --- /dev/null +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -0,0 +1,541 @@ +//! Tracing in the script object model: `trace()` on placed and raster items, the `PluginItem`, its +//! `TracingObject` and its `TracingOptions`, and the checks on what a script gives them. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-dom-tracing-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A 60 × 60 PNG of a black disc on white. +fn disc_png() -> Vec { + vectorcraft_trace::Raster::from_fn(60, 60, |x, y| { + let (dx, dy) = (f64::from(x) + 0.5 - 30.0, f64::from(y) + 0.5 - 30.0); + if dx * dx + dy * dy <= 400.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }) + .encode_png() +} + +/// A session with one 400 × 300 pt document holding the disc image, linked (`link`) or embedded. +fn session(base: &Path, link: bool) -> (Session, NodeId) { + let png = base.join("main/disc.png"); + std::fs::write(&png, disc_png()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": link})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + (s, id) +} + +/// Runs `text` as `main/main.jsx` in `base`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn log(s: &mut Session, base: &Path, text: &str) -> Vec { + let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The Image Trace objects of the active document. +fn traces(s: &Session) -> Vec { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if crate::cmd::is_trace_group(n) { + out.push(n.id); + } + }); + out +} + +/// The `trace` settings of the Image Trace object `id`. +fn trace_of(s: &Session, id: NodeId) -> Value { + s.active().unwrap().doc.node(id).and_then(|n| n.extras().trace.as_deref().cloned()).unwrap_or(Value::Null) +} + +/// Every top-level object of the active document's first layer. +fn top(s: &Session) -> Vec { + let d = &s.active().unwrap().doc; + d.children(Some(d.layers[0].id)).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default() +} + +/// Traces with the Default preset as a script does, which the script's counts should match: its +/// `paths` and `anchors`, and the different paints of the result. +fn command_counts(base: &Path, link: bool) -> (u64, u64, u64) { + let (mut s, id) = session(base, link); + let r = s.execute("imageTrace.make", &json!({"id": id.0})).unwrap(); + (r["paths"].as_u64().unwrap(), r["anchors"].as_u64().unwrap(), r["colors"].as_u64().unwrap()) +} + +#[test] +fn raster_trace_returns_plugin_with_counts() { + let base = folder("raster"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].clone(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, r = d.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing;\ + vc.log(p.typename); vc.log(p.isTracing); vc.log(t.typename); vc.log(t.sourceArt.name); vc.log(r.typename);\ + vc.log(t.pathCount); vc.log(t.anchorCount); vc.log(t.usedColorCount); vc.log(t.imageResolution);\ + vc.log(p.tracing.pathCount === t.pathCount); vc.log(t.parent.isTracing); vc.log(t.tracingOptions.typename);\ + vc.log(t.tracingOptions.parent.typename); vc.log(d.pageItems[0].typename); vc.log(t.tracingOptions.preset);", + ); + assert_eq!(out[..5], [json!("PluginItem"), json!(true), json!("TracingObject"), json!("src"), json!("RasterItem")]); + let (paths, anchors, colors) = command_counts(&base, false); + assert!(paths > 0 && anchors > 0, "{paths} {anchors}"); + assert_eq!(out[5], json!(paths)); + assert_eq!(out[6], json!(anchors)); + let used = out[7].as_u64().unwrap(); + assert!(used >= 1 && used <= colors, "{used} of {colors}"); + assert_eq!(out[8].as_f64(), ppi.as_f64()); + assert_eq!(out[9..], [json!(true), json!(true), json!("TracingOptions"), json!("TracingObject"), json!("PluginItem"), json!("Default")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(top(&s), groups); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_image_resolution_is_one_number_or_none() { + let base = folder("resolution"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].as_f64().unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.width = r.width * 2; r.height = r.height * 2;\ + var t = r.trace().tracing; vc.log(t.imageResolution); t.releaseTracing(); r.width = r.width * 2;\ + var m = ''; try { r.trace().tracing.imageResolution; } catch (e) { m = e.message; } vc.log(m);", + ); + assert!((out[0].as_f64().unwrap() - ppi / 2.0).abs() < 1e-9, "{out:?}"); + assert_eq!(out[1], json!("the source image has no single resolution")); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_trace_returns_plugin_with_source_art() { + let base = folder("placed"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, pl = d.placedItems[0]; pl.name = 'src'; var p = pl.trace();\ + vc.log(p.typename); vc.log(p.tracing.sourceArt.name); vc.log(pl.typename); vc.log(pl.file.name);\ + var m = ''; try { pl.trace(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("PluginItem"), json!("src"), json!("PlacedItem"), json!("disc.png"), json!("The image is the source art of a tracing")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(image), Some(groups[0]), "the image is the tracing's source"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_checks_the_image_first() { + let base = folder("unbound"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ + try { n.trace(); } catch (e) { m.push(e.message); } p.embed(); try { p.trace(); } catch (e) { m.push(e.message); }\ + try { PlacedItem.prototype.trace.call(d.rasterItems[0]); } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(["PlacedItem.file is required", "Stale page item", "this is not a PlacedItem"])]); + assert!(traces(&s).is_empty()); + assert!(s.active().unwrap().doc.node(image).is_some()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_missing_link_refuses_preview() { + let base = folder("missing"); + let (mut s, image) = session(&base, true); + std::fs::remove_file(base.join("main/disc.png")).unwrap(); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.placedItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + assert_eq!(out, [json!("Linked image is missing")]); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_release_restores_source_kind() { + let base = folder("release"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src';\ + var p = r.trace(), t = p.tracing, o = t.tracingOptions, back = t.releaseTracing();\ + vc.log(back.name); vc.log(back.typename); vc.log(r.hidden);\ + var m = []; try { p.name; } catch (e) { m.push(e.message); } try { t.pathCount; } catch (e) { m.push(e.message); }\ + try { o.threshold; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out[..3], [json!("src"), json!("RasterItem"), json!(false)]); + assert_eq!(out[3], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_expand_returns_group_and_stales_plugin() { + let base = folder("expand"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0], p = r.trace(), t = p.tracing, m = [];\ + try { t.expandTracing(true); } catch (e) { m.push(e.message); }\ + try { t.expandTracing('yes'); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(p.isTracing);\ + var g = t.expandTracing(); vc.log(g.typename); vc.log(p === g); m = [];\ + try { p.isTracing; } catch (e) { m.push(e.message); } try { t.anchorCount; } catch (e) { m.push(e.message); }\ + try { r.name; } catch (e) { m.push(e.message); } vc.log(m); vc.log(app.activeDocument.pageItems[0] === g);", + ); + assert_eq!(out[0], json!(["TracingObject.expandTracing(true) is not implemented", "TypeError"])); + assert_eq!(out[1..4], [json!(true), json!("GroupItem"), json!(false)], "the group is a new object"); + assert_eq!(out[4], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert_eq!(out[5], json!(true), "the group read again is the object expandTracing gave"); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + assert!(d.node(image).is_none(), "the expanded group keeps no source image"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_options_retrace_preserves_source_and_view() { + let base = folder("options"); + let (mut s, image) = session(&base, false); + let defaults = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing, o = t.tracingOptions;\ + vc.log([o.tracingMode, o.threshold, o.fills, o.strokes, o.maxColors, o.palette, o.ignoreWhite, o.minArea]);\ + vc.log([o.viewRaster, o.viewVector]);\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE;\ + o.threshold = 200; o.minArea = 4;\ + vc.log([o.threshold, o.minArea, o.preset, o.viewRaster, o.viewVector]);\ + vc.log(t.sourceArt.name); vc.log(r.name); vc.log(p.isTracing); vc.log(p.tracing.tracingOptions.threshold); vc.log(t.pathCount > 0);", + ); + let mode = |m: &str| json!(format!("TracingModeType.TRACINGMODE{m}")); + let expected_mode = match defaults["mode"].as_str() { + Some("blackAndWhite") => mode("BLACKANDWHITE"), + Some("grayscale") => mode("GRAY"), + _ => mode("COLOR"), + }; + assert_eq!( + out[0], + json!([ + expected_mode, + defaults["threshold"], + defaults["fills"], + defaults["strokes"], + defaults["colors"], + "Limited", + defaults["ignoreWhite"], + defaults["noise"] + ]) + ); + assert_eq!(out[1], json!(["ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"])); + assert_eq!(out[2], json!([200, 4, "Custom", "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"])); + assert_eq!(out[3..], [json!("src"), json!("src"), json!(true), json!(200), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let t = trace_of(&s, groups[0]); + assert_eq!( + (t["params"]["threshold"].clone(), t["params"]["noise"].clone(), t["view"].clone()), + (json!(200), json!(4), json!("outlinesWithSourceImage")) + ); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + + // Assigning the values the options have already changes nothing. + let before = (undo_steps(&s), traces(&s)); + let out = log( + &mut s, + &base, + "var o = app.activeDocument.pageItems[0].tracing.tracingOptions; o.threshold = 200; o.minArea = 4; o.fills = true;\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; vc.log(o.threshold);", + ); + assert_eq!(out, [json!(200)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_invalid_option_is_atomic() { + let base = folder("invalid"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace();"); + let before = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + let cases = [ + ("o.threshold = 'x'", "TypeError"), + ("o.threshold = 256", "TracingOptions.threshold is out of range"), + ("o.threshold = -1", "TracingOptions.threshold is out of range"), + ("o.threshold = 1.5", "TracingOptions.threshold is out of range"), + ("o.threshold = NaN", "TypeError"), + ("o.maxColors = 1", "TracingOptions.maxColors is out of range"), + ("o.maxColors = 257", "TracingOptions.maxColors is out of range"), + ("o.minArea = 1e12", "TracingOptions.minArea is out of range"), + ("o.fills = 1", "TypeError"), + ("o.fills = false", "TracingOptions requires fills or strokes"), + ("o.tracingMode = 'color'", "TypeError"), + ("o.palette = 'Spectrum'", "TracingOptions.palette has an invalid value"), + ("o.palette = 3", "TypeError"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERADJUSTEDIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewVector = 'outlines'", "TypeError"), + ("o.pathFitting = 3", "TracingOptions.pathFitting is not implemented"), + ("o.cornerAngle", "TracingOptions.cornerAngle is not implemented"), + ("o.resampleResolution = 72", "TracingOptions.resampleResolution is not implemented"), + ("t.areaCount", "TracingObject.areaCount is not implemented"), + ("o.loadFromPreset('No Such Preset')", "no built-in or saved preset has that name"), + ("o.loadFromPreset('../Default')", "cannot hold"), + ("o.loadFromPreset('C:\\\\x')", "cannot hold"), + ("o.loadFromPreset('a\\u0000b')", "cannot hold"), + ("o.loadFromPreset(new Array(300).join('x'))", "at most 256 bytes"), + ("o.loadFromPreset(' ')", "the preset name is empty"), + ("o.loadFromPreset(5)", "TypeError"), + ("o.storeToPreset('Mine')", "a script cannot run `imageTrace.presets.save`"), + ("o.storeToPreset('../Mine')", "cannot hold"), + ]; + let mut wrong = vec![]; + for (code, message) in cases { + let out = log( + &mut s, + &base, + &format!( + "var t = app.activeDocument.pageItems[0].tracing, o = t.tracingOptions, m = 'none';\ + try {{ {code}; }} catch (e) {{ m = e.name + ': ' + e.message; }} vc.log(m); vc.log(o.threshold);" + ), + ); + let m = out[0].as_str().unwrap_or_default().to_string(); + let now = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before { + wrong.push(format!("{code}: {m}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + assert!(s.prefs.trace_presets.is_empty(), "no preset was saved"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_presets_load_and_locked_store() { + let base = folder("presets"); + let (mut s, _) = session(&base, false); + let silhouettes = serde_json::to_value(vectorcraft_trace::preset("Silhouettes").unwrap()).unwrap(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + vc.log(o.loadFromPreset('Silhouettes')); vc.log(o.preset); vc.log(o.threshold);\ + vc.log(o.storeToPreset('Default')); vc.log(o.storeToPreset('custom')); vc.log(o.storeToPreset('Silhouettes'));", + ); + assert_eq!(out, [json!(true), json!("Silhouettes"), silhouettes["threshold"].clone(), json!(false), json!(false), json!(false)]); + let t = trace_of(&s, traces(&s)[0]); + assert_eq!(t["params"], silhouettes); + + // Loading the preset the tracing has already traces nothing again. + let before = (undo_steps(&s), traces(&s)); + let out = log(&mut s, &base, "vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.loadFromPreset('silhouettes'));"); + assert_eq!(out, [json!(true)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_external_retrace_undo_and_source_delete() { + let base = folder("stale"); + let (mut s, image) = session(&base, false); + let threshold = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap()["threshold"].clone(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = [];\ + var p = d.rasterItems[0].trace(), t = p.tracing; d.selection = p; vc.run('imageTrace.make', {{}});\ + try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\ + var q = d.pageItems[0], u = q.tracing, o = u.tracingOptions; o.threshold = 90; vc.log(o.threshold); vc.log(q.isTracing);\ + vc.run('edit.undo'); vc.log(q.isTracing); vc.log(o.threshold); vc.log(u.pathCount > 0);\ + var r = ''; try {{ u.sourceArt.remove(); }} catch (e) {{ r = e.message; }} vc.log(r); vc.log(u.pathCount > 0);\ + vc.run('edit.clear', {{ids: [{}]}});\ + try {{ u.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ q.isTracing; }} catch (e) {{ m.push(e.message); }}\ + vc.log(d.pageItems[0].typename); vc.log(m);", + image.0 + ), + ); + assert_eq!(out[..5], [json!(90), json!(true), json!(true), threshold, json!(true)], "the undo puts the first tracing back"); + assert!(out[5].as_str().is_some_and(|m| m.starts_with("cannot delete hidden or locked objects")), "{:?}", out[5]); + assert_eq!(out[6], json!(true), "the refused remove leaves the tracing"); + assert_eq!(out[7], json!("GroupItem"), "a group without its source image is no longer a tracing"); + assert_eq!(out[8], json!(vec!["Stale page item"; 4])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_deleted_plugin_is_stale() { + let base = folder("deleted"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = []; p.remove();\ + try { p.name; } catch (e) { m.push(e.message); } try { t.sourceArt; } catch (e) { m.push(e.message); }\ + try { o.threshold = 10; } catch (e) { m.push(e.message); } try { t.releaseTracing(); } catch (e) { m.push(e.message); }\ + try { o.pathFitting; } catch (e) { m.push(e.message); } try { o.cornerAngle = 1; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(vec!["Stale page item"; 6])]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// A script's trace of an image past the tracer's source limit (`vectorcraft_trace::MAX_SOURCE_PIXELS`, +/// 192 megapixels) is refused from the image's header before its pixels are decoded, and the run +/// leaves the document as it was. +#[test] +fn trace_large_image_is_bounded() { + let base = folder("large"); + let png = base.join("main/wall.png"); + std::fs::write(&png, super::linkspanel::png_header(30_000, 30_000)).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.rasterItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + let m = out[0].as_str().unwrap_or_default(); + assert!(m.contains("30000 × 30000 pixels") && m.contains("(192 megapixels)"), "{m}"); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_remove_all_takes_the_tracing() { + let base = folder("remove-all"); + let (mut s, _) = session(&base, false); + let out = log(&mut s, &base, "var d = app.activeDocument; d.rasterItems[0].trace(); d.pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(0)]); + assert!(traces(&s).is_empty()); + assert!(top(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_stop_rolls_back_long_work() { + let base = folder("stop"); + let (mut s, image) = session(&base, false); + let before = top(&s); + s.script_in_run = true; + let stop = s.script_interrupt(); + stop.set(); + let r = s.execute("imageTrace.make", &json!({"id": image.0})); + stop.clear(); + s.script_in_run = false; + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(top(&s), before); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_trace_refuses_the_source_image_of_a_trace() { + let base = folder("source"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let e = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap_err().to_string(); + assert!(e.contains("source image of an Image Trace object"), "{e}"); + assert_eq!(traces(&s), [group]); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(group)); + + // With another image named after the source image, that other image is traced. + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let r = s.execute("imageTrace.make", &json!({"ids": [image.0, other.0]})).unwrap(); + let second = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(other), Some(second)); + assert_eq!(d.parent_of(image), Some(group)); + assert_eq!(traces(&s).len(), 2); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_of_another_image_inside_a_tracing() { + let base = folder("inside"); + let (mut s, image) = session(&base, false); + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var q = r.trace(); vc.log(q.typename); vc.log(q.tracing.sourceArt === r); vc.log(p.tracing.pathCount > 0);", + ); + assert_eq!(out, [json!("PluginItem"), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 2); + let d = &s.active().unwrap().doc; + let (a, b) = (d.parent_of(image).unwrap(), d.parent_of(other).unwrap()); + assert!(groups.contains(&a) && groups.contains(&b) && a != b, "each image is the source of its own tracing"); + assert!(d.parent_of(a) == Some(b) || d.parent_of(b) == Some(a), "one tracing is inside the other"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_source_art_is_not_listed_with_the_images() { + let base = folder("lists"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.rasterItems[0].trace(); var n = d.rasterItems.length, k = 0;\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename === 'RasterItem') k++; }\ + d.rasterItems.removeAll(); vc.log(n); vc.log(k); vc.log(d.rasterItems.length); vc.log(d.pageItems[0].typename);", + ); + assert_eq!(out, [json!(1), json!(1), json!(0), json!("PluginItem")]); + assert_eq!(traces(&s).len(), 1, "removing the raster items leaves the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_plugin_keeps_its_name() { + let base = folder("renamed"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, m = '', n = p.name; p.name = n;\ + try { p.name = 'logo'; } catch (e) { m = e.message; } vc.log(m); vc.log(p.name === n); vc.log(p.typename); vc.log(t.pathCount > 0);", + ); + assert_eq!(out, [json!("The name of a tracing cannot be changed"), json!(true), json!("PluginItem"), json!(true)]); + assert_eq!(traces(&s).len(), 1); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 931023a427..8593d593aa 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -78,7 +78,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems PlacedItem PlacedItems RasterItem RasterItems RulerUnits ZOrderMethod", + PageItems PlacedItem PlacedItems PluginItem RasterItem RasterItems RulerUnits TracingObject TracingOptions ZOrderMethod", ), ("Application.", "prototype"), ( @@ -121,7 +121,9 @@ const INSIDE: &[(&str, &str)] = &[ ("PlacedItems.", "prototype"), ("PlacedItems.prototype.", "add constructor getByName index length parent removeAll typename"), ("PlacedItem.", "prototype"), - ("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace trace="), + ("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace"), + ("PluginItem.", "prototype"), + ("PluginItem.prototype.", "constructor isTracing tracing"), ("RasterItems.", "prototype"), ("RasterItems.prototype.", "constructor getByName index length parent removeAll typename"), ("RasterItem.", "prototype"), @@ -129,7 +131,23 @@ const INSIDE: &[(&str, &str)] = &[ "RasterItem.prototype.", "bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \ contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \ - trace trace= transparent", + trace transparent", + ), + ("TracingObject.", "prototype"), + ( + "TracingObject.prototype.", + "anchorCount areaCount constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \ + tracingOptions typename usedColorCount", + ), + ("TracingOptions.", "prototype"), + ( + "TracingOptions.prototype.", + "constructor cornerAngle cornerAngle= fills fills= ignoreWhite ignoreWhite= livePaintOutput livePaintOutput= \ + loadFromPreset maxColors maxColors= maxStrokeWeight maxStrokeWeight= minArea minArea= minStrokeLength \ + minStrokeLength= outputToSwatches outputToSwatches= palette palette= parent pathFitting pathFitting= \ + preprocessBlur preprocessBlur= preset resample resample= resampleResolution resampleResolution= storeToPreset \ + strokes strokes= threshold threshold= tracingMode tracingMode= typename viewRaster viewRaster= viewVector \ + viewVector=", ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), @@ -163,6 +181,15 @@ const INSIDE: &[(&str, &str)] = &[ ("", "ImageColorSpace RasterLinkState"), ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), ("RasterLinkState.", "DATAFROMFILE DATAMODIFIED NODATA"), + // The enumerations of tracings. + ("", "TracingModeType ViewRasterType ViewVectorType"), + ("TracingModeType.", "TRACINGMODEBLACKANDWHITE TRACINGMODECOLOR TRACINGMODEGRAY"), + ("ViewRasterType.", "TRACINGVIEWRASTERADJUSTEDIMAGE TRACINGVIEWRASTERNOIMAGE TRACINGVIEWRASTERORIGINALIMAGE TRACINGVIEWRASTERTRANSPARENTIMAGE"), + ( + "ViewVectorType.", + "TRACINGVIEWVECTORNOTRACINGRESULT TRACINGVIEWVECTOROUTLINES TRACINGVIEWVECTOROUTLINESWITHTRACING \ + TRACINGVIEWVECTORTRACINGRESULT", + ), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 7cb632376d..b6bf5a3388 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -518,7 +518,7 @@ fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult< if outcome(i, o, &r)? { let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; if matches!(fs, Value::String(_)) { - set_slot(i, o, PATH, fs)?; + set_path(i, o, fs)?; } } Ok(Value::Undefined) diff --git a/docs/mcp.md b/docs/mcp.md index bd8fa335c6..2fc817b9ad 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2756,7 +2756,38 @@ app through the global object `vc`, and writes to the Script Console and runs ot `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point a pixel. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the - end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. + end of the run. `contentVariable`, `colorants`, `colorize` and `overprint` are not available yet. +- `PlacedItem.trace()` and `RasterItem.trace()` trace the image with `imageTrace.make` and the Default preset and + return the Image Trace object as a `PluginItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/), whose + `isTracing` is `true` and whose `tracing` is its `TracingObject` + (https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/). A `TracingObject` has `sourceArt` (the traced image), + `pathCount`, `anchorCount`, `usedColorCount`, `imageResolution`, `tracingOptions`, `parent`, `expandTracing()` + (`imageTrace.expand`, which returns the expanded group) and `releaseTracing()` (`imageTrace.release`, which returns + the image). `TracingOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/) has `tracingMode`, + `threshold`, `maxColors`, `palette`, `fills`, `strokes`, `ignoreWhite`, `minArea`, `viewRaster`, `viewVector`, + `preset`, `parent`, `loadFromPreset(name)` and `storeToPreset(name)`, and the enumerations `TracingModeType`, + `ViewRasterType` and `ViewVectorType` hold strings such as `"TracingModeType.TRACINGMODECOLOR"`. VectorCraft's own + rules: `trace()` returns once the trace is made. It throws `The image is the source art of a tracing` on an image an + Image Trace object holds, and `Linked image is missing` on a linked image whose file is missing. `pathCount` does not + count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and + `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions + across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the + source image and the view, and a value the tracing already has runs no command. The `PluginItem`, `TracingObject` + and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `threshold` takes a whole + number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest + image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`, + `"Full Tone"` or `"Document Library"`; `viewRaster` and `viewVector` take only the pairs that match an Image Trace + view. A value of the wrong type throws a `TypeError`, a number out of range a `RangeError`, and nothing changes. + `expandTracing(true)` throws `TracingObject.expandTracing(true) is not implemented` with nothing changed. A preset + name is a string of at most 256 bytes without `/`, `\`, `:` or control characters. `storeToPreset` returns `false` + for a built-in preset name and `Custom`, and throws for any other name, since a script cannot run + `imageTrace.presets.save`. A tracing that was expanded, released, deleted, traced again by a command, or whose + source image was deleted throws `Stale page item`. A script gets the source image from `sourceArt`, and `pageItems`, + `placedItems` and `rasterItems` do not list it. Assigning a different `name` to a `PluginItem` throws + `The name of a tracing cannot be changed`. `areaCount`, `cornerAngle`, `livePaintOutput`, + `maxStrokeWeight`, `minStrokeLength`, `outputToSwatches`, `pathFitting`, `preprocessBlur`, `resample` and + `resampleResolution` throw an error that says they are not implemented. With a script running, `imageTrace.make` + stops at the run's stop request and changes nothing. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5073c9574c..5388cacfb9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,7 +1029,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Tracing, rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. + - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From fde921a7445f10bb9b18fb255209484123b8ed66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:44:39 -0800 Subject: [PATCH 09/41] Scripts: review fixes for tracing, placed items, saves and the New Document layout - The Image Trace panel's lookup test skips an Image Trace object's source image, as imageTrace.make does since trace() came in. - A save of several files refuses a path the file access in force refuses before any file is written, whatever writer the caller gives. - move and duplicate look a page item up through its class, so a PlacedItem that was embedded is stale as the relative object. - PLACEATEND into an Image Trace object puts the object directly above the source image, which stays the first child. - controlBounds takes in the anchors and Bezier handles of the item's paths. - The file of a PlacedItems.add() result is stale once its document closes. - Assigning PlacedItem.file reads the placed image's id from the command's own result, so an id above 2^53 binds and clears exactly. - The enumerations the save and export option defaults name are registered, with the members the scripting constants page lists. - A tracing replaced twice and then undone is followed to the one the document holds. - Choosing the artboard layout in force again keeps a preset's rows. - docs/mcp.md and docs/gaps.md describe controlBounds, a null preset for addDocument, the view options and scripted tracing. --- crates/engine/src/cmd/fileio/save.rs | 8 +- crates/engine/src/cmd/fileio/tests.rs | 25 ++++++ crates/engine/src/script/dom.rs | 82 +++++++++++++------ crates/engine/src/script/dom/images.rs | 28 +++---- crates/engine/src/script/dom/save_open.rs | 71 ++++++++++++++++ crates/engine/src/script/dom/tracing.rs | 39 +++++---- crates/engine/src/tests/script_dom.rs | 28 ++++++- crates/engine/src/tests/script_dom_images.rs | 61 ++++++++++++++ crates/engine/src/tests/script_dom_tracing.rs | 46 +++++++++++ crates/engine/src/tests/script_save_open.rs | 30 +++++++ .../tests/it/script_host_vs_scriptcheck.rs | 38 +++++++++ crates/ui-egui/src/dialogs/new_document.rs | 11 ++- .../ui-egui/src/panels/image_trace/tests.rs | 21 +++-- docs/gaps.md | 4 +- docs/mcp.md | 15 ++-- 15 files changed, 430 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 94187808c6..ba7e6682af 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,13 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. A refused file is refused here, so none of the files is written, also through + // a `write` that does not check the file access itself. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; + return Err(refused); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 56e2a12f30..36ace77603 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -1038,6 +1038,31 @@ fn a_save_canceled_after_its_first_file_writes_them_all() { let _ = std::fs::remove_dir_all(&d); } +/// A save that writes several files, through a writer that does not check the file access in +/// force, writes none of them when that access refuses one: the save refuses it itself. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_save_of_several_files_refused_by_the_file_access_writes_none_through_any_writer() { + let d = tmp_dir("refused-files"); + let mut s = session(100.0, 100.0, 2); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let path = d.join("logo.eps").to_string_lossy().to_string(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let mut written = vec![]; + let r = crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || { + job.write(|p, b| { + std::fs::write(p, b).map_err(|e| EngineError::Other(e.to_string()))?; + written.push(p.to_string()); + Ok(()) + }) + }); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("write authority is absent")), "{r:?}"); + assert!(written.is_empty(), "{written:?}"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(&d); +} + /// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them. #[test] fn a_failed_save_does_not_stamp_the_documents_dates() { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 87f348a24c..20d6668374 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1171,20 +1171,23 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result 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 worked out once for the whole list. + with_doc(h, doc, |_, st| { + let locked = st.doc.locked_artboards(); + let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen = std::collections::HashSet::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, &locked, 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 { @@ -1453,6 +1456,28 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds)); + Ok(f.bounds(h.dom.coords.get(), handles.map_or(r, |b| r.union(b)))) +} + +/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown +/// paths in a group or compound path (a clip group's from its clipping path). `None` for other +/// objects. +fn handle_bounds(n: &crate::doc::Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)), + NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b)) + } + _ => None, + } +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1623,19 +1648,25 @@ struct Destination { fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); - let pending = images::pending_as_item(h, target)?.map(|p| p.to_vec()); - let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, 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())); + // A page item is looked up as its class names it (a wrapper whose object changed class is + // stale), a layer by its handle. + let (doc, target) = if handle_of(target, "PageItem").is_some() { + let t = item_of(h, target)?; + (t.doc, t.id) + } else { + let handle = handle_of(target, "Layer"); + let Some(&[run, uid, 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()))?; + (doc, id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?) }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } - let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| { let d = &st.doc; let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -1672,7 +1703,10 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let d = &st.doc; let from = d.position(id); let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); - let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + // A clip group's first child is its clipping path, and an Image Trace object's its source + // image: both stay first (the source image itself may go to the end of its own tracing). + let source = crate::cmd::is_trace_source(d, id) && d.parent_of(id) == Some(to.parent); + let clips = d.node(to.parent).is_some_and(|n| n.clips() || (crate::cmd::is_trace_group(n) && !source)) && count > 0; let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -1932,7 +1966,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index b1a3665190..10291e2ef1 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -40,9 +40,9 @@ use vectorcraft_geom::{Affine, Point}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; use super::{ - Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, - editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, - with_doc, + Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value, doc_of, + doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -127,14 +127,6 @@ fn pending_handle(d: &Data) -> Option<[f64; 3]> { } } -/// The page item handle (run, uid and the two halves of the id) of the image a -/// `PlacedItems.add()` result `d` placed, or `None` when `d` is not such a result. -pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result, HostError> { - let Some([run, uid, slot]) = pending_handle(d) else { return Ok(None) }; - let [high, low] = super::id_parts(pending_id(h, run, uid, slot)?); - Ok(Some([run, uid, high, low])) -} - /// The ids of a document's linked (`placed`) or embedded images in paint order. fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; @@ -360,6 +352,8 @@ fn placed_file(h: &Host, a: &[Data]) -> Answer { if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) { let k = slot_of(h, run, uid, slot)?; if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) { + // Null while its document is open; stale once that document is closed. + find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; return Ok(Data::Null); } } @@ -387,12 +381,12 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { } let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let path = image_path(h, arg(a, 1), "PlacedItem.file")?; - let placed = on_doc(h, doc.uid, true, |h| command(h, "file.place", &json!({"path": path, "link": true})))?; - let ids: Vec = match field(&placed, "ids") { - Some(Data::Array(ids)) => ids.iter().filter_map(|d| id_value(Some(d))).map(|i| i.0).collect(), - _ => Vec::new(), - }; - let id = id_value(field(&placed, "image")).or_else(|| id_value(field(&placed, "ids"))); + // The ids are read from the command's own result, where every id is exact (a script number + // holds integers exactly only up to 2^53). + let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; + let ids: Vec = placed["ids"].as_array().map(|ids| ids.iter().filter_map(serde_json::Value::as_u64).collect()).unwrap_or_default(); + let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); + let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); let linked = |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); match id.filter(|id| linked(*id)) { Some(id) => { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..04a06629d0 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -84,6 +84,77 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), + // The enumerations of the option defaults ([`Default::Member`]), with the members + // https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ lists. + ("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]), + ( + "CompressionQuality", + &[ + "AUTOMATICJPEG2000HIGH", + "AUTOMATICJPEG2000LOSSLESS", + "AUTOMATICJPEG2000LOW", + "AUTOMATICJPEG2000MAXIMUM", + "AUTOMATICJPEG2000MEDIUM", + "AUTOMATICJPEG2000MINIMUM", + "AUTOMATICJPEGHIGH", + "AUTOMATICJPEGLOW", + "AUTOMATICJPEGMAXIMUM", + "AUTOMATICJPEGMEDIUM", + "AUTOMATICJPEGMINIMUM", + "JPEG2000HIGH", + "JPEG2000LOSSLESS", + "JPEG2000LOW", + "JPEG2000MAXIMUM", + "JPEG2000MEDIUM", + "JPEG2000MINIMUM", + "JPEGHIGH", + "JPEGLOW", + "JPEGMAXIMUM", + "JPEGMEDIUM", + "JPEGMINIMUM", + "ZIP4BIT", + "ZIP8BIT", + "None", + ], + ), + ("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]), + ( + "ColorDestination", + &[ + "COLORDESTINATIONDOCCMYK", + "COLORDESTINATIONDOCRGB", + "COLORDESTINATIONPROFILE", + "COLORDESTINATIONWORKINGCMYK", + "COLORDESTINATIONWORKINGRGB", + "None", + ], + ), + ("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]), + ("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]), + ("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]), + ("PageMarksTypes", &["Japanese", "Roman"]), + ("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]), + ( + "PDFChangesAllowedEnum", + &[ + "CHANGE128ANYCHANGES", + "CHANGE128COMMENTING", + "CHANGE128EDITPAGE", + "CHANGE128FILLFORM", + "CHANGE128NONE", + "CHANGE40ANYCHANGES", + "CHANGE40COMMENTING", + "CHANGE40NONE", + "CHANGE40PAGELAYOUT", + ], + ), + ("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]), + ("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "STYLEATTRIBUTES", "PRESENTATIONATTRIBUTES", "STYLEELEMENTS"]), + ("SVGDocumentEncoding", &["ASCII", "UTF8", "UTF16"]), + ("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]), + ("SVGFontSubsetting", &["ALLGLYPHS", "GLYPHSUSEDPLUSENGLISH", "COMMONENGLISH", "GLYPHSUSEDPLUSROMAN", "COMMONROMAN", "GLYPHSUSED", "None"]), + ("SVGFontType", &["CEFFONT", "SVGFONT", "OUTLINEFONT"]), ]; const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index f8642f3b7d..4e37fb9f31 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -118,26 +118,31 @@ pub(super) struct State { } /// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put -/// it back put back the same object), else the Image Trace object that replaced it when this run -/// traced it again, else `id`. +/// it back put back the same object), else the first object the document holds among those that +/// replaced it, one after the other, when this run traced it again (an Undo can put back one of +/// them), else the last of them, else `id`. pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { - let held = h.session.borrow().documents().iter().find(|d| d.uid == uid).is_some_and(|d| d.doc.node(id).is_some()); - if held { - return id; - } - h.dom.tracing.next.borrow().get(&(uid, id.0)).map_or(id, |n| NodeId(*n)) -} - -/// Records that `new` replaced `old` in the document `uid`: every object that led to `old` leads to -/// `new` now. -fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { - let mut next = h.dom.tracing.next.borrow_mut(); - for ((u, _), to) in next.iter_mut() { - if *u == uid && *to == old.0 { - *to = new.0; + let s = h.session.borrow(); + let doc = s.documents().iter().find(|d| d.uid == uid); + let held = |id: NodeId| doc.is_some_and(|d| d.doc.node(id).is_some()); + let next = h.dom.tracing.next.borrow(); + let mut id = id; + // Each object is replaced by one made later, so the steps end; the bound holds them anyway. + for _ in 0..=next.len() { + if held(id) { + return id; + } + match next.get(&(uid, id.0)) { + Some(n) => id = NodeId(*n), + None => return id, } } - next.insert((uid, old.0), new.0); + id +} + +/// Records that `new` replaced `old` in the document `uid`. +fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { + h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0); } /// The error of a member with no VectorCraft setting. diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 5bf276e3b9..18fdf0b133 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,20 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the Bézier handles of a path, which can reach past what it draws. +#[test] +fn page_item_control_bounds_take_in_the_handles() { + let (mut s, _, _) = doc(); + let anchors = json!([{"x": 0, "y": 100, "out": [0, 0]}, {"x": 100, "y": 100, "in": [100, 0]}]); + s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, i = p[p.length - 1]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let b = |v: &Value| -> Vec { v.as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect() }; + let (visible, control) = (b(&out[0]), b(&out[1])); + assert!(visible[1] < 290.0, "the curve stays well under its handles: {visible:?}"); + assert!((control[1] - 300.0).abs() < 1e-9, "the handles reach the top of the page: {control:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2] && control[3] <= visible[3], "{visible:?} {control:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -451,6 +465,14 @@ fn a_grid_by_column_takes_the_number_of_rows() { let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + if layout.ends_with("GridByCol") { + // A column fills from the top before the next one starts, to the right of it (to the + // left from right to left). + let (first, second, next) = (boards[0].rect, boards[1].rect, boards[rows].rect); + assert!((second.x0 - first.x0).abs() < 1e-9 && second.y0 > first.y0, "{layout} {count}: {first:?} {second:?}"); + let rightward = next.x0 > first.x0; + assert_eq!(rightward, layout == "GridByCol", "{layout} {count}: {first:?} {next:?}"); + } } } @@ -1003,8 +1025,10 @@ 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'));"); + // String literals of the script, whatever characters the temporary folder's path holds. + let literal = |p: String| serde_json::to_string(&p).unwrap(); + let (p, other) = (literal(path.to_string_lossy().into_owned()), literal(format!("{}.other", path.to_string_lossy()))); + 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/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 7a3b764276..8101e17ab0 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -522,3 +522,64 @@ fn members_not_available_yet_check_the_image_first() { assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "RasterItem.colorize is not available yet", "Stale page item"])]); let _ = std::fs::remove_dir_all(base); } + +/// The `file` of a `PlacedItems.add()` result with no file is null while its document is open, and +/// the item is stale once that document is closed. +#[test] +fn a_pending_placed_items_file_is_stale_once_its_document_closes() { + let base = folder("pending-closed"); + let mut s = session(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.placedItems.add(); vc.log(p.file); vc.run('file.close', {});\ + var m = ''; try { vc.log(p.file); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(null), json!("Stale page item")]); + let _ = std::fs::remove_dir_all(base); +} + +/// Assigning `file` binds the placed item to the image `file.place` made, by its exact id, also +/// for an id above 2^53, which a script number does not hold exactly. +#[test] +fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() { + let base = folder("big-id"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + &base, + &format!("var p = app.activeDocument.placedItems.add(); p.file = new File('{}'); vc.log(p.file.name); vc.log(p.width);", js_path(&png)), + ); + assert_eq!(out, vec![json!("a.png"), json!(4)]); + let imgs = images(&s); + assert_eq!(imgs.len(), 1, "{imgs:?}"); + assert_eq!(imgs[0].0, NodeId(big)); + let _ = std::fs::remove_dir_all(base); +} + +/// A `PlacedItem` that was embedded is stale as the relative object of `move`: the raster item +/// it became is named by a fresh wrapper. +#[test] +fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { + let base = folder("stale-relative"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], x = null, m = '';\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') x = d.pageItems[i]; }\ + p.embed(); try { x.move(p, ElementPlacement.PLACEAFTER); } catch (e) { m = e.message; } vc.log(m);\ + x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log(d.pageItems[0].typename);", + ); + assert_eq!(out, vec![json!("Stale page item"), json!("PathItem")]); + assert!(s.active().unwrap().doc.node(NodeId(rect)).is_some()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 9479139027..dd48079cef 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -393,6 +393,26 @@ fn trace_external_retrace_undo_and_source_delete() { let _ = std::fs::remove_dir_all(base); } +/// After two option changes, an Undo puts back the tracing the first change made, and the objects +/// of the first tracing follow it there. +#[test] +fn trace_undo_of_the_second_retrace_reaches_the_first() { + let base = folder("chain"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + o.threshold = 90; o.threshold = 60; vc.log(o.threshold); vc.run('edit.undo');\ + vc.log(o.threshold); vc.log(p.isTracing); vc.log(p.tracing.pathCount > 0);", + ); + assert_eq!(out, [json!(60), json!(90), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_deleted_plugin_is_stale() { let base = folder("deleted"); @@ -506,6 +526,32 @@ fn trace_of_another_image_inside_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// An object moved or duplicated to the end of a tracing goes directly above its source image, +/// which stays the tracing's first child. +#[test] +fn an_object_placed_at_the_end_of_a_tracing_stays_above_its_source() { + let base = folder("at-end"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\ + r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATEND);\ + var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATEND);\ + vc.log(p.tracing.sourceArt.name); vc.log(d.rasterItems.length); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("src"), json!(2), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + let names: Vec> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect(); + let name = |n: &str| Some(n.to_string()); + assert_eq!(names[..3], [name("src"), name("moved"), name("moved")], "the source stays first: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_source_art_is_not_listed_with_the_images() { let base = folder("lists"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..3812314b26 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -178,6 +178,36 @@ fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() { let _ = std::fs::remove_dir_all(base); } +/// The defaults of the options a save or export does not map are named through their +/// enumerations, and an options object given them saves as one left as it was. +#[test] +fn option_defaults_are_named_through_their_enumerations() { + let base = folder("enum-defaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new PDFSaveOptions(); o.colorDownsamplingMethod = DownsampleMethod.NODOWNSAMPLE;\n\ + o.colorCompression = CompressionQuality.None; o.monochromeCompression = MonochromeCompression.None;\n\ + o.flattenOutput = OutputFlattening.PRESERVEAPPEARANCE; o.pDFXStandard = PDFXStandard.PDFXNONE;\n\ + d.saveAs(new File(dir + '/a.pdf'), o);\n\ + var v = new ExportOptionsSVG(); v.cssProperties = SVGCSSPropertyLocation.STYLEATTRIBUTES;\n\ + v.documentEncoding = SVGDocumentEncoding.ASCII; v.DTD = SVGDTDVersion.SVG1_1; v.fontType = SVGFontType.CEFFONT;\n\ + v.fontSubsetting = SVGFontSubsetting.ALLGLYPHS; d.exportFile(new File(dir + '/s'), ExportType.SVG, v);\n\ + vc.log([DownsampleMethod.BICUBICDOWNSAMPLE, CompressionQuality.ZIP8BIT, SVGCSSPropertyLocation.ENTITIES]);" + ), + ); + assert_eq!(out, json!([["DownsampleMethod.BICUBICDOWNSAMPLE", "CompressionQuality.ZIP8BIT", "SVGCSSPropertyLocation.ENTITIES"]])); + assert!(std::fs::read(dir.join("a.pdf")).unwrap().starts_with(b"%PDF-")); + assert!(dir.join("s.svg").is_file()); + let _ = std::fs::remove_dir_all(base); +} + /// A save that writes several files, such as an EPS with a file per artboard, writes none of them /// when one may not be written. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 8593d593aa..3beea4cfed 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -177,6 +177,44 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of the save and export options' defaults. + ( + "", + "ColorConversion ColorDestination ColorProfile CompressionQuality DownsampleMethod MonochromeCompression \ + OutputFlattening PDFChangesAllowedEnum PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes \ + SVGCSSPropertyLocation SVGDTDVersion SVGDocumentEncoding SVGFontSubsetting SVGFontType", + ), + ("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"), + ( + "ColorDestination.", + "COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \ + COLORDESTINATIONWORKINGRGB None", + ), + ("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"), + ( + "CompressionQuality.", + "AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM \ + AUTOMATICJPEG2000MEDIUM AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM \ + AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM \ + JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT", + ), + ("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"), + ("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"), + ("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"), + ( + "PDFChangesAllowedEnum.", + "CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE \ + CHANGE40ANYCHANGES CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT", + ), + ("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"), + ("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"), + ("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"), + ("PageMarksTypes.", "Japanese Roman"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"), + ("SVGDocumentEncoding.", "ASCII UTF16 UTF8"), + ("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"), + ("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"), // The enumerations of placed and raster items. ("", "ImageColorSpace RasterLinkState"), ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cf10f0035e..48f32b93d8 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,9 +253,13 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. The +/// layout in force chosen again changes nothing. fn set_layout(d: &mut Dialog, key: &str, v: Value) { let (lay, shown, ..) = layout(d); + if key == "layout" && v.as_str().and_then(ArtboardLayout::parse) == Some(lay) { + return; + } let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) @@ -935,7 +939,10 @@ mod tests { set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!(to)); - assert_eq!(field(&app, "artboardLayout"), json!({"layout": to, "columns": 3}), "{to}, rows {rows}"); + // The layout in force chosen again keeps the rows, and the columns follow them. + let kept = if to == "gridByColumn" { json!({"layout": to, "columns": 2, "rows": rows}) } else { json!({"layout": to, "columns": 3}) }; + assert_eq!(field(&app, "artboardLayout"), kept, "{to}, rows {rows}"); + assert_eq!(columns(&app), 3, "{to}, rows {rows}"); } } set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index c35a961aa3..ca44c496ac 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1674,16 +1674,24 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { } /// The object Trace acts on as the panel found it before [`find_target`]: every selected object put -/// in paint order, the first image or Image Trace object among them taken, else the first selected -/// object. +/// in paint order, the first image or Image Trace object among them taken (an Image Trace object's +/// source image is traced through that object, so it is skipped), else the first selected object +/// when it is neither. fn target_node_sorting_everything(app: &VectorcraftApp) -> Option { let st = app.session.active()?; - let traceable = |n: &&Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let traceable = |n: &Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let source = |id: NodeId| { + st.doc + .parent_of(id) + .and_then(|g| st.doc.node(g)) + .is_some_and(|g| is_trace(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id)) + }; st.selection .in_paint_order(&st.doc) .into_iter() - .find_map(|id| st.doc.node(id).filter(traceable).cloned()) - .or_else(|| first_selected(app).map(|n| (*n).clone())) + .filter(|id| !source(*id)) + .find_map(|id| st.doc.node(id).filter(|n| traceable(n)).cloned()) + .or_else(|| first_selected(app).filter(|n| !traceable(n)).map(|n| (*n).clone())) } /// [`Target`] from [`target_node_sorting_everything`] and a scan of the whole selection for Image @@ -1779,6 +1787,9 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { &["trace", "trace image"], &["trace image", "trace"], &["rect", "trace image"], + &["trace image"], + &["trace image", "rect"], + &["trace image", "front"], &["clip"], &["rect", "clipped"], &["outer"], diff --git a/docs/gaps.md b/docs/gaps.md index fc32f5b719..602b94f48a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, and its linked and embedded images (`placedItems` and - `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + `rasterItems`, with `PlacedItem` and `RasterItem`), and trace them with `trace()`, which gives the Image Trace + object as a `PluginItem` with its `TracingObject` and `TracingOptions`; the tracing options VectorCraft has no + setting for, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 00ad4fe8af..6730483bc9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2642,8 +2642,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot starts with the defaults that page gives. Its `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 - `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + `presetSettings` of `null` or `undefined` counts as omitted. Any other `presetSettings` that is not a + `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the profile and the reason, and makes no document. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, @@ -2656,7 +2656,8 @@ 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 with the anchors and Bézier handles of the object's paths, and of the shown paths in its groups and + compound paths; a clip group's come from its clipping path), `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 @@ -2717,7 +2718,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, - `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. + `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`, as + do the enumerations of the other options' defaults (`CompressionQuality`, `DownsampleMethod`, + `SVGCSSPropertyLocation` and the like), with the members + https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ lists. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is @@ -2777,7 +2781,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the - source image and the view, and a value the tracing already has runs no command. The `PluginItem`, `TracingObject` + source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or + `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `threshold` takes a whole number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`, From ab12c44ebd68a318df3962d4e88896d62c9fff94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:59:26 -0800 Subject: [PATCH 10/41] JavaScript: .js scripts run async functions and await A .js script now reads async function declarations and expressions, async arrow functions and async methods in object literals, as ECMA-262 2017 section 25.5 defines them. A call returns a Promise that the function's return resolves and an uncaught exception rejects. await suspends the function's frame until its operand settles; a promise job resumes it with the value, or throws the rejection at the await, so try, catch and finally work around it. - Options::es2017 turns the syntax on and implies Options::es2015; script.run sets it for .js files. .jsx scripts and source strings keep async and await as plain names. - A suspended frame is a heap object the collector traces, reached only from its promise reactions, so a function waiting on a promise that nothing can settle is freed. Each resume is a job and takes fuel. - AsyncFunction and its prototype exist without a global binding; async functions are not constructors and have no prototype property. - The test262 runner reads the async-function, await and async-arrow folders and counts runs with and without the option; an async test with a runtime negative now has to throw. --- crates/engine/src/script/include.rs | 5 +- crates/engine/src/script/mod.rs | 4 +- crates/engine/src/tests/script_run.rs | 23 +++ crates/js/src/ast.rs | 4 + crates/js/src/async_tests.rs | 159 +++++++++++++++ crates/js/src/builtins.rs | 19 +- crates/js/src/builtins/async_function.rs | 41 ++++ crates/js/src/builtins/promise.rs | 145 +++++++++++++- crates/js/src/bytecode.rs | 7 +- crates/js/src/compiler.rs | 14 +- crates/js/src/heap.rs | 14 +- crates/js/src/interp.rs | 109 ++++++++++- crates/js/src/interp/async_function.rs | 153 +++++++++++++++ crates/js/src/interp_tests.rs | 1 + crates/js/src/lib.rs | 26 ++- crates/js/src/parser.rs | 234 ++++++++++++++++++++--- crates/js/src/realm.rs | 8 + crates/js/tests/test262.rs | 134 ++++++++++++- docs/mcp.md | 12 ++ docs/target-app-parity.md | 1 + 20 files changed, 1047 insertions(+), 66 deletions(-) create mode 100644 crates/js/src/async_tests.rs create mode 100644 crates/js/src/builtins/async_function.rs create mode 100644 crates/js/src/interp/async_function.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index a024949a35..f380c6cbd7 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -221,7 +221,8 @@ pub(crate) struct Files { es2015: bool, } -/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] and +/// [`vectorcraft_js::Options::es2017`] when its file name ends in /// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as /// ECMAScript 5.1 with the ExtendScript extensions. pub(crate) fn es2015_script(path: Option<&str>) -> bool { @@ -326,7 +327,7 @@ impl Files { /// The options a file of this run is parsed with, preprocessor lines aside. pub(crate) fn options(&self) -> Options { - Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, es2017: self.es2015, ..Options::default() } } /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index a9c828532e..af62a9c5e6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1979,13 +1979,15 @@ impl Session { // A `.js` script's realm has the later editions' built-ins (`Promise`). A kept realm gets // them at the first `.js` run that names it, and keeps them as it keeps its globals. let es2015 = include::es2015_script(request.file.as_deref()); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; + // It also reads async functions and `await` (ECMAScript 2017). + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, es2017: es2015, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + realm.set_es2017(es2015); if es2015 { realm.add_es2015(); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..3d08a4f64d 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -331,6 +331,29 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("es2017"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let src = "async function twice(p) { return 2 * await p; }\nvar half = async x => x / 2;\n\ + twice(Promise.resolve(3)).then(function (v) { vc.log(v); });\n\ + (async function () { try { await Promise.reject(new Error('no')); } catch (e) { vc.log(await half(8) + e.message); } })();\n\ + vc.log('sync');\n"; + let r = s.execute("script.run", &path(&write("async.js", src))).unwrap(); + assert_eq!(r["log"], json!(["sync", 6, "4no"]), "{r}"); + for (name, text) in [("async.jsx", "async function f() {}"), ("arrow.jsx", "var f = async x => x;")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..6fa32e6253 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -218,6 +218,8 @@ pub enum Expr { /// `...expression` in an array literal or an argument list, and as the last of an arrow /// function's parenthesized parameters while they are read. Spread(ExprId), + /// `await operand`, in an async function's body. + Await(ExprId), } /// A piece of a template literal's text between its substitutions. @@ -393,6 +395,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// An async function (ECMAScript 2017): a call returns a promise, and its body may `await`. + pub is_async: bool, pub span: Span, } diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs new file mode 100644 index 0000000000..46656f1205 --- /dev/null +++ b/crates/js/src/async_tests.rs @@ -0,0 +1,159 @@ +//! Async functions and `await` in realms with [`Options::es2017`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2017: true, ..Options::default() }, Limits::default()) +} + +/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran. +fn log(src: &str) -> String { + let mut r = realm(); + if let Err(e) = r.run(&format!("var log = [];\n{src}")) { + panic!("{src}\n{e:?}"); + } + match r.run("log.join(' ')") { + Ok(JsValue::String(s)) => s, + other => panic!("{src}: {other:?}"), + } +} + +fn syntax_error(r: &mut Realm, src: &str) { + match r.run(src) { + Err(e) if e.kind == RunErrorKind::Syntax => {} + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn awaits_resume_in_the_job_order_promise_reactions_have() { + let src = "async function f() { log.push('f1'); await null; log.push('f2'); await null; log.push('f3'); }\n\ + f();\n\ + Promise.resolve().then(function () { log.push('t1'); }).then(function () { log.push('t2'); });\n\ + log.push('sync');"; + assert_eq!(log(src), "f1 sync f2 t1 f3 t2"); +} + +#[test] +fn the_function_returns_a_promise_its_return_resolves_and_its_throw_rejects() { + let src = "async function ok(x) { return x + 1; }\n\ + async function bad() { throw new TypeError('no'); }\n\ + var p = ok(1); log.push(p instanceof Promise);\n\ + p.then(function (v) { log.push('ok ' + v); });\n\ + bad().then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true ok 2 true"); +} + +#[test] +fn a_rejected_await_throws_where_it_stands_and_finally_runs_after_an_await() { + let src = "async function f() {\n\ + try { await Promise.reject('r'); log.push('not here'); }\n\ + catch (e) { log.push('caught ' + e); }\n\ + finally { await 1; log.push('finally'); }\n\ + return 'end';\n\ + }\n\ + f().then(function (v) { log.push(v); });"; + assert_eq!(log(src), "caught r finally end"); + let rethrow = "async function g() { try { await Promise.reject(new Error('x')); } finally { log.push('cleanup'); } }\n\ + g().catch(function (e) { log.push('rejected ' + e.message); });"; + assert_eq!(log(rethrow), "cleanup rejected x"); +} + +#[test] +fn arrows_expressions_and_methods_can_be_async() { + let src = "var a = async x => (await x) * 2;\n\ + var b = async (x, y) => { return await x + y; };\n\ + var c = async function named() { return typeof named; };\n\ + var o = { async m(v) { return this.k + await v; }, k: 'k' };\n\ + Promise.all([a(2), b(Promise.resolve(1), 2), c(), o.m('v')]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "4,3,function,kv"); +} + +#[test] +fn async_functions_are_not_constructors_and_have_no_prototype() { + let src = "async function f() {}\n\ + log.push(f.hasOwnProperty('prototype'));\n\ + try { new f(); } catch (e) { log.push(e instanceof TypeError); }\n\ + var AF = Object.getPrototypeOf(f).constructor;\n\ + log.push(AF !== Function, typeof AF, Object.getPrototypeOf(AF) === Function);\n\ + log.push(typeof this.AsyncFunction);\n\ + var g = AF('a', 'return await a;');\n\ + log.push(Object.getPrototypeOf(g) === Object.getPrototypeOf(f));\n\ + g(5).then(function (v) { log.push(v); });\n\ + log.push(String(async function h() { await 0; }));"; + assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5"); +} + +#[test] +fn await_is_an_identifier_outside_async_functions() { + let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\ + var async = function (x) { return x; }; log.push(async(1));\n\ + async\nfunction g() {}\n\ + log.push(typeof g);"; + assert_eq!(log(src), "3 1 function"); + // A function in an async arrow function's parameters reads `await` as its own body does, + // and an async function declared in a script may be named `await`. + let nested = "var g = async (x = function () { return await; }) => x;\n\ + var h = async (x = async function () { await 0; }) => x;\n\ + async function await() { return 1; }\n\ + log.push(typeof g, typeof h, typeof await);"; + assert_eq!(log(nested), "function function function"); + let mut r = realm(); + syntax_error(&mut r, "async function f() { var await; }"); + syntax_error(&mut r, "async function f(await) {}"); + syntax_error(&mut r, "async function f(x = await 1) {}"); + syntax_error(&mut r, "function f() { await 1; }"); + syntax_error(&mut r, "if (1) async function f() {}"); + syntax_error(&mut r, "async (x = await 1) => x"); + syntax_error(&mut r, "async\n(x) => x"); + syntax_error(&mut r, "async (a = (...await) => {}) => {}"); +} + +#[test] +fn a_suspended_function_survives_a_collection_and_an_unreachable_one_is_freed() { + let mut r = realm(); + r.run( + "var resume; var gate = new Promise(function (res) { resume = res; });\n\ + var out = [];\n\ + async function f() { var local = { n: 41 }; var v = await gate; out.push(local.n + v); }\n\ + f();", + ) + .unwrap(); + r.interp().collect_garbage(); + r.run("resume(1);").unwrap(); + assert_eq!(r.run("out.join()").unwrap(), JsValue::String("42".into())); + // A function waiting on a promise nothing can settle is collected with it. + r.interp().collect_garbage(); + let before = r.interp().heap.live_cells(); + r.run("(function () { async function w() { var big = []; for (var i = 0; i < 200; i++) big.push({ i: i }); await new Promise(function () {}); } w(); })();") + .unwrap(); + r.interp().collect_garbage(); + let after = r.interp().heap.live_cells(); + assert!(after < before + 50, "{before} {after}"); +} + +#[test] +fn a_run_that_ends_with_awaits_pending_ends_cleanly() { + let mut r = realm(); + let v = r.run("async function f() { await new Promise(function () {}); return 1; } f(); 'done'").unwrap(); + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); + assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn each_resume_takes_fuel() { + let mut r = realm(); + r.set_limits(Limits { fuel: 20_000, ..Limits::default() }); + let e = r.run("async function f() { for (;;) await 0; } f();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); +} + +#[test] +fn es5_and_extendscript_realms_do_not_read_async_functions() { + let mut es2015 = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()); + syntax_error(&mut es2015, "async function f() {}"); + assert_eq!(es2015.run("var async = 1, await = 2; async + await").unwrap(), JsValue::Number(3.0)); + syntax_error(&mut Realm::with_options(Options::default(), Limits::default()), "async function f() {}"); + syntax_error(&mut Realm::new(), "var f = async () => 1;"); +} diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 26b351e14a..09cb089e5b 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -10,6 +10,7 @@ //! run past [`crate::Limits`]. mod array; +mod async_function; pub(crate) mod extensions; mod global; mod json; @@ -464,7 +465,16 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + dynamic_function(interp, args, false) +} + +/// The function `Function(p1, …, body)` makes, or with `is_async` the async function that +/// `AsyncFunction(p1, …, body)` makes from `(async function anonymous(p1,…\n) {\nbody\n})` +/// (ECMA-262 2017 section 25.5.1.1). An async function's source is read with +/// [`crate::Options::es2017`] whatever the realm reads scripts with, since only an async function +/// leads a script to `AsyncFunction`. +pub(crate) fn dynamic_function(interp: &mut Interp, args: &[Value], is_async: bool) -> JsResult { + let head: &str = if is_async { "(async function anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -476,12 +486,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -494,7 +504,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.observe_code(&units); interp.source_units = interp.source_units.saturating_add(units.len()); let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len())); - let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() }; + let es2017 = interp.options.es2017 || is_async; + let options = crate::Options { strict: false, max_source_units: remaining, es2017, ..interp.options.clone() }; let program = match crate::parse_utf16(&units, &options) { Ok(p) => p, Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)), diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs new file mode 100644 index 0000000000..43eea77b2a --- /dev/null +++ b/crates/js/src/builtins/async_function.rs @@ -0,0 +1,41 @@ +//! `AsyncFunction` and its prototype (ECMA-262 2017 section 25.5, +//! ), in realms with +//! [`crate::Options::es2015`]: the prototype of every async function, and the constructor a script +//! reaches through it. `AsyncFunction` is not a global. + +use super::{data, dynamic_function, native}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, ObjId, Object}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +/// Creates `AsyncFunction` and `AsyncFunction.prototype`, keeping the prototype for the async +/// functions the realm makes. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let function_proto = interp.intrinsics.function_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + interp.promises.async_function_proto = Some(proto); + let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?; + interp.promises.async_function_ctor = Some(ctor); + // `Function` is the constructor's prototype (section 25.5.2). + let function_ctor = constructor_of(interp, function_proto); + if let Some(o) = interp.heap.object_mut(ctor) { + o.proto = function_ctor.or(o.proto); + } + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary + // built-in prototypes. + data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) +} + +/// The `constructor` property `proto` has from the built-ins, when it is an object. +fn constructor_of(interp: &Interp, proto: ObjId) -> Option { + match interp.get_own_property(proto, &crate::heap::key("constructor")) { + Ok(Some(crate::heap::Prop::Data { value: Value::Object(o), .. })) => Some(o), + _ => None, + } +} + +/// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). +fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index d960fac60b..53d08f6f06 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -142,6 +142,8 @@ enum Then { Settle(ObjId), /// An exception rejects through this resolving record. Reject(ObjId), + /// An async function goes on after `await`; its own promise takes its result. + Resume, } /// The built-in functions a promise operation's functions call, with their record. @@ -156,9 +158,11 @@ enum Kind { CatchFinally, ValueThunk, Thrower, + AwaitFulfilled, + AwaitRejected, } -const KINDS: [(Kind, NativeFn); 9] = [ +const KINDS: [(Kind, NativeFn); 11] = [ (Kind::Resolve, resolve_function), (Kind::Reject, reject_function), (Kind::AllElement, all_element), @@ -168,6 +172,8 @@ const KINDS: [(Kind, NativeFn); 9] = [ (Kind::CatchFinally, catch_finally), (Kind::ValueThunk, value_thunk), (Kind::Thrower, thrower), + (Kind::AwaitFulfilled, await_continuation), + (Kind::AwaitRejected, await_continuation), ]; /// `Promise`'s objects and the run's job queue. @@ -186,11 +192,17 @@ pub(crate) struct Promises { rejected: Vec, /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). pub(crate) max_jobs: usize, + /// `AsyncFunction.prototype` (ECMA-262 2017 section 25.5.3), the prototype of async functions. + pub(crate) async_function_proto: Option, + /// `AsyncFunction` (section 25.5.1), which is not a global. + pub(crate) async_function_ctor: Option, } impl Default for Promises { fn default() -> Self { Self { + async_function_proto: None, + async_function_ctor: None, proto: None, ctor: None, natives: Vec::new(), @@ -208,10 +220,11 @@ impl Promises { /// Adds what the queue and the promise objects hold to the collector's roots. pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); + roots.objects.extend(self.async_function_proto.iter().chain(&self.async_function_ctor)); roots.values.extend(self.completion.iter()); match &self.running { Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), - None => {} + Some(Then::Resume) | None => {} } for job in &self.queue { match job { @@ -259,7 +272,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { let n = native(interp, "", f, 1, NativeKind::Plain, false)?; interp.promises.natives.push(n); } - Ok(()) + super::async_function::install(interp) } /// Turns on [`crate::Options::es2015`] in a realm made without it and creates `Promise` there, @@ -552,6 +565,120 @@ fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult }) } +// ---- async functions ---- + +/// The built-in a suspended async function's reactions are bound to. The job queue resumes the +/// function instead of calling it, and scripts cannot reach it. +fn await_continuation(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(Abrupt::Internal("an await continuation was called".into())) +} + +impl Interp { + /// Settles the promise of an async function whose frame ends: its return value resolves it, + /// and the exception that leaves it rejects it. + pub(crate) fn settle_async(&mut self, p: ObjId, r: Result) -> JsResult<()> { + match r { + Ok(v) => resolve_promise(self, p, v), + Err(e) => { + let site = caught(self); + reject_promise(self, p, e, site) + } + } + } + + /// A new pending promise for the async function call whose frame is on top. + pub(crate) fn new_async_promise(&mut self) -> JsResult { + new_promise(self) + } + + /// `await v` in the async function the top frame runs (Await, ECMA-262 2017 section 6.2.3.1, + /// with PromiseResolve as later editions have it): `v` becomes a built-in promise, the frame + /// is suspended until it settles, and the function's call gives its promise, `Some` when the + /// frame was the boundary frame. Throws at the `await` when reading `v`'s `constructor` throws. + pub(crate) fn await_value(&mut self, v: Value) -> JsResult> { + if self.async_promise().is_none() { + return Err(Abrupt::Internal("await outside an async function".into())); + } + let ctor = self.promises.ctor.map_or(Value::Undefined, Value::Object); + scoped(self, |interp| { + let p = promise_resolve(interp, &ctor, v)?; + root(interp, &p); + let Value::Object(p) = p else { return Err(Abrupt::Internal("PromiseResolve gave a value that is not a promise".into())) }; + let bytes = interp.suspend_bytes(); + interp.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let act = interp.heap.alloc_object(Object::new(Class::Activation(None), None)); + root(interp, &Value::Object(act)); + let on_fulfilled = record_function(interp, Kind::AwaitFulfilled, act, 1)?; + root(interp, &on_fulfilled); + let on_rejected = record_function(interp, Kind::AwaitRejected, act, 1)?; + root(interp, &on_rejected); + // The reactions settle no promise of their own; this one stays pending and unseen. + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + promise_data(interp, derived)?.handled = true; + perform_then(interp, p, on_fulfilled, on_rejected, derived)?; + let (a, boundary) = interp.suspend_frame()?; + let promise = a.promise; + let held = a.bytes(); + if let Some(o) = interp.heap.object_mut(act) { + o.class = Class::Activation(Some(Box::new(a))); + } + interp.heap.bytes = interp.heap.bytes.saturating_add(held); + if boundary { + return Ok(Some(Value::Object(promise))); + } + interp.push(Value::Object(promise))?; + Ok(None) + }) + } + + /// The activation `handler` resumes when it is a suspended async function's reaction, and + /// whether it is the rejection's. + fn await_activation(&self, handler: &Value) -> Option<(ObjId, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let reject = if self.promises.natives.get(Kind::AwaitFulfilled as usize) == Some(target) { + false + } else if self.promises.natives.get(Kind::AwaitRejected as usize) == Some(target) { + true + } else { + return None; + }; + match args.first() { + Some(Value::Object(act)) => Some((*act, reject)), + _ => None, + } + } + + /// Resumes the async function `handler` belongs to with the settled value: its frame goes back + /// on top as a boundary frame the caller runs, and a rejection is thrown at its `await`. A job + /// that finds the frame already resumed does nothing. + fn resume_async(&mut self, handler: &Value, argument: Value, reject: bool, site: Option) -> JsResult<()> { + let Some((act, _)) = self.await_activation(handler) else { return Err(Abrupt::Internal("not an await reaction".into())) }; + let taken = match self.heap.object_mut(act).map(|o| &mut o.class) { + Some(Class::Activation(slot)) => slot.take(), + _ => return Err(Abrupt::Internal("an await reaction lost its activation".into())), + }; + let Some(a) = taken else { return Ok(()) }; + self.heap.bytes = self.heap.bytes.saturating_sub(a.bytes()); + self.restore_frame(*a)?; + self.promises.running = Some(Then::Resume); + if !reject { + return self.push(argument); + } + if site.is_some() { + self.throw_site = site; + } + match self.unwind_or_abort(argument) { + Ok(Some(v)) => self.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => self.finish_job(Err(e)), + Err(e) => Err(e), + } + } +} + // ---- the job queue ---- impl Interp { @@ -627,6 +754,10 @@ impl Interp { self.use_fuel()?; scoped(self, |interp| { let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, site, .. } if interp.await_activation(&handler).is_some() => { + root(interp, &argument); + return interp.resume_async(&handler, argument, reject, site); + } Job::Reaction { handler, argument, reject, derived, site } => { if !interp.is_callable(&handler) { return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; @@ -660,7 +791,7 @@ impl Interp { match (then, r) { (Then::Settle(d), Ok(v)) => resolve_promise(self, d, v), (Then::Settle(d), Err(e)) => reject_promise(self, d, e, site), - (Then::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(_), Ok(_)) | (Then::Resume, _) => Ok(()), (Then::Reject(rec), Err(e)) => scoped(self, |interp| { root(interp, &Value::Object(rec)); reject_through(interp, rec, e, site) @@ -835,8 +966,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -845,7 +976,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { .. } => return Ok(true), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.is_async), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..723ad84b40 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -205,6 +205,9 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `value` → its awaited value: suspends the running async function until the value settles, + /// and goes on with its fulfillment value or throws its rejection reason here. + Await, } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -299,6 +302,8 @@ pub(crate) struct Code { /// The function has default or rest parameters: its parameters start uninitialized, its /// code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The code is an async function's: a call returns a promise, and it may run [`Op::Await`]. + pub(crate) is_async: bool, } impl Code { @@ -380,7 +385,7 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1), Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), - Op::ToStr => e(1, 1), + Op::ToStr | Op::Await => e(1, 1), }) } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..dac56b9359 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -268,12 +268,14 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some(f) = self.ast.function(*fid) else { return internal("function out of range") }; + let Some(name) = f.name.as_ref() else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations a variable, not async ones. + if !self.strict && !f.is_async { annex.push((k, scope, id)); } } else { @@ -1158,6 +1160,11 @@ impl<'a> FnCompiler<'a> { Expr::Template { quasis, exprs } => self.template(quasis, exprs)?, Expr::TaggedTemplate { .. } => self.chain(id)?, Expr::Spread(_) => return internal("spread outside an array literal or argument list"), + Expr::Await(arg) => { + self.expr(*arg)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::Await); + } Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?, Expr::Unary { .. } => self.unary(id)?, Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?, @@ -1762,6 +1769,7 @@ impl<'a> FnCompiler<'a> { arrow: meta.arrow, uses_this: self.uses_this, param_init: meta.param_init, + is_async: meta.is_async, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -1780,6 +1788,7 @@ struct Meta { length: u32, arrow: bool, param_init: bool, + is_async: bool, } fn len_u32(n: usize) -> u32 { @@ -1844,6 +1853,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, length: len_u32(length), arrow: f.kind == FunctionKind::Arrow, param_init, + is_async: f.is_async, }; c.finish(hoisted, meta) } diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index a1af2cd0bd..e25bac7323 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -250,6 +250,8 @@ pub(crate) enum Class { Promise(Box), /// The state that the functions a promise operation makes share; scripts never see it. PromiseRecord(Box), + /// An async function's frame waiting at `await`, until it is resumed; scripts never see it. + Activation(Option>), } /// What an XML value is. @@ -313,7 +315,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::XmlFilter(_) | Class::PromiseRecord(_) | Class::Activation(_) => "Object", Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", @@ -728,6 +730,16 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } extra = crate::builtins::promise::RECORD_BYTES; } + Class::Activation(Some(a)) => { + for v in a.values() { + mark_value(v, work, strings); + } + work.extend(a.ids()); + for code in a.codes() { + mark_code(code, strings); + } + extra = a.bytes(); + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 8c77936da5..783fd80f95 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -184,11 +184,16 @@ pub(crate) struct Frame { completion: Value, /// Returning from this frame returns from the Rust call that pushed it. boundary: bool, + /// The promise of the async function the frame runs: a return resolves it, an exception + /// that leaves the frame rejects it, and the call's value is the promise. + async_promise: Option, } /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +pub(crate) mod async_function; + /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -502,7 +507,8 @@ fn is(k: &[u16], s: &str) -> bool { } impl Interp { - pub(crate) fn new(options: Options, limits: Limits) -> Self { + pub(crate) fn new(mut options: Options, limits: Limits) -> Self { + options.es2015 = options.modern(); let mut heap = Heap::default(); let global = heap.alloc_object(Object::new(Class::Ordinary, None)); let global_env = heap.alloc_env(Env::Obj { object: global, with_this: false, outer: None }); @@ -787,7 +793,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.async_promise.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -816,7 +822,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(v), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(v); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -835,7 +845,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(Some(v)), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(Some(v)); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -870,10 +884,26 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::Await => { + let v = self.pop()?; + self.await_value(v) + } _ => self.exec(op).map(|()| None), } } + /// [`Self::unwind`], ending the frames down to the boundary frame when it fails with a limit + /// or an internal error, which leaves the frame it was in on top. + pub(crate) fn unwind_or_abort(&mut self, v: Value) -> JsResult> { + match self.unwind(v) { + Err(e @ (Abrupt::Limit(_) | Abrupt::Internal(_))) => { + self.abort_to_boundary(); + Err(e) + } + r => r, + } + } + fn note_site(&mut self) { if self.throw_site.is_none() && let Some(f) = self.frames.last() @@ -884,7 +914,10 @@ impl Interp { /// Finds the handler for an exception: in the top frame, or in the frames below it up to the /// boundary frame. Returns the exception when no handler takes it before the boundary frame. - fn unwind(&mut self, v: Value) -> JsResult<()> { + /// An async function's frame without a handler rejects its promise with the exception and + /// returns the promise as a `return` would: `Some` with it when that frame was the boundary + /// frame. + fn unwind(&mut self, v: Value) -> JsResult> { self.note_site(); let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed @@ -920,10 +953,25 @@ impl Interp { if let (false, Some(site)) = (caught, site) { self.finally_sites.push((site, target_len)); } - return Ok(()); + return Ok(None); + } + // The promise is settled while the frame is still on top, so a limit reached doing it + // ends the frames the way any other limit does. + let promise = frame.async_promise; + if let Some(p) = promise { + self.settle_async(p, Err(v.clone()))?; } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + if let Some(p) = promise { + self.drop_left_finally_marks(); + self.drop_left_finally_sites(frame.base); + if frame.boundary { + return Ok(Some(Value::Object(p))); + } + self.push(Value::Object(p))?; + return Ok(None); + } if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -947,6 +995,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // An async function's return resolves its promise, while the frame is still on top, and + // the call gives the promise. + let v = match self.async_promise() { + Some(p) => { + self.settle_async(p, Ok(v))?; + Value::Object(p) + } + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); // A `return` in a finally block leaves the block, and the value takes its exception's slot. @@ -1100,7 +1157,7 @@ impl Interp { self.replace(1, Value::String(s)) } Op::TemplateObject(i) => self.op_template_object(i), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Return | Op::ReturnCompletion | Op::Await => internal("return reached the dispatcher"), } } @@ -2095,17 +2152,30 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let is_async = code.is_async; + let proto = match self.promises.async_function_proto { + Some(p) if is_async => p, + _ => self.intrinsics.function_proto, + }; let length = code.length; let strict = code.strict; let arrow = code.arrow; let self_name = code.self_name.clone(); let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto))); self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; - // An arrow function has no `prototype` and cannot be constructed (section 14.2.16). + // An arrow function has no `prototype` and cannot be constructed (section 14.2.16), and + // neither has nor can an async function (ECMA-262 2017 section 25.5.4). An async function + // must not have own `caller` or `arguments` properties, restricted or not, in sloppy code + // too (section 16.2). if arrow { return Ok(f); } + if is_async { + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } let p = self.new_object(); self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; @@ -2701,6 +2771,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.is_async => Err(self.type_error("an async function is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; let proto = match self.get_from(callee, &key("prototype"), &f)? { @@ -2764,6 +2835,7 @@ impl Interp { } }; let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?; + let code_is_async = code.is_async; let base = self.stack.len(); self.frames.push(Frame { code, @@ -2777,7 +2849,16 @@ impl Interp { construct, completion: Value::Undefined, boundary, + async_promise: None, }); + // An async function's call makes its promise first thing (section 25.5.5.2); the frame + // keeps what the function holds reachable while it is made. + if code_is_async && let Err(e) = self.start_async_call() { + if let Some(frame) = self.frames.pop() { + self.stack.truncate(frame.base); + } + return Err(e); + } Ok(()) } @@ -3135,9 +3216,16 @@ impl Interp { self.global_lex } - /// Sets [`Options::es2015`] for the next runs. + /// Sets [`Options::es2015`] for the next runs; turning it off turns [`Options::es2017`] off too. pub(crate) fn set_es2015(&mut self, es2015: bool) { self.options.es2015 = es2015; + self.options.es2017 &= es2015; + } + + /// Sets [`Options::es2017`] for the next runs; turning it on turns [`Options::es2015`] on too. + pub(crate) fn set_es2017(&mut self, es2017: bool) { + self.options.es2017 = es2017; + self.options.es2015 |= es2017; } /// Declares a script's top-level `let` and `const` names in the global scope, uninitialized @@ -3213,6 +3301,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + async_promise: None, }); Ok(()) } diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs new file mode 100644 index 0000000000..7121215b9d --- /dev/null +++ b/crates/js/src/interp/async_function.rs @@ -0,0 +1,153 @@ +//! An async function's frame while it waits at `await` (ECMA-262 2017 sections 25.5 and 6.2.3.1, +//! ): [`Interp::suspend_frame`] moves the running +//! frame, its operands and its pending `finally` state into an [`Activation`], which lives on the +//! heap inside the functions that resume it, and [`Interp::restore_frame`] puts it back on top of +//! the frames to go on. An activation that nothing can resume any more is collected like any +//! other object. + +use std::rc::Rc; + +use super::{Frame, Interp, JsResult, ThrowSite, internal}; +use crate::bytecode::Code; +use crate::heap::{EnvId, ObjId}; +use crate::value::Value; + +/// The estimated bytes of an activation, beyond the object and its operands. +pub(crate) const ACTIVATION_BYTES: usize = 128; +/// The estimated bytes of each operand, `finally` mark or `finally` site an activation keeps. +pub(crate) const SLOT_BYTES: usize = 16; + +/// A suspended frame. Stack slots in `marks` and `sites` count from the frame's first operand. +#[derive(Clone)] +pub(crate) struct Activation { + code: Rc, + pc: usize, + env: EnvId, + var_env: EnvId, + env_depth: u32, + this: Value, + callee: Option, + completion: Value, + /// The promise the async function's call returned. + pub(crate) promise: ObjId, + stack: Vec, + marks: Vec<(ObjId, u32, usize)>, + sites: Vec<(ThrowSite, usize)>, +} + +impl Activation { + /// The values the activation holds, for the collector. + pub(crate) fn values(&self) -> impl Iterator { + self.stack.iter().chain([&self.this, &self.completion]) + } + + /// The objects and environments the activation holds, for the collector. + pub(crate) fn ids(&self) -> impl Iterator { + self.callee.iter().chain([&self.promise]).chain(self.marks.iter().map(|(o, _, _)| o)).map(|o| o.0).chain([self.env.0, self.var_env.0]) + } + + /// The code the activation runs and the code of its `finally` sites, for the collector. + pub(crate) fn codes(&self) -> impl Iterator { + std::iter::once(&*self.code).chain(self.sites.iter().map(|((code, _), _)| &**code)) + } + + /// The estimated bytes of the activation, beyond the object. + pub(crate) fn bytes(&self) -> usize { + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(self.stack.len() + self.marks.len() + self.sites.len())) + } +} + +impl Interp { + /// The promise of the async function the top frame runs, when it runs one. + pub(crate) fn async_promise(&self) -> Option { + self.frames.last().and_then(|f| f.async_promise) + } + + /// Makes the promise of the async function call whose frame was just pushed. + pub(crate) fn start_async_call(&mut self) -> JsResult<()> { + let p = self.new_async_promise()?; + match self.frames.last_mut() { + Some(f) => { + f.async_promise = Some(p); + Ok(()) + } + None => internal("an async call without a frame"), + } + } + + /// The bytes [`Self::suspend_frame`] will move off the operand stack, for the heap check made + /// before it. + pub(crate) fn suspend_bytes(&self) -> usize { + let Some(f) = self.frames.last() else { return ACTIVATION_BYTES }; + let n = self.stack.len().saturating_sub(f.base) + + self.finally_marks.iter().filter(|&&(_, _, s)| s >= f.base).count() + + self.finally_sites.iter().filter(|&&(_, s)| s >= f.base).count(); + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(n)) + } + + /// Takes the top frame, which runs an async function, off the frames with its operands and + /// its `finally` state. Gives the activation and whether the frame was a boundary frame. + pub(crate) fn suspend_frame(&mut self) -> JsResult<(Activation, bool)> { + let Some(frame) = self.frames.pop() else { return internal("await without a frame") }; + let Some(promise) = frame.async_promise else { return internal("await outside an async function") }; + let base = frame.base; + if self.stack.len() < base { + return internal("frame operands below the stack"); + } + let stack = self.stack.split_off(base); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(o, mark, slot)| { + if slot < base { + return true; + } + marks.push((o, mark, slot - base)); + false + }); + let at = self.finally_sites.iter().position(|&(_, slot)| slot >= base).unwrap_or(self.finally_sites.len()); + let sites = self.finally_sites.split_off(at).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let activation = Activation { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + promise, + stack, + marks, + sites, + }; + Ok((activation, frame.boundary)) + } + + /// Puts a suspended frame back on top of the frames as a boundary frame, with its operands at + /// the top of the operand stack. + pub(crate) fn restore_frame(&mut self, a: Activation) -> JsResult<()> { + if self.frames.len() >= self.limits.frames { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Frames)); + } + let base = self.stack.len(); + for v in a.stack { + self.push(v)?; + } + self.finally_marks.extend(a.marks.into_iter().map(|(o, mark, slot)| (o, mark, slot + base))); + self.finally_sites.extend(a.sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.frames.push(Frame { + code: a.code, + pc: a.pc, + base, + env: a.env, + var_env: a.var_env, + env_depth: a.env_depth, + this: a.this, + callee: a.callee, + construct: None, + completion: a.completion, + boundary: true, + async_promise: Some(a.promise), + }); + Ok(()) + } +} diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index d0bed32c1d..4a281a7b2f 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -983,6 +983,7 @@ fn code(ops: Vec) -> Code { arrow: false, uses_this: false, param_init: false, + is_async: false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 3bc60375e9..36577c7960 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -63,6 +63,10 @@ //! jobs a script queues run in order once its code has ended, before its run ends, on the run's //! limits; a promise still rejected with no handler at the end is reported by //! [`Realm::unhandled_rejections`]. +//! +//! With [`Options::es2017`], the parser and the realm also read and run async functions and +//! `await` (ECMA-262 2017 section 25.5, ). +//! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] pub mod ast; @@ -126,11 +130,29 @@ pub struct Options { /// Give a realm the later editions' built-ins this engine has: `Promise` and its job queue. /// Off, a realm has the ES5.1 built-ins only, as ExtendScript scripts expect. pub es2015: bool, + /// Also read and run async functions and `await` (ECMAScript 2017). It turns on + /// [`Options::es2015`] too, whatever that field says. Off, `async` and `await` are identifiers. + pub es2017: bool, +} + +impl Options { + /// [`Options::es2015`], which [`Options::es2017`] turns on too. + pub(crate) fn modern(&self) -> bool { + self.es2015 || self.es2017 + } } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } + Self { + strict: false, + preprocessor_lines: false, + max_depth: DEFAULT_MAX_DEPTH, + max_source_units: 64 << 20, + e4x: false, + es2015: false, + es2017: false, + } } } @@ -226,6 +248,8 @@ impl LineTable { } } +#[cfg(test)] +mod async_tests; #[cfg(test)] mod builtins_tests; #[cfg(test)] diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index db034d1e2d..c2ce5505b3 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -36,6 +36,21 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is an async function's body: `await` is an operator, not an identifier. + in_async: bool, + /// The code is an async function's parameters: `await` is neither an operator nor an + /// identifier there (ECMA-262 2017 section 14.6.1). + async_params: bool, +} + +/// What the parser noted about a parenthesized expression or a call to `async` that may turn out +/// to be an arrow function's head. +#[derive(Clone, Copy, Debug)] +struct Head { + /// A line break comes between `async` and `(`. + line_break: bool, + /// The parentheses hold an `await` expression or the identifier `await`. + awaits: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -72,6 +87,8 @@ enum BinKind { enum Prefix { Unary(UnaryOp), Update(UpdateOp), + /// `await`, in an async function's body. + Await, } pub(crate) struct Parser<'s> { @@ -101,11 +118,20 @@ pub(crate) struct Parser<'s> { es2015: bool, /// The scopes open around the current token, outermost first (only with `es2015`). scopes: Vec, + /// Read async functions and `await` ([`crate::Options::es2017`]). + es2017: bool, + /// How many `await` expressions and `await` identifiers have been read. + awaits: u32, + /// The parenthesized expressions and calls to `async` read so far that may be arrow heads. + heads: HashMap, + /// The last identifier expression read from an `async` written without escapes. + async_ident: Option, } impl<'s> Parser<'s> { pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result { - let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(options.es2015); + let es2015 = options.modern(); + let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(es2015); let placeholder = Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false }; let mut parser = Self { @@ -123,8 +149,12 @@ impl<'s> Parser<'s> { function_allowed: false, in_list: false, e4x: options.e4x, - es2015: options.es2015, - scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2015, + scopes: if es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2017: options.es2017, + awaits: 0, + heads: HashMap::new(), + async_ident: None, }; parser.tok = parser.next_significant()?; Ok(parser) @@ -266,9 +296,23 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if name == "await" && (self.ctx.in_async || self.ctx.async_params) { + return Err(self.error_at_token(token, "'await' cannot be an identifier in an async function")); + } Ok(()) } + /// The current token is `async` written without escapes, read as the start of an async + /// function or arrow function only with [`crate::Options::es2017`]. + fn at_async(&self) -> bool { + self.es2017 && self.tok.ident() == Some("async") && !self.tok.escaped + } + + /// The current token is `async` and `function` follows it on the same line: an async function. + fn at_async_function(&self) -> bool { + self.at_async() && self.peek().is_some_and(|t| t.is_keyword(Keyword::Function) && !t.newline_before) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -280,6 +324,9 @@ impl<'s> Parser<'s> { if self.ctx.strict && is_eval_or_arguments(&name) { return Err(self.error_at_token(&self.tok, format!("'{name}' cannot be declared in strict mode"))); } + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } let token = self.bump()?; Ok(Name { name, span: token.span }) } @@ -341,7 +388,11 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some(f) = self.ast.function(id) else { return Ok(()) }; + let Some(name) = f.name.clone() else { return Ok(()) }; + // An async function in a block never repeats another name (Annex B.3.3.4 covers plain + // function declarations only). + let plain = !f.is_async; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -350,7 +401,7 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + Some(_) => self.declare_lexical(&name, plain), None => Ok(()), } } @@ -457,7 +508,7 @@ impl<'s> Parser<'s> { /// A source element: a function declaration or a statement. fn parse_statement_item(&mut self) -> Result { - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.parse_function_declaration(); self.leave(); @@ -509,6 +560,9 @@ impl<'s> Parser<'s> { } self.parse_function_declaration() } + TokenKind::Ident(_) if self.at_async_function() => { + Err(self.error_at_token(&self.tok, "an async function declaration cannot stand here; put it in a block")) + } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), _ => self.plain_statement(start), } @@ -959,9 +1013,11 @@ impl<'s> Parser<'s> { // ---- functions ---- fn parse_function_declaration(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, is_async)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -977,15 +1033,30 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `is_async`, an async function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + is_async: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with `await` as the function has it, then the code around + // them goes on as it was. + // An `await` inside the function does not count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = false; + self.ctx.async_params = is_async; + let result = self.function_rest(kind, name, start, is_async); + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, is_async: bool) -> Result { self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1025,7 +1096,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1034,13 +1105,18 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let span = self.span_from(start); + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, is_async, span }; + // An async declaration or expression takes FormalParameters as a plain function does + // (ECMA-262 2017 section 14.6): repeated simple names are an error only in strict code. + // Arrow functions and async methods reject every repeat. self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } - /// An arrow function's body and the function, from `=>`, with its parameters read. - fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool) -> Result { + /// An arrow function's body and the function, from `=>`, with its parameters read; with + /// `is_async`, an async arrow function's. + fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool, is_async: bool) -> Result { if self.tok.newline_before { return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'")); } @@ -1048,7 +1124,7 @@ impl<'s> Parser<'s> { self.enter()?; let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let block = self.at(Punct::LBrace); @@ -1066,7 +1142,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, is_async, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1081,6 +1158,13 @@ impl<'s> Parser<'s> { Some(Expr::Sequence(list)) => list.clone(), _ => vec![*inner], }; + self.arrow_items(items) + } + + /// The parameters the items of an arrow function's head give: names, names with `= default`, + /// and a last `...name`. + fn arrow_items(&self, items: Vec) -> Result { + let invalid = |at: ExprId| self.error_at_offset(self.ast.expr_span(at).start, "invalid arrow function parameters"); let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None); let name_of = |id: ExprId| match self.ast.expr(id) { Some(Expr::Ident(n)) => Some(Name { name: n.clone(), span: self.ast.expr_span(id) }), @@ -1181,7 +1265,9 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; + // `async` followed on its line by a name starts an async arrow function. + let async_name = self.at_async() && self.peek().is_some_and(|t| matches!(t.kind, TokenKind::Ident(_)) && !t.newline_before); + let mut expr = if async_name { self.parse_async_name_arrow(no_in)? } else { self.parse_conditional(no_in)? }; if self.es2015 && self.at(Punct::Arrow) { expr = self.arrow_from(expr, no_in)?; } @@ -1203,12 +1289,39 @@ impl<'s> Parser<'s> { /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); - let params = match self.ast.expr(expr) { - Some(Expr::Ident(name)) => (vec![Name { name: name.clone(), span: start }], vec![None], None), - Some(Expr::Paren(_)) => self.arrow_params(expr)?, + let head = self.heads.get(&expr).copied(); + let (params, is_async) = match self.ast.expr(expr) { + Some(Expr::Ident(name)) => ((vec![Name { name: name.clone(), span: start }], vec![None], None), false), + Some(Expr::Paren(_)) => (self.arrow_params(expr)?, false), + // `async (…) =>` was read as a call to `async` (ECMA-262 2017 section 14.7). + Some(Expr::Call { args, .. }) if head.is_some() => { + if head.is_some_and(|h| h.line_break) { + return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function")); + } + (self.arrow_items(args.clone())?, true) + } _ => return Err(self.unexpected()), }; - self.parse_arrow(start, params, no_in) + // `await` cannot be an arrow function's parameter, or stand in one's default value, + // where it is an operator or in an async arrow function's head. + if head.is_some_and(|h| h.awaits) && (is_async || self.ctx.in_async) { + return Err(self.error_at_offset(start.start, "'await' cannot stand in an arrow function's parameters here")); + } + self.parse_arrow(start, params, no_in, is_async) + } + + /// `async name => …` from `async` (ECMA-262 2017 section 14.7): the one parameter is read as + /// an async function's is. + fn parse_async_name_arrow(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + let async_params = std::mem::replace(&mut self.ctx.async_params, true); + let param = self.binding_identifier(); + self.ctx.async_params = async_params; + let param = param?; + if !self.at(Punct::Arrow) { + return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok)))); + } + self.parse_arrow(start, (vec![param], vec![None], None), no_in, true) } /// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code @@ -1278,7 +1391,17 @@ impl<'s> Parser<'s> { /// Prefix operators, read with a loop and applied innermost first. fn parse_unary(&mut self) -> Result { let mut prefixes = Vec::new(); - while let Some(prefix) = prefix_op(&self.tok) { + loop { + // In an async function's body, `await` is a prefix operator (ECMA-262 2017 section 14.6). + let prefix = if self.ctx.in_async && self.tok.ident() == Some("await") { + if self.tok.escaped { + return Err(self.error_at_token(&self.tok, "keyword 'await' must not contain escaped characters")); + } + Prefix::Await + } else { + let Some(prefix) = prefix_op(&self.tok) else { break }; + prefix + }; prefixes.push((prefix, self.tok.span)); self.bump()?; } @@ -1296,6 +1419,10 @@ impl<'s> Parser<'s> { } self.ast.push_expr(Expr::Unary { op, arg: expr }, span) } + Prefix::Await => { + self.awaits = self.awaits.saturating_add(1); + self.ast.push_expr(Expr::Await(expr), span) + } }; } Ok(expr) @@ -1351,12 +1478,18 @@ impl<'s> Parser<'s> { expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span); } TokenKind::Punct(Punct::LParen) => { + let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); + let line_break = self.tok.newline_before; + let awaits = self.awaits; let args = self.parse_arguments()?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), None => self.ast.push_expr(Expr::Call { callee: expr, args }, span), }; + if async_head && self.at(Punct::Arrow) { + self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits }); + } } _ => break, } @@ -1409,9 +1542,19 @@ impl<'s> Parser<'s> { TokenKind::Keyword(Keyword::True) => Expr::Bool(true), TokenKind::Keyword(Keyword::False) => Expr::Bool(false), TokenKind::Keyword(Keyword::Function) => return self.parse_function_expression(), + TokenKind::Ident(_) if self.at_async_function() => return self.parse_function_expression(), TokenKind::Ident(name) => { let name = name.clone(); self.check_identifier(&self.tok, &name)?; + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } + if self.at_async() { + let token = self.bump()?; + let id = self.ast.push_expr(Expr::Ident(name), token.span); + self.async_ident = Some(id); + return Ok(id); + } Expr::Ident(name) } TokenKind::Number(n) => { @@ -1463,6 +1606,7 @@ impl<'s> Parser<'s> { /// function, which may also be `()` or end with `...name`; those two must come before `=>`. fn parse_paren_or_arrow_head(&mut self) -> Result { let start = self.expect(Punct::LParen)?.span; + let awaits = self.awaits; let mut items = Vec::new(); let mut head_only = self.at(Punct::RParen); while !self.at(Punct::RParen) { @@ -1493,7 +1637,11 @@ impl<'s> Parser<'s> { self.ast.push_expr(Expr::Sequence(items), span) } }; - Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start))) + let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start)); + if self.at(Punct::Arrow) { + self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits }); + } + Ok(paren) } /// A template literal from its first piece (the current token): its pieces and substitutions. @@ -1522,9 +1670,20 @@ impl<'s> Parser<'s> { } fn parse_function_expression(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; + // A function expression's name is read as its own body reads names (ECMA-262 2017 + // section 14.6): `await` is a name for an ordinary one, and not for an async one. + // Nor does the name count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = is_async; + self.ctx.async_params = false; + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; + let id = self.parse_function_rest(FunctionKind::Expression, name?, start, is_async)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1575,13 +1734,30 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } let key = PropertyKey::Ident(word.ident().unwrap_or_default().to_string()); return self.property_value(key, start); } + // `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, whose value is an + // async function that does not bind its own name. + if self.at_async() && self.peek().is_some_and(|t| !t.newline_before && property_key(&t).is_some()) { + self.bump()?; + let (key, _) = self.parse_property_key()?; + let function = self.parse_function_rest(FunctionKind::Expression, None, start, true)?; + // A method's parameters have distinct names (UniqueFormalParameters). + let mut seen = HashSet::new(); + for p in self.ast.function(function).into_iter().flat_map(|f| f.params.iter().chain(&f.rest)) { + if !seen.insert(p.name.as_str()) { + return Err(self.error_at_offset(p.span.start, format!("duplicate parameter name '{}'", p.name))); + } + } + let span = self.span_from(start); + let value = self.ast.push_expr(Expr::Function(function), span); + return Ok(Property { key, value: PropertyValue::Init(value), span }); + } let (key, _) = self.parse_property_key()?; self.property_value(key, start) } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ce8e37df32..166b32cea0 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -240,6 +240,14 @@ impl Realm { self.interp.set_es2015(es2015); } + /// Sets [`Options::es2017`] for the next runs, and for the code they evaluate; on, it also + /// sets [`Options::es2015`]. Async functions an earlier run made keep running when it is + /// turned off. Call [`Realm::add_es2015`] too in a realm made without either option, since + /// an async function needs `Promise`. + pub fn set_es2017(&mut self, es2017: bool) { + self.interp.set_es2017(es2017); + } + /// Gives a realm made without [`Options::es2015`] the built-ins that option adds (`Promise`), /// for its next runs; a realm that has them already is left as it is. It does not take them /// away again. Call it between runs. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 62aa806316..66a5b159d7 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -863,12 +863,11 @@ fn promise_builtins_run() { handle.join().unwrap(); } -/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global -/// `print` that collects its output; an `async` test passes when it prints -/// `Test262:AsyncTestComplete`. -fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { - let options = Options { es2015: true, ..Options::default() }; - let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); +/// Runs one test that may be asynchronous in a new realm made with `options` and a global `print` +/// that collects its output; an `async` test without a runtime negative passes when it prints +/// `Test262:AsyncTestComplete`, and one with a runtime negative must throw that error. +fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); let out = printed.clone(); realm.define_function("print", move |args| { @@ -882,7 +881,7 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool Ok(JsValue::Undefined) }); let result = realm.run(script); - if asynchronous && result.is_ok() { + if asynchronous && negative_type.is_none() && result.is_ok() { let printed = printed.borrow(); return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { Ok(()) @@ -951,7 +950,8 @@ fn run_promise(dir: &Path) { let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; let script = if strict { format!("\"use strict\";\n{body}") } else { body }; let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); - match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) { + let es2015 = Options { es2015: true, ..Options::default() }; + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, &es2015)) { Ok(Ok(())) => counts.passed += 1, Ok(Err(why)) => { counts.failed += 1; @@ -988,6 +988,124 @@ fn run_promise(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display()); } +/// The folders under `test/language/` that hold tests of async functions and `await`. +const ASYNC_FOLDERS: &[&str] = &["expressions/async-function", "statements/async-function", "expressions/await", "expressions/async-arrow-function"]; + +/// The feature tags an async-function test may carry and still run: [`ES2015_FEATURES`], +/// `async-functions` and `Promise`. +const ASYNC_FEATURES: &[&str] = &["async-functions", "Promise"]; + +#[test] +fn async_functions_run() { + let Some(dir) = suite_dir() else { + println!("test262 async functions: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_async_functions(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests in [`ASYNC_FOLDERS`] whose feature tags are all in [`ES2015_FEATURES`] or +/// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative +/// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests +/// included, skipping module tests and those that need a missing built-in. Prints the counts of +/// both and writes the failures with [`Options::es2017`] to `async-function-failures.txt`. +fn run_async_functions(dir: &Path) { + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let done = harness("doneprintHandle.js"); + let missing = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let es2015 = Options { es2015: true, ..Options::default() }; + let es2017 = Options { es2015: true, es2017: true, ..Options::default() }; + let editions = [es2015, es2017.clone()]; + let mut counts = [Es2015Counts::default(), Es2015Counts::default()]; + let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize); + for folder in ASYNC_FOLDERS { + let root = or_fail(inside(dir, &format!("test/language/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + for path in or_fail(test_files(&root)) { + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !ES2015_FEATURES.contains(&f.as_str()) && !ASYNC_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if has("module") || meta.negative_phase.as_deref() == Some("resolution") { + skipped += 1; + continue; + } + let asynchronous = has("async"); + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &es2017) { + skipped += 1; + continue; + } + selected += 1; + for (options, counts) in editions.iter().zip(counts.iter_mut()) { + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let outcome = if expect_error { + let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; + if parse(&text, options).is_err() { + counts.parse_passed += 1; + continue; + } + counts.parse_failed += 1; + "parsed; a SyntaxError was expected".to_string() + } else { + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, options)) { + Ok(Ok(())) => { + counts.run_passed += 1; + continue; + } + Ok(Err(why)) => { + counts.run_failed += 1; + why + } + Err(_) => { + counts.run_failed += 1; + counts.panicked += 1; + "PANIC".to_string() + } + } + }; + counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n")); + } + } + } + } + assert!(selected > 0, "no async-function tests under {}", dir.display()); + let [before, after] = counts; + let report = dir.join("async-function-failures.txt"); + if let Err(e) = std::fs::write(&report, &after.failures) { + println!("could not write {}: {e}", report.display()); + } + let line = |c: &Es2015Counts| { + format!( + "negative parse runs {} passed, {} failed; other runs {} passed, {} failed ({} panicked)", + c.parse_passed, c.parse_failed, c.run_passed, c.run_failed, c.panicked + ) + }; + println!( + "test262 async functions: {selected} tests. With Options::es2015 alone: {}. With Options::es2017: {}. Skipped {skipped} module \ + or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}", + line(&before), + line(&after), + report.display() + ); + assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); diff --git a/docs/mcp.md b/docs/mcp.md index a0108999dc..2c49b01d83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,6 +2675,18 @@ own rules: all of them, and the Script Console shows an error line for each, as in `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. +A `.js` script also reads async functions and `await` as ECMA-262 2017 section 25.5 defines them +(https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, +async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` +resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function +goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` +work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is +reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. Outside an async +function `await` is an ordinary name, and in a `.jsx` file or a `source` string `async` and `await` are ordinary +names and an async function is a syntax error. These are VectorCraft's own rules: each time a function resumes +counts as a job and takes 1 unit of fuel, and a function still waiting when no job is left stays suspended, and the +run ends. + Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ea01b22966..65cabd7f70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1084,6 +1084,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. Until the language has iterators, `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 402 of 538 runs pass, where none ran before. The 136 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and a `name` on built-in functions. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. `await` is an identifier outside async functions, and `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file; `.jsx` scripts and `source` strings do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 81a2dea0a44ef212a2885a93396bb0b1fbaccce2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:27:11 -0800 Subject: [PATCH 11/41] Saves: a refused file of a save without a path is named by its file name A save of several files without a path given (separateArtboards) refuses a file outside the write root before any file is written, and the error now names that file by its file name, as the error for the document's own file does. A path the client gives stays whole in the error. --- crates/engine/src/cmd/fileio/save.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index ba7e6682af..3ae8def31b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,9 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// Does a file the file access refuses before the first is written get named as + /// [`super::access::naming_in_error`] names it (a save without a path given)? + names_refused: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +966,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.names_refused = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1072,12 +1082,13 @@ impl SaveJob { } // Every path is checked against the file access in force before the first file is // written. A refused file is refused here, so none of the files is written, also through - // a `write` that does not check the file access itself. + // a `write` that does not check the file access itself. The error names the file as the + // job names refused files ([`SaveJob::naming_refused_files`]). #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) + && let Some((p, refused)) = files.iter().find_map(|(p, _)| super::may_write(p).err().map(|e| (p, e))) { - return Err(refused); + return Err(if self.names_refused { super::access::naming_in_error(refused, p) } else { refused }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1235,9 +1246,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refused_files() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) From a8174f2ae5cfd1dbe30f7a8867fa3922f6ac59da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:33:43 -0800 Subject: [PATCH 12/41] JavaScript: spreading a string counts the strings it makes for its characters Spreading a string makes a new one- or two-unit string for each code point, but the spread held only the bytes of each element's property, so a long string could make the host build every character string past the heap limit in one instruction. Each element now holds the bytes of its string as well, and the strings stay in the heap estimate once the array holds them. --- crates/js/src/es2015_tests.rs | 40 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 12 ++++++++--- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index d717ba2090..f7b704b210 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -513,6 +513,46 @@ fn spreading_a_rope_counts_its_flattened_length_first() { assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel"); } +#[test] +fn spreading_a_string_counts_the_string_it_makes_for_each_character() { + // Each of the 16,384 elements is a property and a one-character string of its own. The + // smaller heap has room for the properties alone but not for the strings as well, so the + // spread stops with the heap limit after about 83% of the characters, before the fuel for + // 90% of them runs out. The larger heap holds the array, its keys and the strings. + const N: usize = 16_384; + let property = crate::heap::PROP_BYTES; + let string = crate::heap::string_bytes(1); + let setup = "var s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s[0]; 0"; + let cases = [(property + string / 2, N * 9 / 10, Err(LimitKind::Heap)), (2 * (property + string) + 8, N * 2, Ok(N as f64))]; + for (per_element, fuel, expected) in cases { + let mut r = es(); + assert_eq!(r.run(setup), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let heap_bytes = r.interp().heap.bytes + N * per_element; + r.set_limits(Limits { heap_bytes, fuel: fuel as u64, ..Limits::default() }); + match (r.run("var a = [...s]; a.length"), expected) { + (Ok(JsValue::Number(n)), Ok(m)) if n == m => {} + (Err(e), Err(kind)) if e.kind == RunErrorKind::Limit(kind) => {} + (result, expected) => panic!("{per_element} bytes for each element: {result:?}, expected {expected:?}"), + } + } +} + +#[test] +fn the_strings_a_string_spread_makes_stay_counted_while_the_array_holds_them() { + const N: u32 = 4096; + let mut r = es(); + assert_eq!(r.run("var s = 'x'; for (var i = 0; i < 12; i++) s = s + s; s[0]; 0"), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let before = r.interp().heap.bytes; + assert_eq!(r.run("var a = [...s]; a.length"), Ok(JsValue::Number(f64::from(N)))); + // Takes the bytes the spread held while it ran off the estimate. + r.interp().reserve_heap(0).unwrap(); + let element = |i: u32| crate::heap::PROP_BYTES + crate::heap::string_bytes(i.to_string().len()) + crate::heap::string_bytes(1); + let least = before + (0..N).map(element).sum::(); + assert!(r.interp().heap.bytes >= least, "{} < {least}", r.interp().heap.bytes); +} + #[test] fn a_rest_parameter_checks_the_heap_before_its_array_is_made() { // The 20,000 arguments fit in the room left over, and the rest array of them does not, so diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0b75dab588..286302d021 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2404,8 +2404,9 @@ impl Interp { /// index (holes read as `undefined`), with its length read again before each one as its /// iterator reads it, a string's or a `String` object's characters by code point, and an /// object with a `length` by index. Any other value is a `TypeError`. Each element takes a - /// unit of fuel, and a concatenated string's flattened copy is counted against the heap before - /// it is made. + /// unit of fuel, a concatenated string's flattened copy is counted against the heap before + /// it is made, and so is each string a string's spread makes for its characters, while the + /// spread runs and after the array holds it. fn op_array_spread(&mut self) -> JsResult<()> { let v = self.peek(0)?; let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") }; @@ -2417,6 +2418,8 @@ impl Interp { }, _ => None, }; + // The bytes of the strings a string's spread makes, which the array keeps once it holds them. + let mut made = 0usize; let items: Vec = match boxed.as_ref().unwrap_or(&v) { Value::String(s) => { let units = crate::string_builtins::flat_charged(self, s)?; @@ -2425,9 +2428,11 @@ impl Interp { let mut i = 0; while let Some(&u) = units.get(i) { self.use_fuel()?; - held.add(self, PROP_BYTES)?; let pair = (0xD800..0xDC00).contains(&u) && units.get(i + 1).is_some_and(|n| (0xDC00..0xE000).contains(n)); let len = if pair { 2 } else { 1 }; + // Each element is a new string of its own as well as a property. + held.add(self, PROP_BYTES + string_bytes(len))?; + made = made.saturating_add(string_bytes(len)); out.push(Value::String(Str::from_units(units.get(i..i + len).unwrap_or_default().to_vec()))); i += len; } @@ -2490,6 +2495,7 @@ impl Interp { for (i, item) in (start..end).zip(items) { self.define(a, index_key(i), Prop::Data { value: item, flags: OPEN })?; } + self.heap.bytes = self.heap.bytes.saturating_add(made); self.pop().map(drop) } From b900ea2308034ec6ffe9a52613532fabd0026213 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:56:10 -0800 Subject: [PATCH 13/41] JavaScript: a block function skips its variable when a let has the name - A block function in script or eval code no longer stops the run with "redeclaration of" when a `let`, a `const` or a block function between the code and its variable environment has its name, or when the global object cannot take the variable (Annex B.3.3.2 and B.3.3.3). Its block still has the function, and a `var` of the name is still a SyntaxError. - A script stopped by the heap limit or the frame limit declares none of its `let` and `const` names, so a later script can declare them. The frame limit is checked, and the heap reserved for the names, before anything is declared. - An arrow function in an async arrow function's parameters reads `await` as an identifier, as its own body does. - With E4X, `async::name` is a qualified name. - `AsyncFunction` inherits from the built-in `Function` even after a script replaced `Function.prototype.constructor`. - The test262 reports list the older edition's panics, an async test passes only when one `print` call gives exactly the completion line, and the promise collection test checks that all 200 rejections arrive. --- crates/js/src/async_tests.rs | 20 +++++ crates/js/src/builtins.rs | 1 + crates/js/src/builtins/async_function.rs | 17 ++--- crates/js/src/bytecode.rs | 5 ++ crates/js/src/compiler.rs | 17 ++++- crates/js/src/es2015_tests.rs | 54 ++++++++++++++ crates/js/src/heap.rs | 3 +- crates/js/src/interp.rs | 95 +++++++++++++++++++++--- crates/js/src/interp/async_function.rs | 1 + crates/js/src/interp_tests.rs | 1 + crates/js/src/parser.rs | 6 +- crates/js/src/promise_tests.rs | 3 +- crates/js/tests/test262.rs | 48 +++++++----- 13 files changed, 223 insertions(+), 48 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index a473fd57da..0d78c4fd3c 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -84,6 +84,23 @@ fn async_functions_are_not_constructors_and_have_no_prototype() { assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5"); } +#[test] +fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_its_constructor() { + let mut r = Realm::new(); + assert_eq!(r.run("Function.prototype.constructor = {}; 0"), Ok(JsValue::Number(0.0))); + r.add_es2015(); + r.set_es2017(true); + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor; Object.getPrototypeOf(AF) === Function && typeof AF.call"; + assert_eq!(r.run(src), Ok(JsValue::String("function".into()))); +} + +#[test] +fn with_e4x_async_before_a_double_colon_is_a_qualified_name() { + let options = Options { es2017: true, e4x: true, ..Options::default() }; + assert!(parse("async::b", &options).is_ok()); + assert!(parse("var x = ; x.async::b", &options).is_ok()); +} + #[test] fn await_is_an_identifier_outside_async_functions() { let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\ @@ -98,6 +115,9 @@ fn await_is_an_identifier_outside_async_functions() { async function await() { return 1; }\n\ log.push(typeof g, typeof h, typeof await);"; assert_eq!(log(nested), "function function function"); + // An arrow function in an async arrow function's parameters reads `await` as its own body does. + let arrow = "var await = 7; var f = async (cb = () => await) => cb(); f().then(function (v) { log.push(v); });"; + assert_eq!(log(arrow), "7"); let mut r = realm(); syntax_error(&mut r, "async function f() { var await; }"); syntax_error(&mut r, "async function f(await) {}"); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 09cb089e5b..f1f8c0a547 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -123,6 +123,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, object_proto, "propertyIsEnumerable", property_is_enumerable, 1)?; let function = native(interp, "Function", function_ctor, 1, NativeKind::Plain, true)?; + interp.intrinsics.function_ctor = function; constructor(interp, "Function", function, function_proto)?; let call = native(interp, "call", unreachable_native, 1, NativeKind::Call, false)?; data(interp, function_proto, "call", Value::Object(call), HIDDEN)?; diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs index 43eea77b2a..4e3e65a906 100644 --- a/crates/js/src/builtins/async_function.rs +++ b/crates/js/src/builtins/async_function.rs @@ -4,7 +4,7 @@ //! reaches through it. `AsyncFunction` is not a global. use super::{data, dynamic_function, native}; -use crate::heap::{CONFIGURABLE, Class, NativeKind, ObjId, Object}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, Object}; use crate::interp::{Interp, JsResult}; use crate::value::Value; @@ -16,10 +16,11 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { interp.promises.async_function_proto = Some(proto); let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?; interp.promises.async_function_ctor = Some(ctor); - // `Function` is the constructor's prototype (section 25.5.2). - let function_ctor = constructor_of(interp, function_proto); + // The built-in `Function` is the constructor's prototype (section 25.5.2), even after a + // script has replaced `Function.prototype.constructor`. + let function_ctor = interp.intrinsics.function_ctor; if let Some(o) = interp.heap.object_mut(ctor) { - o.proto = function_ctor.or(o.proto); + o.proto = Some(function_ctor); } data(interp, ctor, "prototype", Value::Object(proto), 0)?; // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary @@ -27,14 +28,6 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) } -/// The `constructor` property `proto` has from the built-ins, when it is an object. -fn constructor_of(interp: &Interp, proto: ObjId) -> Option { - match interp.get_own_property(proto, &crate::heap::key("constructor")) { - Ok(Some(crate::heap::Prop::Data { value: Value::Object(o), .. })) => Some(o), - _ => None, - } -} - /// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { dynamic_function(interp, args, true) diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 723ad84b40..5dba6c540f 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -280,6 +280,11 @@ pub(crate) struct Code { pub(crate) vars: Vec, /// Function declarations to instantiate on entry: their names and indices in `functions`. pub(crate) fun_decls: Vec<(Key, u32)>, + /// In script and eval code, the variables of block functions (Annex B.3.3.2 and B.3.3.3) that + /// the code does not declare otherwise: each is declared, and its function assigned to it, only + /// when no `let`, `const` or block function between the code and its variable environment has + /// the name and the variable can be declared. + pub(crate) annex_vars: Vec, /// The body refers to `arguments` or calls `eval`. pub(crate) uses_arguments: bool, pub(crate) source: Rc, diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 3690ef3e28..aa0feff65f 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -106,6 +106,9 @@ struct FnCompiler<'a> { struct Hoisted { vars: Vec, fun_decls: Vec<(Key, u32)>, + /// The names of block functions (Annex B.3.3) that are neither a `var` nor a function at the + /// top of the body. + annex_vars: Vec, } fn key_of(name: &str) -> Key { @@ -244,7 +247,8 @@ impl<'a> FnCompiler<'a> { /// hoisted; one in a block is instantiated when the block is entered, and outside strict mode /// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with /// a `let` or a `const` of the body or of a block or loop around the declaration, or with a - /// function of a block around the one that holds it. + /// function of a block around the one that holds it. Such a name that the body does not also + /// declare with `var` or as a function at its top goes in [`Hoisted::annex_vars`]. fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult { let mut out = Hoisted::default(); let mut seen = HashSet::new(); @@ -259,6 +263,7 @@ impl<'a> FnCompiler<'a> { } }; let mut annex: Vec<(Key, usize, StmtId)> = Vec::new(); + let mut annex_seen = HashSet::new(); while let Some((id, nested, scope)) = work.pop() { let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") }; let inner = self.es2015; @@ -366,7 +371,9 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - add_var(&mut out, k); + if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + out.annex_vars.push(k); + } } } Ok(out) @@ -1800,6 +1807,7 @@ impl<'a> FnCompiler<'a> { params: meta.params, vars: hoisted.vars, fun_decls: hoisted.fun_decls, + annex_vars: hoisted.annex_vars, uses_arguments: self.uses_arguments, source: self.source.clone(), span: meta.span, @@ -1848,7 +1856,10 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let params: Vec = f.params.iter().map(|p| key_of(&p.name)).collect(); let rest = f.rest.as_ref().map(|r| key_of(&r.name)); let all_params: Vec = params.iter().chain(&rest).cloned().collect(); - let hoisted = c.hoist(&f.body, &all_params)?; + let mut hoisted = c.hoist(&f.body, &all_params)?; + // A function's block functions always have their variable (Annex B.3.3.1). + let annex = std::mem::take(&mut hoisted.annex_vars); + hoisted.vars.extend(annex); let top_scope = c.list_scope(&f.body, false)?; let param_init = !f.simple_params(); if param_init { diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index ec09876731..a8a77b723b 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -138,6 +138,28 @@ fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() { truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1"); } +#[test] +fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { + // A block function of a script or of eval code gets no variable when a `let`, a `const` or a + // block function out to the variable environment has its name, or when the global object + // cannot take it (Annex B.3.3.2 and B.3.3.3); its block still has it, and a `var` of the name + // is still a SyntaxError. + let mut realm = es(); + assert_eq!(realm.run("let f = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var inner; { function f() { return 2; } inner = f(); } inner + f"), Ok(JsValue::Number(3.0))); + assert!(is_thrown(&realm.run("{ function f() {} } var f;"), "SyntaxError")); + assert_eq!(realm.run("(0, eval)('{ function f() { return 4; } }'); f"), Ok(JsValue::Number(1.0))); + truth("function t() { let h = 1; { eval('{ function h() { return 2; } }'); } return h; } t() === 1"); + truth("function t() { let h = 1; eval('{ function h() {} }'); return h; } t() === 1"); + // A `catch` parameter does not stop the variable (Annex B.3.5). + truth("try { throw 1; } catch (c) { eval('{ function c() { return 5; } }'); } c() === 5"); + let mut realm = es(); + assert_eq!(realm.run("var out; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0))); + let kept = realm.run("{ function n() { return 6; } out = n(); } out + typeof n"); + assert_eq!(kept, Ok(JsValue::String("6undefined".into()))); + assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); @@ -286,6 +308,38 @@ fn a_global_var_that_cannot_be_declared_declares_nothing() { assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0))); } +#[test] +fn a_script_stopped_by_the_frame_limit_declares_no_let() { + let mut realm = Realm::with_options(es_options(), Limits { frames: 0, ..Limits::default() }); + let stopped = realm.run("let early = 1; const fixed = 2;"); + assert!(matches!(&stopped, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Frames)), "{stopped:?}"); + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0))); +} + +#[test] +fn a_script_stopped_by_the_heap_limit_declares_no_let() { + // The `let` and `const` names of a script go in before its functions are made; a heap too + // small for both stops the script before any name is declared. + let lets: String = (0..200).map(|i| format!("let a_long_lexical_name_{i} = {i}; ")).collect(); + let decls: String = (0..40).map(|i| format!("function f{i}() {{ return {i}; }} ")).collect(); + let src = format!("let early = 1; const fixed = 2; {lets}{decls}"); + let mut stopped = 0; + for spare in (40_000..200_000).step_by(97) { + let mut realm = es(); + let live = realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match realm.run(&src) { + Ok(_) => continue, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => stopped += 1, + Err(e) => panic!("{spare}: {e:?}"), + } + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)), "{spare}"); + } + assert!(stopped > 0); +} + #[test] fn eval_code_keeps_its_let_and_const_to_itself() { truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'"); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index e25bac7323..c59925c1bb 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -623,6 +623,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { + code.functions.len() + code.params.len() + code.vars.len() + + code.annex_vars.len() + 2 * code.fun_decls.len() + code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::() + code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::(); @@ -641,7 +642,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { strings.add(pattern); strings.add(flags); } - let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k)); + let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(&code.annex_vars).chain(code.fun_decls.iter().map(|(k, _)| k)); for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) { strings.add_key(k); } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index d7a0ef6481..b4fa731b76 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -92,6 +92,9 @@ impl ErrorType { pub(crate) struct Intrinsics { pub(crate) object_proto: ObjId, pub(crate) function_proto: ObjId, + /// The built-in `Function`, which a script can replace as the global or as the prototype's + /// `constructor`. + pub(crate) function_ctor: ObjId, pub(crate) array_proto: ObjId, pub(crate) string_proto: ObjId, pub(crate) number_proto: ObjId, @@ -115,6 +118,7 @@ impl Intrinsics { Self { object_proto: o, function_proto: o, + function_ctor: o, array_proto: o, string_proto: o, number_proto: o, @@ -149,6 +153,7 @@ impl Intrinsics { let mut v = vec![ self.object_proto, self.function_proto, + self.function_ctor, self.array_proto, self.string_proto, self.number_proto, @@ -187,6 +192,9 @@ pub(crate) struct Frame { /// The promise of the async function the frame runs: a return resolves it, an exception /// that leaves the frame rejects it, and the call's value is the promise. async_promise: Option, + /// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not + /// declared: [`Op::AnnexB`] leaves them alone. + annex_off: Vec, } /// Where the exception being thrown was raised: the code and the instruction. @@ -471,7 +479,13 @@ fn declaration_bytes(code: &Code) -> usize { let closure = code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f)); total.saturating_add(binding_bytes(name.len()) + closure) }); - code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) + code.vars.iter().chain(&code.annex_vars).fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) +} + +/// The bytes the `let` and `const` names at the top of a script add to the global scope. +fn global_lexical_bytes(code: &Code) -> usize { + let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets); + lets.iter().fold(0usize, |total, (name, _)| total.saturating_add(binding_bytes(name.len()))) } /// A call to a function written in JavaScript, ready to enter. @@ -2396,9 +2410,13 @@ impl Interp { Ok(()) } - /// Assigns a function declared in a block to the variable of the same name. + /// Assigns a function declared in a block to the variable of the same name, unless the + /// variable of script or eval code was not declared. fn op_annex_b(&mut self, n: u32) -> JsResult<()> { let name = self.name(n)?; + if self.frame()?.annex_off.contains(&name) { + return self.pop().map(drop); + } let v = self.peek(0)?; let var_env = self.frame()?.var_env; match self.heap.env(var_env) { @@ -2952,6 +2970,7 @@ impl Interp { completion: Value::Undefined, boundary, async_promise: None, + annex_off: Vec::new(), }); // An async function's call makes its promise first thing (section 25.5.5.2); the frame // keeps what the function holds reachable while it is made. @@ -3278,14 +3297,16 @@ impl Interp { (caller_env, caller_var_env) }; self.stack.truncate(start); - let env = self.instantiate_pending(&code, env, var_env, true)?; - self.push_code_frame(code, env, var_env, this, false) + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, true)?; + self.push_code_frame(code, env, var_env, this, false)?; + self.frame_mut()?.annex_off = annex_off; + Ok(()) } /// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the /// code counted against the heap, until its frame holds them: the scopes and functions it /// makes can collect. - fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { let mark = self.temp_envs.len(); self.temp_envs.push(env); self.temp_codes.push(code.clone()); @@ -3311,9 +3332,15 @@ impl Interp { r } - /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. + /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. The + /// frame limit and the heap, with a script's `let` and `const` names, are checked before + /// anything is declared. pub(crate) fn enter_global(&mut self, code: Rc, is_eval: bool) -> JsResult<()> { - self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let lexical = if is_eval { 0 } else { global_lexical_bytes(&code) }; + self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(lexical))?; let (scope, global) = (self.global_scope(), self.global); let (env, var_env) = if code.strict && is_eval { let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); @@ -3321,8 +3348,10 @@ impl Interp { } else { (scope, self.global_env) }; - let env = self.instantiate_pending(&code, env, var_env, is_eval)?; - self.push_code_frame(code, env, var_env, Value::Object(global), true) + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, is_eval)?; + self.push_code_frame(code, env, var_env, Value::Object(global), true)?; + self.frame_mut()?.annex_off = annex_off; + Ok(()) } /// The environment global code runs in: the one that holds the scripts' `let` and `const` @@ -3437,6 +3466,7 @@ impl Interp { completion: Value::Undefined, boundary, async_promise: None, + annex_off: Vec::new(), }); Ok(()) } @@ -3446,8 +3476,9 @@ impl Interp { /// /// Gives the environment the code runs in: `env`, or with [`Options::es2015`] eval code's own /// environment of its `let` and `const` names. A script's `let` and `const` names go in the - /// global scope ([`Self::declare_global_lexical`]). - fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + /// global scope ([`Self::declare_global_lexical`]). Also gives the names of + /// [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not declare. + fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { let configurable = if is_eval { CONFIGURABLE } else { 0 }; if is_eval && !code.strict && self.options.es2015 { self.check_eval_vars(code, env, var_env)?; @@ -3492,7 +3523,47 @@ impl Interp { self.global_vars.insert(v.clone()); } } - Ok(lex) + let mut annex_off = Vec::new(); + for v in &code.annex_vars { + self.use_fuel()?; + if !self.annex_var_declarable(v, env, var_env)? { + annex_off.push(v.clone()); + continue; + } + self.declare(var_env, v, None, configurable)?; + if on_global { + self.global_vars.insert(v.clone()); + } + } + Ok((lex, annex_off)) + } + + /// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and + /// B.3.3.3, ): no + /// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch` + /// parameter does not count, and on the global object the name is its own property or the + /// object is extensible. Each environment passed takes a unit of fuel. + fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult { + let mut cur = Some(env).filter(|&e| e != var_env); + while let Some(e) = cur { + self.use_fuel()?; + cur = match self.heap.env(e) { + Some(Env::Decl { bindings, outer }) => { + if bindings.get(name).is_some_and(|b| b.lexical) { + return Ok(false); + } + *outer + } + Some(Env::Obj { outer, .. }) => *outer, + None => return internal("environment out of range"), + } + .filter(|&o| o != var_env); + } + if var_env != self.global_env { + return Ok(true); + } + let global = self.global; + Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible) } /// A `var` or function that eval code outside strict mode code declares must not take the name diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs index 7121215b9d..9bb7c26cb8 100644 --- a/crates/js/src/interp/async_function.rs +++ b/crates/js/src/interp/async_function.rs @@ -147,6 +147,7 @@ impl Interp { completion: a.completion, boundary: true, async_promise: Some(a.promise), + annex_off: Vec::new(), }); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 4a281a7b2f..346c32983a 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -972,6 +972,7 @@ fn code(ops: Vec) -> Code { params: Vec::new(), vars: Vec::new(), fun_decls: Vec::new(), + annex_vars: Vec::new(), uses_arguments: false, source, span: (0, 0), diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 9478074e73..8a7cef804f 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -1130,6 +1130,8 @@ impl<'s> Parser<'s> { let outer_strict = self.ctx.strict; let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); + // An `await` in the body does not count for an async arrow function's head around it. + let awaits = self.awaits; self.push_scope(true, names); let block = self.at(Punct::LBrace); let body = if block { @@ -1138,6 +1140,7 @@ impl<'s> Parser<'s> { self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))]) }; self.pop_scope(); + self.awaits = awaits; let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict); self.ctx = outer; self.leave(); @@ -1553,7 +1556,8 @@ impl<'s> Parser<'s> { if name == "await" { self.awaits = self.awaits.saturating_add(1); } - if self.at_async() { + // With E4X, `async::name` is a qualified name. + if self.at_async() && !(self.e4x && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon))) { let token = self.bump()?; let id = self.ast.push_expr(Expr::Ident(name), token.span); self.async_ident = Some(id); diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 8e03f2a136..fc6d927c70 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -78,7 +78,7 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() { #[test] fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { - let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\ + let src = "var bad = 0, seen = 0; function check(e) { seen++; if (!(e instanceof TypeError)) bad++; }\n\ for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }"; let mut finished = 0; for spare in (40_000..240_000).step_by(641) { @@ -92,6 +92,7 @@ fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { } r.set_limits(Limits::default()); assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + assert_eq!(r.run("seen"), Ok(JsValue::Number(200.0)), "{spare}"); } assert!(finished > 0); } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 0fe3badb67..8cd87a33bb 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -30,7 +30,8 @@ //! //! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`, //! arrow functions, templates, default and rest parameters) without and with that option, and -//! prints both counts; its failures with the option go to `es2015-failures.txt`. +//! prints both counts; its failures with the option, and the runs without it that panicked, go to +//! `es2015-failures.txt`. //! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset @@ -42,8 +43,8 @@ //! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`: //! those whose feature tags name only `Promise`, `Promise.allSettled` and //! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests -//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its -//! failures go to `promise-failures.txt`. +//! run with the suite's `doneprintHandle.js` and pass when they print the completion line and no +//! line that starts with the failure prefix. Its failures go to `promise-failures.txt`. //! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over @@ -695,13 +696,25 @@ struct Es2015Counts { failures: String, } +impl Es2015Counts { + /// The failures of the run with the option, then each run without it that panicked, marked + /// with `without`. + fn report(after: &Es2015Counts, before: &Es2015Counts, without: &str) -> String { + let mut report = after.failures.clone(); + for line in before.failures.lines().filter(|l| l.ends_with(": PANIC")) { + report.push_str(&format!("{line} ({without})\n")); + } + report + } +} + /// Runs the ES2015 subset: the tests under `test/language/` in [`ES2015_FOLDERS`] whose feature /// tags are all in [`ES2015_FEATURES`], and the tests elsewhere under `test/language/` with feature /// tags that are all in it. Negative parse tests must give a `SyntaxError`; the other tests run in a /// new realm after the harness, as [`run_tests`] runs them, skipping module and asynchronous tests /// and those that need a missing built-in. Each test is read twice, without and with -/// [`Options::es2015`], and the counts of both are printed; the failures with it go to -/// `es2015-failures.txt`. +/// [`Options::es2015`], and the counts of both are printed; the failures with it, and the runs +/// without it that panicked, go to `es2015-failures.txt`. fn run_es2015(dir: &Path) { let language = or_fail(inside(dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); @@ -779,7 +792,7 @@ fn run_es2015(dir: &Path) { assert!(selected > 0, "no ES2015 tests under {}", language.display()); let [before, after] = counts; let report = dir.join("es2015-failures.txt"); - if let Err(e) = std::fs::write(&report, &after.failures) { + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "without Options::es2015")) { println!("could not write {}: {e}", report.display()); } let line = |c: &Es2015Counts| { @@ -869,11 +882,12 @@ fn promise_builtins_run() { } /// Runs one test that may be asynchronous in a new realm made with `options` and a global `print` -/// that collects its output; an `async` test without a runtime negative passes when it prints -/// `Test262:AsyncTestComplete`, and one with a runtime negative must throw that error. +/// that collects its output; an `async` test without a runtime negative passes when one `print` +/// call gives exactly `Test262:AsyncTestComplete` and none gives a value that starts with +/// `Test262:AsyncTestFailure:`, and one with a runtime negative must throw that error. fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> { let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); - let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let out = printed.clone(); realm.define_function("print", move |args| { let line = match args.first() { @@ -881,18 +895,15 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool Some(other) => format!("{other:?}"), None => String::new(), }; - out.borrow_mut().push_str(&line); - out.borrow_mut().push('\n'); + out.borrow_mut().push(line); Ok(JsValue::Undefined) }); let result = realm.run(script); if asynchronous && result.is_ok() && negative_type.is_none() { let printed = printed.borrow(); - return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { - Ok(()) - } else { - Err(format!("printed {:?}", printed.trim())) - }; + let complete = printed.iter().any(|l| l == "Test262:AsyncTestComplete"); + let failed = printed.iter().any(|l| l.starts_with("Test262:AsyncTestFailure:")); + return if complete && !failed { Ok(()) } else { Err(format!("printed {:?}", printed.join("\n"))) }; } match (result, negative_type) { (Ok(_), None) => Ok(()), @@ -1014,7 +1025,8 @@ fn async_functions_run() { /// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative /// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests /// included, skipping module tests and those that need a missing built-in. Prints the counts of -/// both and writes the failures with [`Options::es2017`] to `async-function-failures.txt`. +/// both and writes the failures with [`Options::es2017`], and the runs with [`Options::es2015`] +/// alone that panicked, to `async-function-failures.txt`. fn run_async_functions(dir: &Path) { let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); @@ -1092,7 +1104,7 @@ fn run_async_functions(dir: &Path) { assert!(selected > 0, "no async-function tests under {}", dir.display()); let [before, after] = counts; let report = dir.join("async-function-failures.txt"); - if let Err(e) = std::fs::write(&report, &after.failures) { + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "with Options::es2015 alone")) { println!("could not write {}: {e}", report.display()); } let line = |c: &Es2015Counts| { From 1f1b967a7c3bb04080f6eea9f6fe2dd86515186b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:01:22 -0800 Subject: [PATCH 14/41] JavaScript: Promise.all reads a String object by its characters `Promise.all`, `Promise.allSettled` and `Promise.race` read a `String` object as the string it holds, one input for each character, as they read a string. A character outside the Basic Multilingual Plane was two inputs before. --- crates/js/src/builtins/promise.rs | 9 ++++++++- crates/js/src/promise_tests.rs | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 03ece744a5..901125f565 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -1141,7 +1141,7 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe /// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to /// its length at each step, as an array iterator reads it, and another object up to the `length` -/// it had at the start. +/// it had at the start. A string, and a `String` object, gives its characters. enum Inputs { Indexed { object: ObjId, length: f64 }, CodePoints(Rc<[u16]>), @@ -1149,6 +1149,13 @@ enum Inputs { impl Inputs { fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { + // A `String` object iterates as the string it holds does (ECMA-262 2015 section 21.1.3.27). + if let Value::Object(o) = input + && let Some(Class::String(s)) = interp.heap.object(*o).map(|obj| &obj.class) + { + let s = s.clone(); + return Ok(Inputs::CodePoints(flat_charged(interp, &s)?)); + } match input { Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index fc6d927c70..6f3fb5008d 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -105,6 +105,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\ Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\ Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\ + Promise.all(new String('a\\uD83D\\uDE00')).then(function (v) { log.push('boxed ' + v.length + ' ' + v[1].length); });\n\ Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\ Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\ Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });"; @@ -117,6 +118,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { "rejected:r fulfilled:4", "race fast", "chars 2", + "boxed 2 2", "not a list true", "no length true", "bad length true", From c606701aef2a90d41fead42ad84452460e50321c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:04:25 -0800 Subject: [PATCH 15/41] JavaScript: a comma after a rest parameter is a SyntaxError in async arrows - `async (...xs,) => xs` is a SyntaxError, as `(...xs,) => xs` is. `async (x,) => x` still parses. - An arrow function's parameters may end with a comma: `(a, b,) => a + b` parses, and `(a,)` without `=>` is still a SyntaxError. - A `var` that an inherited property of the global object declared, without ECMAScript 2015 scoping, no longer stops a later `let` of its name once the realm turns the option on. - A tagged template's object reserves the heap for its index names and its `raw` property before it is made. - The test262 runner skips a test whose template literal runs a missing built-in as code, as it skips one whose string does. --- crates/js/src/async_tests.rs | 12 ++++++++++ crates/js/src/es2015_tests.rs | 42 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 17 +++++++++++--- crates/js/src/parser.rs | 37 ++++++++++++++++++++++++------ crates/js/tests/test262.rs | 11 ++++++++- 5 files changed, 108 insertions(+), 11 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 0d78c4fd3c..e16f8e2a35 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -69,6 +69,18 @@ fn arrows_expressions_and_methods_can_be_async() { assert_eq!(log(src), "4,3,function,kv"); } +#[test] +fn a_comma_may_follow_an_arrow_functions_last_parameter_but_not_a_rest_parameter() { + let src = "var f = async (x,) => x; var g = async (x, ...xs) => xs.length; var h = (a, b,) => a + b;\n\ + var async = function () { return arguments.length; }; log.push(async(...[1, 2],));\n\ + Promise.all([f(1), g(1, 2, 3), h(1, 2), h.length]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "2 1,2,3,2"); + let mut r = realm(); + for src in ["async (...xs,) => xs", "async (a, ...xs,) => xs", "(...xs,) => xs", "(a, ...xs,) => xs", "(a,);", "(a, b,);"] { + syntax_error(&mut r, src); + } +} + #[test] fn async_functions_are_not_constructors_and_have_no_prototype() { let src = "async function f() {}\n\ diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index f6a337d860..92516cc4b8 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -262,6 +262,17 @@ fn a_global_var_makes_its_own_property_over_an_inherited_one() { assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true))); } +#[test] +fn a_var_an_inherited_property_declared_does_not_stop_a_later_let() { + // Without the option, `var x` uses the inherited `x` and makes no own property, so a later + // run with the option may declare `x` with `let`. + let mut realm = Realm::new(); + assert_eq!(realm.run("Object.prototype.x = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var x; delete this.x"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("let x = 2; x"), Ok(JsValue::Number(2.0))); +} + #[test] fn a_global_function_that_cannot_be_declared_declares_nothing() { let mut realm = es(); @@ -752,6 +763,37 @@ fn spread_stops_at_the_heap_limit_before_the_next_step_runs() { } } +#[test] +fn a_template_object_stays_within_the_heap_limit() { + // The template object's two arrays, the index name of each string and the `raw` property are + // reserved before they are made, so the heap stays within each limit tried. + let setup = "function t(s) { return s.length; } 0"; + let run = format!("t`{}`", (0..10).map(|i| format!("p{i}${{{i}}}")).collect::()); + let mut measure = Realm::with_options(es_options(), Limits::default()); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + measure.interp().collect_garbage(); + let base = measure.interp().heap.bytes; + assert_eq!(measure.run(&run), Ok(JsValue::Number(11.0))); + let need = measure.interp().settled_heap_bytes() - base; + let mut stopped = 0; + for heap_bytes in (base..=base + need).step_by(4) { + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + if realm.run(setup).is_err() { + continue; + } + realm.interp().collect_garbage(); + let r = realm.run(&run); + stopped += usize::from(r.is_err()); + assert!( + matches!(&r, Ok(JsValue::Number(_))) || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), + "{heap_bytes}: {r:?}" + ); + let bytes = realm.interp().settled_heap_bytes(); + assert!(bytes <= heap_bytes, "{bytes} > {heap_bytes}"); + } + assert!(stopped > 0, "no limit stopped the run"); +} + #[test] fn spreading_other_values_is_a_type_error() { throws("[...1];", "TypeError"); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 7224b0c122..f6e21e0224 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2670,8 +2670,16 @@ impl Interp { return self.push(Value::Object(id)); } let Some(t) = code.templates.get(i as usize) else { return internal("template out of range") }; - let strings = t.cooked.len().saturating_add(t.raw.len()); - self.reserve_heap(OBJECT_BYTES.saturating_mul(2).saturating_add(strings.saturating_mul(PROP_BYTES)))?; + // Two arrays, a property and an index name for each string, and the `raw` property. + let names = |n: usize| index_keys_bytes(n).saturating_sub(n.saturating_mul(KEY_ENTRY_BYTES)); + let props = t.cooked.len().saturating_add(t.raw.len()).saturating_add(1); + let bytes = OBJECT_BYTES + .saturating_mul(2) + .saturating_add(props.saturating_mul(PROP_BYTES)) + .saturating_add(names(t.cooked.len())) + .saturating_add(names(t.raw.len())) + .saturating_add(string_bytes(3)); + self.reserve_heap(bytes)?; let raw = self.frozen_array(&t.raw)?; // The raw array stays reachable while the template object is made. self.push(Value::Object(raw))?; @@ -3620,7 +3628,10 @@ impl Interp { for v in &code.vars { self.use_fuel()?; self.declare(var_env, v, None, configurable)?; - if on_global { + // Without ECMA-262 2015's scoping, a property the global object inherits declares the + // variable and no own property is made. Only a name with an own property is kept; + // `delete` removes the name with that property. + if on_global && self.get_own_property(self.global, v)?.is_some() { self.global_vars.insert(v.clone()); } } diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index d4ed2e8c4a..4430636d2d 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -51,6 +51,8 @@ struct Head { line_break: bool, /// The parentheses hold an `await` expression or the identifier `await`. awaits: bool, + /// A comma follows the last item in the parentheses. + trailing_comma: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -1313,6 +1315,13 @@ impl<'s> Parser<'s> { if head.is_some_and(|h| h.line_break) { return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function")); } + // No comma may follow a rest parameter (ECMA-262 2017 section 14.1). + if let Some(&last) = args.last() + && head.is_some_and(|h| h.trailing_comma) + && matches!(self.ast.expr(last), Some(Expr::Spread(_))) + { + return Err(self.error_at_offset(self.ast.expr_span(last).start, "a rest parameter must be the last parameter")); + } (self.arrow_items(args.clone())?, true) } _ => return Err(self.unexpected()), @@ -1517,14 +1526,14 @@ impl<'s> Parser<'s> { let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); let line_break = self.tok.newline_before; let awaits = self.awaits; - let args = self.parse_arguments()?; + let (args, trailing_comma) = self.arguments()?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), None => self.ast.push_expr(Expr::Call { callee: expr, args }, span), }; if async_head && self.at(Punct::Arrow) { - self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits }); + self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma }); } } TokenKind::Punct(Punct::QuestionDot) => { @@ -1612,19 +1621,29 @@ impl<'s> Parser<'s> { } fn parse_arguments(&mut self) -> Result> { + Ok(self.arguments()?.0) + } + + /// An argument list, and whether a comma follows its last argument. + fn arguments(&mut self) -> Result<(Vec, bool)> { self.expect(Punct::LParen)?; let mut args = Vec::new(); + let mut trailing_comma = false; if !self.at(Punct::RParen) { loop { args.push(self.parse_element()?); // A comma may follow the last argument (ECMAScript 2017, section 12.3). - if !self.eat(Punct::Comma)? || self.at(Punct::RParen) { + if !self.eat(Punct::Comma)? { + break; + } + if self.at(Punct::RParen) { + trailing_comma = true; break; } } } self.expect(Punct::RParen)?; - Ok(args) + Ok((args, trailing_comma)) } fn parse_primary(&mut self) -> Result { @@ -1704,7 +1723,8 @@ impl<'s> Parser<'s> { } /// `( … )` with [`crate::Options::es2015`]: a parenthesized expression, or the head of an arrow - /// function, which may also be `()` or end with `...name`; those two must come before `=>`. + /// function, which may also be `()`, end with `...name` or end with a comma; those three must + /// come before `=>`. fn parse_paren_or_arrow_head(&mut self) -> Result { let start = self.expect(Punct::LParen)?.span; let awaits = self.awaits; @@ -1723,8 +1743,11 @@ impl<'s> Parser<'s> { if !self.eat(Punct::Comma)? { break; } + // A comma may follow the last parameter (ECMA-262 2017 section 14.2), but not the + // last item of a parenthesized expression. if self.at(Punct::RParen) { - return Err(self.unexpected()); + head_only = true; + break; } } self.expect(Punct::RParen)?; @@ -1740,7 +1763,7 @@ impl<'s> Parser<'s> { }; let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start)); if self.at(Punct::Arrow) { - self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits }); + self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits, trailing_comma: false }); } Ok(paren) } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fcfeb7bf25..fc90beb905 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -436,7 +436,7 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens)); lists.iter().flatten().any(|t| match &t.kind { TokenKind::Ident(name) => missing.contains(name.as_str()), - TokenKind::String(units) => { + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => { let text = String::from_utf16_lossy(units); missing.contains(text.as_str()) || (strings_are_code && text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word))) @@ -1155,6 +1155,15 @@ fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() { assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern)); } +#[test] +fn a_missing_name_in_a_template_that_can_run_as_code_skips() { + let missing: HashSet<&str> = ["Map"].into_iter().collect(); + let modern = Options { es2015: true, ..Options::default() }; + assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern)); + assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern)); + assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern)); +} + #[test] fn a_missing_name_in_code_skips() { assert!(skips(&["var m = new Map();"])); From f6a6cf35183118924bb9c391c522351571b3c479 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:25:22 -0800 Subject: [PATCH 16/41] Tests: a template key naming eval runs strings as code in the test262 runner runs_strings_as_code matched a string token naming eval, Function or constructor, but not a template, so this[`eval`](`new Map()`) did not skip when Map is missing. Templates now match the same names, as needs_missing_builtin_in already reads both forms. --- crates/js/tests/test262.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fc90beb905..77de4c13f6 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -446,12 +446,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: } /// The tokens can run a string as code: they name `eval`, `Function` or a `constructor` property, -/// as an identifier or as a string key (`this["eval"]`), called directly or through an alias. +/// as an identifier or as a string or template key (`this["eval"]`), called directly or through an alias. /// `Function.prototype` alone does not count. fn runs_strings_as_code(tokens: &[Token]) -> bool { const RUNNERS: [&str; 3] = ["eval", "Function", "constructor"]; tokens.iter().enumerate().any(|(i, t)| match &t.kind { - TokenKind::String(units) => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), TokenKind::Ident(name) if name == "eval" || name == "constructor" => true, TokenKind::Ident(name) if name == "Function" => { let prototype = tokens.get(i + 1).is_some_and(|d| d.is_punct(Punct::Dot)) @@ -1161,6 +1161,9 @@ fn a_missing_name_in_a_template_that_can_run_as_code_skips() { let modern = Options { es2015: true, ..Options::default() }; assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern)); assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern)); + // A template key names the runner, as a string key does. + assert!(needs_missing_builtin_in(&["this[`eval`](`new Map()`);"], &missing, &modern)); + assert!(needs_missing_builtin_in(&[r#"var F = this[`Function`]; F("return new Map()")();"#], &missing, &modern)); assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern)); } From d6bb6429f4abf4a48df27d505e33741d05846db2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:11:19 -0800 Subject: [PATCH 17/41] Scripts: controlBounds, placedItems and rasterItems follow main's empty-object and topmost-first rules On main, a page item's bounds are an Option, and an object with nothing in it reads its bounds as zeros. controlBounds now does the same: it joins the visible bounds with the handle bounds when either exists, and reads zeros when neither does. Main lists pageItems topmost first. placedItems and rasterItems take their order from pageItems, so they list the images topmost first too; docs/mcp.md says so, and the tests that read the newest object or the bottom one by index read it at its new position. The plug-in test main added that builds a ScriptGate by hand now sets the held field this branch added to it. --- crates/engine/src/script/dom.rs | 8 ++++++-- crates/engine/src/script/dom/images.rs | 3 ++- crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_dom.rs | 2 +- crates/engine/src/tests/script_dom_images.rs | 9 +++++---- docs/mcp.md | 2 +- 6 files changed, 16 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9fae8ab13e..1a0ecbc44b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1811,12 +1811,16 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } -/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths. +/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an +/// object with nothing in it. fn item_control(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, true)?; let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds)); - Ok(f.bounds(h.dom.coords.get(), handles.map_or(r, |b| r.union(b)))) + match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) { + Some(r) => Ok(f.bounds(h.dom.coords.get(), r)), + None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } } /// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 921cbef27f..24c40006e2 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -127,7 +127,8 @@ fn pending_handle(d: &Data) -> Option<[f64; 3]> { } } -/// The ids of a document's linked (`placed`) or embedded images in paint order. +/// The ids of a document's linked (`placed`) or embedded images, topmost first as [`page_items`] +/// lists them. fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; if let Some(l) = &*h.dom.images.lists.borrow() diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1ae16ec6a8..c6da92ac55 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 91598e766a..6eca338c60 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -140,7 +140,7 @@ fn page_item_control_bounds_take_in_the_handles() { let (mut s, _, _) = doc(); let anchors = json!([{"x": 0, "y": 100, "out": [0, 0]}, {"x": 100, "y": 100, "in": [100, 0]}]); s.execute("path.create", &json!({"anchors": anchors})).unwrap(); - let out = log(&mut s, "var p = app.activeDocument.pageItems, i = p[p.length - 1]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); let b = |v: &Value| -> Vec { v.as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect() }; let (visible, control) = (b(&out[0]), b(&out[1])); assert!(visible[1] < 290.0, "the curve stays well under its handles: {visible:?}"); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 8101e17ab0..639020ab18 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -326,9 +326,10 @@ fn raster_metadata_uses_encoded_header_not_rgb_fallback() { &base, "var r = app.activeDocument.rasterItems, t = [];\ for (var i = 0; i < r.length; i++) t.push([r[i].imageColorSpace, r[i].channels, r[i].bitsPerChannel, r[i].transparent, r[i].colorizedGrayscale]);\ - vc.log(t); vc.log(r[0].boundingBox); vc.log(r[1].imageColorSpace === ImageColorSpace.RGB); var m = r[1].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);", + vc.log(t); vc.log(r[1].boundingBox); vc.log(r[0].imageColorSpace === ImageColorSpace.RGB); var m = r[0].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);", ); - assert_eq!(out[0], json!([["ImageColorSpace.Grayscale", 1, 8, false, false], ["ImageColorSpace.RGB", 4, 8, true, false]])); + // The collection lists the images topmost first, as `pageItems` does: the color image placed last comes first. + assert_eq!(out[0], json!([["ImageColorSpace.RGB", 4, 8, true, false], ["ImageColorSpace.Grayscale", 1, 8, false, false]])); assert_eq!(out[1], json!([0, 4, 6, 0])); assert_eq!(out[2], json!(true)); let m = out[3].as_array().unwrap(); @@ -577,9 +578,9 @@ fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { "var d = app.activeDocument, p = d.placedItems[0], x = null, m = '';\ for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') x = d.pageItems[i]; }\ p.embed(); try { x.move(p, ElementPlacement.PLACEAFTER); } catch (e) { m = e.message; } vc.log(m);\ - x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log(d.pageItems[0].typename);", + x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log([d.pageItems[0].typename, d.pageItems[1].typename]);", ); - assert_eq!(out, vec![json!("Stale page item"), json!("PathItem")]); + assert_eq!(out, vec![json!("Stale page item"), json!(["RasterItem", "PathItem"])]); assert!(s.active().unwrap().doc.node(NodeId(rect)).is_some()); let _ = std::fs::remove_dir_all(base); } diff --git a/docs/mcp.md b/docs/mcp.md index 59bc92d6dd..1b22e2896a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2938,7 +2938,7 @@ other files through `$`: keeps the preset's value. A bad value throws an error before anything is written. - `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones, - in paint order, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` + topmost first as `pageItems` lists them, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` gives a `PlacedItem` with no file; assigning a `File` to its `file` runs `file.place` with `link: true`, and every other member of it throws `PlacedItem.file is required` until then. A `PlacedItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/) has `file`, `relink(file)` (`links.relink`), `embed()` From 19f1cf0aa0ad5244172d49221b4ad2c7be692d86 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:01:51 -0800 Subject: [PATCH 18/41] Scripts: a File keeps its path in FsEntry under main's file_path main reads a script's File for host class members through file_classes::file_path and defines FILE_REF_KEY and file_ref_path in host_classes. file_path now reads the path from the object's FsEntry slot, so an object made with Object.create(File.prototype) still is not a File, and the branch's own copies of FILE_REF_KEY, file_ref_path and file_ref_of are removed. file_ref uses main's key. The host class tests set the new HostClass::info field. --- crates/js/src/file_classes.rs | 47 +++++++---------------------------- crates/js/src/host_tests.rs | 3 ++- crates/js/src/lib.rs | 2 +- 3 files changed, 12 insertions(+), 40 deletions(-) diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f8100ce1b3..0488bb4596 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -49,37 +49,6 @@ impl Classes { } } -/// The one key of the [`crate::Data`] object that stands for a `File` given to a member of a host -/// class ([`crate::HostClass`]), with the file's path in the host's platform form as its value. A -/// plain object a script made that carries the key is refused. -pub const FILE_REF_KEY: &str = "\u{0}fileRef"; - -/// The path of the `File` that `d` stands for ([`FILE_REF_KEY`]). -pub fn file_ref_path(d: &crate::Data) -> Option<&str> { - let crate::Data::Object(items) = d else { return None }; - match items.as_slice() { - [(k, crate::Data::String(path))] if k == FILE_REF_KEY => Some(path), - _ => None, - } -} - -impl Interp { - /// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is - /// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads - /// it; `None` for any other object, one made with `Object.create(File.prototype)` included. - pub(crate) fn file_ref_of(&self, id: ObjId) -> JsResult> { - let Some(c) = &self.files else { return Ok(None) }; - let o = self.object(id)?; - if o.proto != Some(c.file_proto) { - return Ok(None); - } - Ok(match &o.class { - Class::FsEntry(s) => Some(crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(s.to_rust_string()))])), - _ => None, - }) - } -} - /// The path of `o` when the `File` or `Folder` class made it. fn own_path(i: &Interp, o: ObjId) -> JsResult> { Ok(match &i.object(o)?.class { @@ -144,17 +113,18 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } -/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose -/// path is in its own slot. `None` for anything else, a `Folder` included. +/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and that the +/// `File` class made, with its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` +/// and an object made with `Object.create(File.prototype)` included. pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { let Some(c) = &i.files else { return Ok(None) }; if i.object(id)?.proto != Some(c.file_proto) { return Ok(None); } - Ok(match slot(i, id, PATH)? { + Ok(own_path(i, id)?.and_then(|p| match p { Value::String(s) => Some(s.to_rust_string()), _ => None, - }) + })) } fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { @@ -1201,10 +1171,11 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { Ok(()) } -/// The [`crate::Data`] that stands for a `File` of `path` ([`FILE_REF_KEY`]), in the platform's -/// form. A member of a host class ([`crate::HostClass`]) gives one to hand the script a new `File`. +/// The [`crate::Data`] that stands for a `File` of `path` ([`crate::FILE_REF_KEY`]), in the +/// platform's form. A member of a host class ([`crate::HostClass`]) gives one to hand the script a +/// new `File`. pub fn file_ref(path: &str) -> crate::Data { - crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) + crate::Data::Object(vec![(crate::FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) } impl Interp { diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 473a073919..a5144faa71 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -915,6 +915,7 @@ fn a_read_of_a_class_on_another_branch_gives_a_new_object() { name: name.into(), parent: parent.map(Into::into), members: Vec::new(), + info: Vec::new(), index: None, construct: None, }; @@ -941,7 +942,7 @@ fn the_path_of_a_file_a_host_class_gives_is_charged_to_the_heap() { r.define_file_classes(vec![("current".into(), HostItem::Function(current))]).unwrap(); let file: HostFunction = Rc::new(move |_| Ok(file_ref(&"p".repeat(len)))); let members = vec![("file".to_string(), HostMember::Method(file))]; - let maker = HostClass { name: "Maker".into(), parent: None, members, index: None, construct: None }; + let maker = HostClass { name: "Maker".into(), parent: None, members, info: Vec::new(), index: None, construct: None }; r.define_host_classes(vec![maker], vec![("maker".into(), host_ref("Maker", &[]))]).unwrap(); assert_eq!(r.run("var f = maker.file(); f instanceof File"), Ok(JsValue::Bool(true))); r.interp().heap.bytes diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 4b2cd766f7..f833dc9db2 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -168,7 +168,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use file_classes::{FILE_REF_KEY, file_ref, file_ref_path}; +pub use file_classes::file_ref; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; From e59994ead4326f2ccd3b67220000d7e2ebb50ba4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:42:47 -0800 Subject: [PATCH 19/41] Scripts: placed and raster members use main's described member lists; a placedItems.add() result goes stale after File > Revert The images, tracing and save/open members now carry the type and argument descriptions that main's Described lists expect, and PlacedItem.contentVariable comes from the variables members. A placedItems.add() handle now records the document's revert count, so reading or assigning its file after File > Revert throws Stale page item and places nothing, as other page items do. --- crates/engine/src/script/dom.rs | 14 +-- crates/engine/src/script/dom/images.rs | 102 +++++++++--------- crates/engine/src/script/dom/save_open.rs | 22 ++-- crates/engine/src/script/dom/tracing.rs | 90 ++++++++-------- crates/engine/src/tests/script_dom_images.rs | 18 ++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- docs/mcp.md | 4 +- 7 files changed, 140 insertions(+), 112 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 0ba342a1e7..aebf848b3c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -575,12 +575,9 @@ fn item_of(h: &Host, d: &Data) -> std::result::Result { }; let (doc, id) = match handle.as_slice() { [_, _, _, _, _] => node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?, - &[run, uid, _, _, reverts, slot] => { - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - if h.session.borrow().documents().get(doc.index).map(|st| st.reverts) != whole(reverts) { - return Err(HostError::Error(STALE_ITEM.into())); - } - (doc, images::pending_id(h, run, uid, slot)?) + &[run, uid, _, _, _, slot] => { + let id = images::pending_id(h, run, uid, slot)?; + (find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?, id) } _ => return Err(HostError::Type("this is not a page item".into())), }; @@ -2972,9 +2969,8 @@ fn classes(link: &Link) -> Vec { ]); document.extend(defaults::document_members(l)); document.extend(text::styles::doc_members(l)); - document.extend( - ["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "close"].into_iter().map(|m| later(l, "Document", m)), - ); + document + .extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "close"].into_iter().map(|m| later(l, "Document", m))); document.extend(save_open::document_members(l)); document.extend(images::document_members(l)); document.extend(variables::document_members(l)); diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 24c40006e2..7e744be0b0 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -37,12 +37,12 @@ use std::sync::Arc; use serde_json::json; use vectorcraft_geom::{Affine, Point}; -use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; +use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, file_ref, file_ref_path, host_ref, host_ref_parts}; use super::{ - Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value, doc_of, - doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, - typename_of, whole, with_doc, + Answer, Coords, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value, + doc_of, doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, + returns, text, typed, typename_of, variables, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -86,22 +86,23 @@ pub(super) struct State { lists: RefCell>, } -/// A `PlacedItems.add()` result: its document, and its image once `file` placed one. +/// A `PlacedItems.add()` result: its document, how many times that document had been reverted then, +/// and its image once `file` placed one. struct Pending { uid: u64, + reverts: u64, bound: Option, } -/// The slot of a `PlacedItems.add()` result in this run, from its handle. +/// The slot of a `PlacedItems.add()` result in this run, from its handle. A result whose document +/// was closed or reverted since is stale. fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result { let stale = || HostError::Error(STALE_ITEM.into()); - if whole(run) != Some(h.run) { - return Err(stale()); - } + let doc = find_doc(h, run, uid).ok_or_else(stale)?; + let reverts = h.session.borrow().documents().get(doc.index).map(|st| st.reverts); let k = whole(slot).and_then(|k| usize::try_from(k).ok()).ok_or_else(stale)?; - let uid = whole(uid).ok_or_else(stale)?; match h.dom.images.pending.borrow().get(k) { - Some(p) if p.uid == uid => Ok(k), + Some(p) if p.uid == doc.uid && Some(p.reverts) == reverts => Ok(k), _ => Err(stale()), } } @@ -115,12 +116,12 @@ pub(super) fn pending_id(h: &Host, run: f64, uid: f64, slot: f64) -> Result Option<[f64; 3]> { match host_ref_parts(d) { Some(("PlacedItem", handle)) => match handle.as_slice() { - [run, uid, _, _, slot] => Some([*run, *uid, *slot]), + [run, uid, _, _, _, slot] => Some([*run, *uid, *slot]), _ => None, }, _ => None, @@ -241,12 +242,13 @@ fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer { /// `PlacedItems.add()`: a placed item with no file yet, which assigning `file` places. fn placed_add(h: &Host, a: &[Data]) -> Answer { let doc = list_doc(h, a, true)?; + let reverts = h.session.borrow().documents().get(doc.index).map_or(0, |st| st.reverts); let mut pending = h.dom.images.pending.borrow_mut(); if pending.len() >= MAX_PENDING { return Err(HostError::Range(format!("a run makes at most {MAX_PENDING} placed items with PlacedItems.add"))); } - pending.push(Pending { uid: doc.uid, bound: None }); - Ok(host_ref("PlacedItem", &[float(h.run), float(doc.uid), 0.0, 0.0, float(pending.len() as u64 - 1)])) + pending.push(Pending { uid: doc.uid, reverts, bound: None }); + Ok(host_ref("PlacedItem", &[float(h.run), float(doc.uid), 0.0, 0.0, float(reverts), float(pending.len() as u64 - 1)])) } macro_rules! both { @@ -623,50 +625,54 @@ fn raster_status(h: &Host, a: &[Data]) -> Answer { } /// `Document.placedItems` and `Document.rasterItems`. -pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { - named(vec![("placedItems", get(l, doc_placed)), ("rasterItems", get(l, doc_raster))]) +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![ + ("placedItems", get(l, doc_placed), MemberInfo { collection: true, ..typed("PlacedItems") }), + ("rasterItems", get(l, doc_raster), MemberInfo { collection: true, ..typed("RasterItems") }), + ]) } /// The collections, `PlacedItem` and `RasterItem`, after `PageItem`. pub(super) fn classes(l: &Link) -> Vec { let placed_list = named(vec![ - ("typename", typename_of("PlacedItems")), - ("length", get(l, placed_length)), - ("parent", get(l, placed_parent)), - ("index", method(l, placed_index)), - ("getByName", method(l, placed_by_name)), - ("removeAll", method(l, placed_remove_all)), - ("add", method(l, placed_add)), + ("typename", typename_of("PlacedItems"), typed("string")), + ("length", get(l, placed_length), typed("number")), + ("parent", get(l, placed_parent), typed("Document")), + ("index", method(l, placed_index), returns("PlacedItem", &[("itemKey", "*")])), + ("getByName", method(l, placed_by_name), returns("PlacedItem", &[("name", "string")])), + ("removeAll", method(l, placed_remove_all), returns("undefined", &[])), + ("add", method(l, placed_add), returns("PlacedItem", &[])), ]); let raster_list = named(vec![ - ("typename", typename_of("RasterItems")), - ("length", get(l, raster_length)), - ("parent", get(l, raster_parent)), - ("index", method(l, raster_index)), - ("getByName", method(l, raster_by_name)), - ("removeAll", method(l, raster_remove_all)), + ("typename", typename_of("RasterItems"), typed("string")), + ("length", get(l, raster_length), typed("number")), + ("parent", get(l, raster_parent), typed("Document")), + ("index", method(l, raster_index), returns("RasterItem", &[("itemKey", "*")])), + ("getByName", method(l, raster_by_name), returns("RasterItem", &[("name", "string")])), + ("removeAll", method(l, raster_remove_all), returns("undefined", &[])), ]); let mut placed = named(vec![ - ("file", property(l, placed_file, placed_set_file)), - ("relink", method(l, placed_relink)), - ("embed", method(l, placed_embed)), - ("matrix", property(l, placed_matrix, placed_set_matrix)), - ("boundingBox", get(l, placed_box)), + ("file", property(l, placed_file, placed_set_file), typed("File")), + ("relink", method(l, placed_relink), returns("undefined", &[("relinkFile", "File")])), + ("embed", method(l, placed_embed), returns("undefined", &[])), + ("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")), + ("boundingBox", get(l, placed_box), typed("Array")), ]); - placed.push(later(l, "PlacedItem", "contentVariable")); + placed.extend(variables::item_members(l, "PlacedItem")); let mut raster = named(vec![ - ("bitsPerChannel", get(l, raster_bits)), - ("channels", get(l, raster_channels)), - ("colorizedGrayscale", get(l, raster_colorized)), - ("embedded", property(l, raster_embedded, raster_set_embedded)), - ("file", get(l, raster_file)), - ("imageColorSpace", get(l, raster_color_space)), - ("matrix", property(l, raster_matrix, raster_set_matrix)), - ("status", get(l, raster_status)), - ("transparent", get(l, raster_transparent)), - ("boundingBox", get(l, raster_box)), + ("bitsPerChannel", get(l, raster_bits), typed("number")), + ("channels", get(l, raster_channels), typed("number")), + ("colorizedGrayscale", get(l, raster_colorized), typed("boolean")), + ("embedded", property(l, raster_embedded, raster_set_embedded), typed("boolean")), + ("file", get(l, raster_file), typed("File")), + ("imageColorSpace", get(l, raster_color_space), typed("ImageColorSpace")), + ("matrix", property(l, raster_matrix, raster_set_matrix), typed("Matrix")), + ("status", get(l, raster_status), typed("RasterLinkState")), + ("transparent", get(l, raster_transparent), typed("boolean")), + ("boundingBox", get(l, raster_box), typed("Array")), ]); - raster.extend(["colorants", "colorize", "contentVariable", "overprint"].into_iter().map(|m| later(l, "RasterItem", m))); + raster.extend(variables::item_members(l, "RasterItem")); + raster.extend(["colorants", "colorize", "overprint"].into_iter().map(|m| later(l, "RasterItem", m))); vec![ class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 04a06629d0..2ce974dee4 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -39,11 +39,11 @@ use std::cell::Cell; use std::rc::Rc; use serde_json::{Map, Value, json}; -use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{ - Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc, property, - text, this_doc, whole, + Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc, + property, returns, text, this_doc, typed, whole, }; /// The most a scale factor of an export takes, in percent. @@ -787,13 +787,19 @@ fn app_set_interaction(h: &Host, a: &[Data]) -> Answer { } /// The members these add to `Application`. -pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { - named(vec![("open", method(l, app_open)), ("userInteractionLevel", property(l, app_interaction, app_set_interaction))]) +pub(super) fn application_members(l: &Link) -> Vec { + named(vec![ + ("open", method(l, app_open), returns("Document", &[("file", "File"), ("documentColorSpace", "DocumentColorSpace"), ("options", "*")])), + ("userInteractionLevel", property(l, app_interaction, app_set_interaction), typed("UserInteractionLevel")), + ]) } /// The members these add to `Document`. -pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { - named(vec![("saveAs", method(l, doc_save_as)), ("exportFile", method(l, doc_export_file))]) +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![ + ("saveAs", method(l, doc_save_as), returns("undefined", &[("saveIn", "File"), ("options", "*")])), + ("exportFile", method(l, doc_export_file), returns("undefined", &[("exportFile", "File"), ("exportFormat", "ExportType"), ("options", "*")])), + ]) } /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its @@ -806,7 +812,7 @@ pub(super) fn classes(link: &Link) -> Vec { current(&l)?.charge_call(64)?; Ok(fresh(c)) }); - HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + HostClass { name: c.name.into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: Some(f) } }) .collect() } diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index 4e37fb9f31..1364ea777b 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -39,11 +39,11 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde_json::{Map, Value, json}; -use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, MemberInfo, host_ref, host_ref_parts}; use super::{ - Answer, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, find_doc, float, get, id_of, item_of, item_ref, - method, named, num, number, on_doc, property, text, typename_of, whole, with_doc, + Answer, Described, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, float, get, item_of, item_ref, method, + named, node_of, num, number, on_doc, property, returns, text, typed, typename_of, whole, with_doc, }; use crate::doc::{Node, TraceView}; use crate::{NodeId, NodeKind}; @@ -179,27 +179,27 @@ fn result_id(v: &Value, key: &str) -> Option { /// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject` /// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document. -fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 4]), HostError> { +fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostError> { let Some((c, handle)) = host_ref_parts(d).filter(|(c, _)| *c == cls) else { return Err(HostError::Type(format!("this is not a {cls}"))); }; - let &[run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) }; - let doc = find_doc(h, run, uid).ok_or_else(stale)?; - let id = follow(h, doc.uid, id_of(high, low).ok_or_else(stale)?); + let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) }; + let (doc, id) = node_of(h, &handle).ok_or_else(stale)?; + let id = follow(h, doc.uid, id); let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::cmd::is_trace_group)); if !live { return Err(stale()); } - Ok((Item { doc, id }, [run, uid, high, low])) + Ok((Item { doc, id }, [run, uid, high, low, reverts])) } /// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps. -fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 4]), HostError> { +fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 5]), HostError> { match host_ref_parts(arg(a, 0)) { Some(("PluginItem", handle)) => { let item = item_of(h, arg(a, 0))?; match handle.as_slice() { - &[run, uid, high, low] => Ok((item, [run, uid, high, low])), + &[run, uid, high, low, reverts] => Ok((item, [run, uid, high, low, reverts])), _ => Err(HostError::Type("this is not a PluginItem".into())), } } @@ -681,7 +681,7 @@ fn options_store(h: &Host, a: &[Data]) -> Answer { /// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw, /// after the check that the tracing `this` names is still there. -fn missing(link: &Link, name: &'static str) -> (String, HostMember) { +fn missing(link: &Link, name: &'static str) -> Described { let message = not_implemented("TracingOptions", name); let l = link.clone(); let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec| { @@ -690,52 +690,54 @@ fn missing(link: &Link, name: &'static str) -> (String, HostMember) { tracing_of(&h, arg(&a, 0), "TracingOptions")?; Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }) + (name.to_string(), HostMember::Property { get: f.clone(), set: f }, MemberInfo { unavailable: true, ..MemberInfo::default() }) } /// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`. pub(super) fn add_trace(classes: &mut [HostClass], l: &Link) { for c in classes.iter_mut() { - match c.name.as_str() { - "PlacedItem" => c.members.push(("trace".into(), method(l, placed_trace))), - "RasterItem" => c.members.push(("trace".into(), method(l, raster_trace))), - _ => {} - } + let f: super::Member = match c.name.as_str() { + "PlacedItem" => placed_trace, + "RasterItem" => raster_trace, + _ => continue, + }; + c.members.push(("trace".into(), method(l, f))); + c.info.push(("trace".into(), returns("PluginItem", &[]))); } } /// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`. pub(super) fn classes(l: &Link) -> Vec { - let plugin = named(vec![("isTracing", get(l, plugin_is_tracing)), ("tracing", get(l, plugin_tracing))]); + let plugin = named(vec![("isTracing", get(l, plugin_is_tracing), typed("boolean")), ("tracing", get(l, plugin_tracing), typed("TracingObject"))]); let tracing = named(vec![ - ("typename", typename_of("TracingObject")), - ("anchorCount", get(l, tracing_anchors)), - ("areaCount", get(l, tracing_areas)), - ("imageResolution", get(l, tracing_resolution)), - ("parent", get(l, tracing_parent)), - ("pathCount", get(l, tracing_paths)), - ("sourceArt", get(l, tracing_source)), - ("tracingOptions", get(l, tracing_options)), - ("usedColorCount", get(l, tracing_colors)), - ("expandTracing", method(l, tracing_expand)), - ("releaseTracing", method(l, tracing_release)), + ("typename", typename_of("TracingObject"), typed("string")), + ("anchorCount", get(l, tracing_anchors), typed("number")), + ("areaCount", get(l, tracing_areas), typed("number")), + ("imageResolution", get(l, tracing_resolution), typed("number")), + ("parent", get(l, tracing_parent), typed("PluginItem")), + ("pathCount", get(l, tracing_paths), typed("number")), + ("sourceArt", get(l, tracing_source), typed("PageItem")), + ("tracingOptions", get(l, tracing_options), typed("TracingOptions")), + ("usedColorCount", get(l, tracing_colors), typed("number")), + ("expandTracing", method(l, tracing_expand), returns("GroupItem", &[("viewed", "boolean")])), + ("releaseTracing", method(l, tracing_release), returns("PageItem", &[])), ]); let mut options = named(vec![ - ("typename", typename_of("TracingOptions")), - ("parent", get(l, options_parent)), - ("preset", get(l, options_preset)), - ("tracingMode", property(l, options_mode, options_set_mode)), - ("threshold", property(l, options_threshold, options_set_threshold)), - ("fills", property(l, options_fills, options_set_fills)), - ("strokes", property(l, options_strokes, options_set_strokes)), - ("maxColors", property(l, options_max_colors, options_set_max_colors)), - ("palette", property(l, options_palette, options_set_palette)), - ("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white)), - ("minArea", property(l, options_min_area, options_set_min_area)), - ("viewRaster", property(l, options_view_raster, options_set_view_raster)), - ("viewVector", property(l, options_view_vector, options_set_view_vector)), - ("loadFromPreset", method(l, options_load)), - ("storeToPreset", method(l, options_store)), + ("typename", typename_of("TracingOptions"), typed("string")), + ("parent", get(l, options_parent), typed("TracingObject")), + ("preset", get(l, options_preset), typed("string")), + ("tracingMode", property(l, options_mode, options_set_mode), typed("TracingModeType")), + ("threshold", property(l, options_threshold, options_set_threshold), MemberInfo { min: Some(0.0), max: Some(255.0), ..typed("number") }), + ("fills", property(l, options_fills, options_set_fills), typed("boolean")), + ("strokes", property(l, options_strokes, options_set_strokes), typed("boolean")), + ("maxColors", property(l, options_max_colors, options_set_max_colors), MemberInfo { min: Some(2.0), max: Some(256.0), ..typed("number") }), + ("palette", property(l, options_palette, options_set_palette), typed("string")), + ("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white), typed("boolean")), + ("minArea", property(l, options_min_area, options_set_min_area), typed("number")), + ("viewRaster", property(l, options_view_raster, options_set_view_raster), typed("ViewRasterType")), + ("viewVector", property(l, options_view_vector, options_set_view_vector), typed("ViewVectorType")), + ("loadFromPreset", method(l, options_load), returns("boolean", &[("presetName", "string")])), + ("storeToPreset", method(l, options_store), returns("boolean", &[("presetName", "string")])), ]); options.extend(NOT_IMPLEMENTED.iter().map(|m| missing(l, m))); vec![ diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 639020ab18..8175d1ecd6 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -101,6 +101,24 @@ fn placed_add_file_links_one_image() { let _ = std::fs::remove_dir_all(base); } +/// A `placedItems.add()` result made before File › Revert is stale, as the document's other objects +/// are, and places nothing. +#[test] +fn a_placed_items_add_result_is_stale_after_a_revert() { + let base = folder("add-revert"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 2)).unwrap(); + let mut s = session(); + s.execute("document.save", &json!({"path": base.join("main/saved.vectorcraft").to_string_lossy()})).unwrap(); + let assign = format!("p.file = new File('{}')", js_path(&png)); + for read in ["p.file", assign.as_str()] { + let e = failure(&mut s, &base, &format!("var p = app.activeDocument.placedItems.add(); vc.run('file.revert'); {read};")); + assert!(e.contains("Stale page item"), "{read}: {e}"); + } + assert!(images(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn placed_file_refuses_bad_values_without_changing_the_document() { let base = folder("bad"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index da30a9cfc4..1013f6178d 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \ defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \ groupItems= height layers layers= name pageItems paragraphStyles parent pathItems placedItems rasterItems \ - rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \ + rulerOrigin rulerOrigin= rulerUnits saveAs scaleFactor selection selection= stories swatches swatches= \ symbols symbols= tags textFrames toString typename views width", ), ("Views.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 1c63a40c17..c8fee8e281 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3165,8 +3165,8 @@ through `$`: item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` result without a file throws `PlacedItem.file is required` whatever the value, and assigning `file` to one checks the file and places the image. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a - file is dropped at the end of the run. `contentVariable`, `colorants`, `colorize` and `overprint` are not available - yet. + file is dropped at the end of the run. `contentVariable` works as the variables paragraph below describes, and + `colorants`, `colorize` and `overprint` are not available yet. - `PlacedItem.trace()` and `RasterItem.trace()` trace the image with `imageTrace.make` and the Default preset and return the Image Trace object as a `PluginItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/), whose `isTracing` is `true` and whose `tracing` is its `TracingObject` From 94a6d6ccf7522096fa6e4504da453cdedc856ca5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:27:42 -0800 Subject: [PATCH 20/41] Tests: the placedItems.add() revert test edits the document first, so File > Revert is available --- crates/engine/src/tests/script_dom_images.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 8175d1ecd6..f81dbd6a66 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -112,7 +112,7 @@ fn a_placed_items_add_result_is_stale_after_a_revert() { s.execute("document.save", &json!({"path": base.join("main/saved.vectorcraft").to_string_lossy()})).unwrap(); let assign = format!("p.file = new File('{}')", js_path(&png)); for read in ["p.file", assign.as_str()] { - let e = failure(&mut s, &base, &format!("var p = app.activeDocument.placedItems.add(); vc.run('file.revert'); {read};")); + let e = failure(&mut s, &base, &format!("var d = app.activeDocument; d.pathItems.rectangle(0, 0, 10, 10); var p = d.placedItems.add(); vc.run('file.revert'); {read};")); assert!(e.contains("Stale page item"), "{read}: {e}"); } assert!(images(&s).is_empty()); From 64972e8a91be41d0ccac050f3483b6a6b940b57a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:49:36 -0800 Subject: [PATCH 21/41] Scripts: saveAs logs the save's warnings; exact grants cover linked files; a tracing's source stays first - Document.saveAs writes each warning file.saveAs gives to the console as a line that starts with "saveAs: ", and still returns undefined. - A save, export or open of a File the script names no longer reads a file an open document links to outside the script's grants. - A save or export that writes several files checks that no folder is where one of them goes before it writes the first, so none of them is written. - Moving the source image of a tracing within its tracing, and zOrder on it, leave it first; zOrder SENDTOBACK on another object in a tracing puts it just above the source. - The two new script file errors are English only; their catalog rows are removed (translations go through storytold/craft-i18n). --- crates/engine/src/cmd/fileio/access.rs | 11 +++ crates/engine/src/cmd/fileio/export_names.rs | 2 +- crates/engine/src/cmd/fileio/save.rs | 2 +- crates/engine/src/script/dom.rs | 39 +++++++--- crates/engine/src/script/dom/save_open.rs | 12 ++- crates/engine/src/script/files.rs | 5 +- crates/engine/src/tests/script_dom_images.rs | 6 +- crates/engine/src/tests/script_dom_tracing.rs | 26 +++++++ crates/engine/src/tests/script_save_open.rs | 75 +++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 2 - crates/ui-egui/src/i18n/cs.tsv | 2 - crates/ui-egui/src/i18n/da.tsv | 2 - crates/ui-egui/src/i18n/de.tsv | 2 - crates/ui-egui/src/i18n/el.tsv | 2 - crates/ui-egui/src/i18n/es.tsv | 2 - crates/ui-egui/src/i18n/fi.tsv | 2 - crates/ui-egui/src/i18n/fr.tsv | 2 - crates/ui-egui/src/i18n/hi.tsv | 2 - crates/ui-egui/src/i18n/hu.tsv | 2 - crates/ui-egui/src/i18n/id.tsv | 2 - crates/ui-egui/src/i18n/it.tsv | 2 - crates/ui-egui/src/i18n/ja.tsv | 2 - crates/ui-egui/src/i18n/ka.tsv | 2 - crates/ui-egui/src/i18n/ko.tsv | 2 - crates/ui-egui/src/i18n/nl.tsv | 2 - crates/ui-egui/src/i18n/pl.tsv | 2 - crates/ui-egui/src/i18n/pt-br.tsv | 2 - crates/ui-egui/src/i18n/ru.tsv | 2 - crates/ui-egui/src/i18n/sv.tsv | 2 - crates/ui-egui/src/i18n/tr.tsv | 2 - crates/ui-egui/src/i18n/uk.tsv | 2 - crates/ui-egui/src/i18n/vi.tsv | 2 - crates/ui-egui/src/i18n/zh-hans.tsv | 2 - crates/ui-egui/src/i18n/zh-hant.tsv | 2 - docs/mcp.md | 3 +- 35 files changed, 161 insertions(+), 70 deletions(-) diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 8ca1fedcd7..720adc8388 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -267,6 +267,17 @@ pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } +/// [`may_write`], and an error when something other than a regular file is at `path` (a folder): +/// the check each file of a set gets before the first of them is written. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn may_write_file(path: &str) -> Result<()> { + may_write(path)?; + match std::fs::metadata(path) { + Ok(m) if !m.is_file() => Err(EngineError::Other(format!("{path}: not a file"))), + _ => Ok(()), + } +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { may_read(path)?; diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..f44b390a70 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -87,7 +87,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 { for (p, _) in &files { - super::may_write(p)?; + super::access::may_write_file(p)?; } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 5f16c2ef33..8a53cefb76 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1086,7 +1086,7 @@ impl SaveJob { // job names refused files ([`SaveJob::naming_refused_files`]). #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, refused)) = files.iter().find_map(|(p, _)| super::may_write(p).err().map(|e| (p, e))) + && let Some((p, refused)) = files.iter().find_map(|(p, _)| super::access::may_write_file(p).err().map(|e| (p, e))) { return Err(if self.names_refused { super::access::naming_in_error(refused, p) } else { refused }); } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index fc315cb49e..7964fee085 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2632,9 +2632,11 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let from = d.position(id); let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); // A clip group's first child is its clipping path, and an Image Trace object's its source - // image: both stay first (the source image itself may go to the end of its own tracing). - let source = crate::cmd::is_trace_source(d, id) && d.parent_of(id) == Some(to.parent); - let clips = d.node(to.parent).is_some_and(|n| n.clips() || (crate::cmd::is_trace_group(n) && !source)) && count > 0; + // image: both stay first, and the source image moved within its own tracing stays where it is. + if crate::cmd::is_trace_source(d, id) && d.parent_of(id) == Some(to.parent) { + return Ok(0); + } + let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0; let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -2743,19 +2745,36 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (before, after) = with_doc(h, item.doc, |_, st| { - let at = st.doc.position(item.id); - let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); - (at.map(|(_, i, _)| i), count) + let (before, after, parent, source, in_trace) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let at = d.position(item.id); + let count = at.and_then(|(p, ..)| d.children(p).map(Vec::len)).unwrap_or(0); + let parent = d.parent_of(item.id); + let in_trace = parent.and_then(|p| d.node(p)).is_some_and(crate::cmd::is_trace_group); + (at.map(|(_, i, _)| i), count, parent, crate::cmd::is_trace_source(d, item.id), in_trace) }); let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; + // The source image an Image Trace object keeps first stays first, and the other objects in it + // stay above it. + if source { + return Ok(Data::Undefined); + } + let bottom = usize::from(in_trace); let top = i + 1 >= after; let unchanged = match id { "object.arrange.bringToFront" | "object.arrange.bringForward" => top, - _ => i == 0, + _ => i <= bottom, }; - if !unchanged { - edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + if unchanged { + return Ok(Data::Undefined); + } + match parent { + Some(p) if in_trace && id == "object.arrange.sendToBack" => { + edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": bottom}))?; + } + _ => { + edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + } } Ok(Data::Undefined) } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 2ce974dee4..52d8af2661 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -42,8 +42,8 @@ use serde_json::{Map, Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{ - Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc, - property, returns, text, this_doc, typed, whole, + Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, command_value, current, doc_ref, given, method, named, + num, on_doc, property, returns, text, this_doc, typed, whole, }; /// The most a scale factor of an export takes, in percent. @@ -630,7 +630,7 @@ fn refused(message: &str, path: &str) -> HostError { /// Runs `f` with the commands' reads and writes held to the script's own grants /// ([`super::super::files::Disk::exact`]). -fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { +fn exactly(h: &Host, f: impl FnOnce() -> Result) -> Result { h.disk.borrow_mut().exact = true; let r = f(); h.disk.borrow_mut().exact = false; @@ -668,7 +668,11 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + let (_, value) = exactly(h, || on_doc(h, doc.uid, false, |h| command_value(h, "file.saveAs", &Value::Object(p))))?; + // Each warning of the save (what the format leaves out) goes to the console. + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("saveAs: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } Ok(Data::Undefined) } diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 41812feedf..988dfb145c 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -475,8 +475,9 @@ impl Disk { /// and the files it may only read because the documents open when the run began link to them, /// `linked`. pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { - // A save, export or open of a `File` the script names reads and writes as its `File` would. - let documents = if self.exact { Vec::new() } else { documents }; + // A save, export or open of a `File` the script names reads and writes as its `File` would, + // without the files of open documents or the files they link to. + let (documents, linked) = if self.exact { (Vec::new(), crate::file_access::LinkedFiles::default()) } else { (documents, linked) }; let held = self.open.values().filter_map(|o| o.target.clone()).collect(); crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, linked, also: None } } diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index f81dbd6a66..6693499a2e 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -112,7 +112,11 @@ fn a_placed_items_add_result_is_stale_after_a_revert() { s.execute("document.save", &json!({"path": base.join("main/saved.vectorcraft").to_string_lossy()})).unwrap(); let assign = format!("p.file = new File('{}')", js_path(&png)); for read in ["p.file", assign.as_str()] { - let e = failure(&mut s, &base, &format!("var d = app.activeDocument; d.pathItems.rectangle(0, 0, 10, 10); var p = d.placedItems.add(); vc.run('file.revert'); {read};")); + let e = failure( + &mut s, + &base, + &format!("var d = app.activeDocument; d.pathItems.rectangle(0, 0, 10, 10); var p = d.placedItems.add(); vc.run('file.revert'); {read};"), + ); assert!(e.contains("Stale page item"), "{read}: {e}"); } assert!(images(&s).is_empty()); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index dd48079cef..333ef058cf 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -552,6 +552,32 @@ fn an_object_placed_at_the_end_of_a_tracing_stays_above_its_source() { let _ = std::fs::remove_dir_all(base); } +/// The source image stays a tracing's first child when it goes to the front of the tracing, and +/// when another object in the tracing is sent to the back or the source is brought to the front. +#[test] +fn reordering_inside_a_tracing_keeps_the_source_first() { + let base = folder("reorder"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\ + r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.isTracing);\ + r.zOrder(ZOrderMethod.SENDTOBACK); vc.log(p.isTracing); r.zOrder(ZOrderMethod.SENDBACKWARD); vc.log(p.isTracing);\ + s.zOrder(ZOrderMethod.BRINGTOFRONT); s.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(p.isTracing); vc.log(p.tracing.sourceArt.name);", + ); + assert_eq!(out, [json!(true), json!(true), json!(true), json!(true), json!("src")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + let names: Vec> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[..2], [Some("src".to_string()), Some("moved".to_string())], "the source stays first: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_source_art_is_not_listed_with_the_images() { let base = folder("lists"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 3812314b26..c006cb2059 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,25 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +/// The warnings of the save go to the console, and `saveAs` still returns nothing. +#[test] +fn save_as_logs_the_saves_warnings() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let text = format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log(String(d.saveAs(new File({d} + '/a.svg'))));" + ); + let r = run(&mut s, &base, &text).unwrap_or_else(|e| panic!("{text}: {e}")); + assert_eq!(r["log"], json!(["undefined"])); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + let warned = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ") && l.contains("keeps the artwork")); + assert!(warned, "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + /// Without options, a save or export writes what an untouched new options object of its class gives. #[test] fn omitted_options_are_a_new_options_objects_defaults() { @@ -234,9 +253,37 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(&board, perms).unwrap(); + // A folder where an artboard's file goes writes none of them either. + std::fs::remove_file(&board).unwrap(); + std::fs::create_dir(&board).unwrap(); + let e = failure(&mut s, &base, &save); + assert!(e.contains("not a file"), "{e}"); + assert!(!central.exists(), "the central file is not written when a folder is where an artboard's file goes"); let _ = std::fs::remove_dir_all(base); } +/// An export that writes several files writes none of them when a folder is where one of them goes. +#[test] +fn an_export_writes_nothing_when_a_folder_is_where_one_of_its_files_goes() { + let dir = vectorcraft_testkit::TempDir::new("export-folder-target"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let path = dir.join("a.eps").to_string_lossy().into_owned(); + let export = json!({"path": path, "format": "eps", "useArtboards": true}); + let r = s.execute("document.export", &export).unwrap(); + let files: Vec = + r["files"].as_array().unwrap_or_else(|| panic!("several files: {r}")).iter().map(|f| PathBuf::from(f.as_str().unwrap())).collect(); + assert!(files.len() > 1, "{r}"); + for f in &files { + std::fs::remove_file(f).unwrap(); + } + std::fs::create_dir(files.last().unwrap()).unwrap(); + let e = s.execute("document.export", &export).unwrap_err().to_string(); + assert!(e.contains("not a file"), "{e}"); + assert!(files[..files.len() - 1].iter().all(|f| !f.exists()), "no file is written when a folder is where one goes"); +} + /// Every path goes through the script's file grants, as a `File` opened for reading or writing. #[test] fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { @@ -368,6 +415,34 @@ fn open_reads_linked_files_only_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +/// A file an open document links to is read by `open` only where the script may read, too. +#[test] +fn open_reads_files_open_documents_link_to_only_where_the_script_may() { + let base = folder("linked-by-open"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/linked.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": true})).unwrap(); + let href = pic.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); + std::fs::write( + dir.join("page.svg"), + format!(""), + ) + .unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("page.svg")))); + let mut sizes = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + sizes.push((im.width, im.height)); + } + }); + assert_eq!(sizes.len(), 1, "{sizes:?}"); + assert_ne!(sizes[0], (2, 2), "the linked file outside the script's folders is not read"); + let _ = std::fs::remove_dir_all(base); +} + /// An SVG export with `embedRasterImages` false writes the document's embedded image beside the /// SVG, and when that file may not be written, the SVG is not written either. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e032c7b6ab..555080655a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6648,8 +6648,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written No s’ha pogut escriure el fitxer de l’script @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi -@msg Script file is read-only El fitxer de l’script és només de lectura -@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a931fb3ff1..8d11266cdd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5430,8 +5430,6 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file could not be written Soubor skriptu nelze zapsat @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis -@msg Script file is read-only Soubor skriptu je jen pro čtení -@msg Script file is open for writing Soubor skriptu je otevřený pro zápis @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9ce2907169..9820804ff0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -88,8 +88,6 @@ @msg Script file could not be written Scriptfilen kunne ikke skrives @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning -@msg Script file is read-only Scriptfilen er skrivebeskyttet -@msg Script file is open for writing Scriptfilen er åben for skrivning @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index cdcd2ff353..d29f3c46c0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5007,8 +5007,6 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file could not be written Skriptdatei konnte nicht geschrieben werden @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet -@msg Script file is read-only Skriptdatei ist schreibgeschützt -@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e3eb8d8709..e4a651342a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2839,8 +2839,6 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή -@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση -@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cac7cad37c..008a0b6483 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5117,8 +5117,6 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file could not be written No se pudo escribir el archivo del script @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura -@msg Script file is read-only El archivo del script es de solo lectura -@msg Script file is open for writing El archivo del script está abierto para escritura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 6d5b949f74..ffbeb6f49b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5360,8 +5360,6 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten -@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa -@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2a117d6b79..7e03e3b7c4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5074,8 +5074,6 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file could not be written Le fichier du script n’a pas pu être écrit @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture -@msg Script file is read-only Le fichier du script est en lecture seule -@msg Script file is open for writing Le fichier du script est ouvert en écriture @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 30e8126e7d..8ad28968c5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7857,8 +7857,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है -@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है -@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 7449b965bf..3116815efa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5952,8 +5952,6 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file could not be written A parancsfájl fájlját nem sikerült írni @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva -@msg Script file is read-only A parancsfájl fájlja csak olvasható -@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 6d95149f85..b159d2bfb7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8920,8 +8920,6 @@ breakText Glyphs Glif @msg Script file could not be written File skrip tidak dapat ditulis @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis -@msg Script file is read-only File skrip hanya dapat dibaca -@msg Script file is open for writing File skrip sedang dibuka untuk ditulis @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 40719fd02b..d6b341a367 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5145,8 +5145,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Impossibile scrivere il file dello script @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura -@msg Script file is read-only Il file dello script è di sola lettura -@msg Script file is open for writing Il file dello script è aperto in scrittura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9d430afdf8..48f6dd36cf 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5981,8 +5981,6 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file could not be written スクリプトのファイルを書き込めませんでした @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません -@msg Script file is read-only スクリプトのファイルは読み取り専用です -@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d527f78d39..cbb58ee5ab 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8654,8 +8654,6 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის -@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია -@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57a6a0756b..bd430d2fc1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5910,8 +5910,6 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 -@msg Script file is read-only 스크립트 파일이 읽기 전용입니다 -@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 8e83cb948a..20365f1488 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -90,8 +90,6 @@ @msg Script file could not be written Het scriptbestand kon niet worden geschreven @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven -@msg Script file is read-only Het scriptbestand is alleen-lezen -@msg Script file is open for writing Het scriptbestand is geopend voor schrijven @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 110b4c1c82..4a22a1dd93 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5247,8 +5247,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written Nie można zapisać pliku skryptu @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu -@msg Script file is read-only Plik skryptu jest tylko do odczytu -@msg Script file is open for writing Plik skryptu jest otwarty do zapisu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 46c09ae7d0..6d910ce85f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6292,8 +6292,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Não foi possível gravar o arquivo do script @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação -@msg Script file is read-only O arquivo do script é somente leitura -@msg Script file is open for writing O arquivo do script está aberto para gravação @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 042cd9907e..60906af64a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5142,8 +5142,6 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file could not be written Не удалось записать файл скрипта @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи -@msg Script file is read-only Файл скрипта доступен только для чтения -@msg Script file is open for writing Файл скрипта открыт для записи @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index aa2fdb6dd2..bf7420d255 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5015,8 +5015,6 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file could not be written Skriptets fil kunde inte skrivas @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning -@msg Script file is read-only Skriptets fil är skrivskyddad -@msg Script file is open for writing Skriptets fil är öppen för skrivning @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7ee0cf0e12..830b60e56b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4843,8 +4843,6 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file could not be written Betiğin dosyası yazılamadı @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil -@msg Script file is read-only Betiğin dosyası salt okunur -@msg Script file is open for writing Betiğin dosyası yazmak için açık @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7efb82793c..09a9e4bf6d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5129,8 +5129,6 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file could not be written Не вдалося записати файл скрипту @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису -@msg Script file is read-only Файл скрипту доступний лише для читання -@msg Script file is open for writing Файл скрипту відкрито для запису @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 52c6ecf841..bc63725d0f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5642,8 +5642,6 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file could not be written Không thể ghi tệp của tập lệnh @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi -@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc -@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 82fcc938a1..9b7e1c7bbc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5637,8 +5637,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 无法写入脚本的文件 @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 -@msg Script file is read-only 脚本的文件为只读 -@msg Script file is open for writing 脚本的文件已以写入方式打开 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 838cb74394..2e3bae2d60 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2978,8 +2978,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 無法寫入指令碼的檔案 @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 -@msg Script file is read-only 指令碼的檔案為唯讀 -@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 diff --git a/docs/mcp.md b/docs/mcp.md index 8d7364a60e..95d0596d7a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3097,7 +3097,8 @@ through `$`: strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves that this page does not describe are not defined yet and read as `undefined`. -- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. +- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. Each warning the + save gives goes to the console as a line that starts with `saveAs: `. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). From db7fe4d38be3aa883dfa3c92c8457462b08eb7a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:02:07 -0800 Subject: [PATCH 22/41] Scripts: tracing keeps added images and direct selections; app.open logs warnings - Expanding a tracing removes only its source image; other images a script moved or duplicated into the group stay. - A TracingObject goes stale when its original source image is gone, even when another image now sits first in the group. - Tracing, retracing, expanding and releasing restore the whole selection, anchors and segments included, with only the replaced object remapped. - app.open writes the open's warnings to the script console, as saveAs does. - embed() checks the image's link state after the command instead of a returned id rounded to a JavaScript number. - The placed-image tests pass ordinary drive paths to File on Windows. --- crates/engine/src/cmd/buildcmds/trace.rs | 3 +- crates/engine/src/script/dom/images.rs | 15 +--- crates/engine/src/script/dom/save_open.rs | 5 +- crates/engine/src/script/dom/tracing.rs | 38 +++++---- crates/engine/src/tests/script_dom_images.rs | 35 +++++++- crates/engine/src/tests/script_dom_tracing.rs | 81 +++++++++++++++++++ crates/engine/src/tests/script_save_open.rs | 20 +++++ 7 files changed, 163 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 3e0747370c..975a8b03c1 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1400,7 +1400,8 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result { n.name = None; n.extras_mut().trace = None; if let Some(ch) = n.children_mut() { - ch.retain(|c| !matches!(c.kind, NodeKind::Image(_))); + let source = ch.first().map(|c| c.id); + ch.retain(|c| Some(c.id) != source); } if by_color { let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default(); diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 7e744be0b0..d32a183ebc 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -159,14 +159,6 @@ fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> { } } -fn id_value(d: Option<&Data>) -> Option { - match d { - Some(Data::Number(n)) => whole(*n).map(NodeId), - Some(Data::Array(a)) => id_value(a.first()), - _ => None, - } -} - // ---- PlacedItems and RasterItems ---- fn collection(placed: bool) -> &'static str { @@ -422,11 +414,8 @@ fn placed_embed(h: &Host, a: &[Data]) -> Answer { if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") { return Err(HostError::Error(MISSING_LINK.into())); } - let r = edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?; - let embedded = match field(&r, "embedded") { - Some(Data::Array(ids)) => ids.iter().any(|d| id_value(Some(d)) == Some(item.id)), - _ => false, - }; + edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?; + let embedded = with_doc(h, item.doc, |_, st| matches!(st.doc.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none())); if !embedded { return Err(HostError::Error(MISSING_LINK.into())); } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 52d8af2661..65691227c9 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -767,7 +767,10 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let (r, value) = exactly(h, || command_value(h, "document.open", &Value::Object(p)))?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("open: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index 1364ea777b..c26cf2839e 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -115,6 +115,7 @@ const NOT_IMPLEMENTED: &[&str] = &[ #[derive(Default)] pub(super) struct State { next: RefCell>, + sources: RefCell>, } /// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put @@ -185,8 +186,11 @@ fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostErr }; let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) }; let (doc, id) = node_of(h, &handle).ok_or_else(stale)?; + let source = h.dom.tracing.sources.borrow().get(&(doc.uid, id.0)).copied().ok_or_else(stale)?; let id = follow(h, doc.uid, id); - let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::cmd::is_trace_group)); + let live = with_doc(h, doc, |_, st| { + st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) + }); if !live { return Err(stale()); } @@ -218,27 +222,24 @@ fn read_group(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) - /// Runs command `id` with `params` on `item`'s document → the object its result names under `key`. /// The selection stays as it was, with that object in place of `item`. fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result { - let before = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); + let mut before = with_doc(h, item.doc, |_, st| st.selection.clone()); on_doc(h, item.doc.uid, false, |h| { let (_, r) = command_value(h, id, params)?; let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?; - let (want, now) = { + let remap = |i: NodeId| if i == item.id { new } else { i }; + before.objects = before.objects.into_iter().map(remap).collect(); + let mut seen = HashSet::new(); + before.objects.retain(|i| seen.insert(*i)); + before.key = before.key.map(remap); + before.target = before.target.map(remap); + before.on_path_member = before.on_path_member.map(remap); + let restore = { let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - let mut want: Vec = Vec::new(); - for i in before.iter().map(|i| if *i == item.id { new } else { *i }) { - if st.doc.node(i).is_some() && !want.contains(&i) { - want.push(i); - } - } - (want, st.selection.objects.clone()) + (st.selection != before).then(|| st.doc.clone()) }; - if now != want { - if want.is_empty() { - command(h, "select.none", &json!({}))?; - } else { - command(h, "select.set", &json!({"ids": want.iter().map(|i| i.0).collect::>()}))?; - } + if let Some(doc) = restore { + super::restore_selection(h, &doc, &before)?; } Ok(new) }) @@ -299,7 +300,10 @@ fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer { } fn plugin_tracing(h: &Host, a: &[Data]) -> Answer { - let (_, handle) = plugin_of(h, a)?; + let (item, handle) = plugin_of(h, a)?; + let source = read_group(h, item, |_, g| g.children().and_then(|c| c.first()).map(|n| n.id).ok_or_else(stale))?; + let (_, original) = node_of(h, &handle).ok_or_else(stale)?; + h.dom.tracing.sources.borrow_mut().entry((item.doc.uid, original.0)).or_insert(source); Ok(host_ref("TracingObject", &handle)) } diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 6693499a2e..0caa9403e1 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -14,7 +14,7 @@ fn folder(name: &str) -> PathBuf { let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("main")).unwrap(); std::fs::create_dir_all(base.join("outside")).unwrap(); - std::fs::canonicalize(&base).unwrap() + PathBuf::from(plain_path(&std::fs::canonicalize(&base).unwrap().to_string_lossy())) } /// A `w`×`h` 8-bit gray PNG. @@ -25,7 +25,21 @@ fn gray_png(w: u32, h: u32) -> Vec { } fn js_path(p: &Path) -> String { - p.to_string_lossy().replace('\\', "\\\\").replace('\'', "\\'") + plain_path(&p.to_string_lossy()).replace('\\', "\\\\").replace('\'', "\\'") +} + +fn plain_path(path: &str) -> String { + if let Some(tail) = path.strip_prefix(r"\\?\UNC\") { format!(r"\\{tail}") } else { path.strip_prefix(r"\\?\").unwrap_or(path).to_string() } +} + +#[test] +fn fixture_paths_strip_verbatim_prefixes_on_every_platform() { + let drive = format!("{}{}", r"\\?\", r"C:\x\a.png"); + let unc = format!("{}{}", r"\\?\UNC\", r"server\share\a.png"); + assert_eq!(plain_path(&drive), r"C:\x\a.png"); + assert_eq!(plain_path(&unc), r"\\server\share\a.png"); + assert_eq!(js_path(Path::new(&drive)), r"C:\\x\\a.png"); + assert_eq!(plain_path("/tmp/a.png"), "/tmp/a.png"); } /// A session with one 400 × 300 pt document. @@ -334,6 +348,23 @@ fn missing_link_embed_reports_error() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn embed_keeps_an_exact_image_id_above_javascript_integer_precision() { + let base = folder("embed-big-id"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let id = place(&mut s, &png, true); + assert_eq!(id, NodeId(big)); + let out = + log(&mut s, &base, "var d = app.activeDocument; d.placedItems[0].embed(); vc.log(d.placedItems.length); vc.log(d.rasterItems[0].embedded);"); + assert_eq!(out, [json!(0), json!(true)]); + assert_eq!(images(&s), vec![(id, None)]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn raster_metadata_uses_encoded_header_not_rgb_fallback() { let base = folder("meta"); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 333ef058cf..ed9b1e5431 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -222,6 +222,87 @@ fn trace_expand_returns_group_and_stales_plugin() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn expand_keeps_images_moved_and_duplicated_into_the_tracing() { + let base = folder("expand-other-images"); + let (mut s, source) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.name = 'other';\ + r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var g = p.tracing.expandTracing(); vc.log(g.typename); vc.log(d.rasterItems.length); vc.log(r.name);", + ); + assert_eq!(out, [json!("GroupItem"), json!(2), json!("other")]); + let d = &s.active().unwrap().doc; + assert!(d.node(source).is_none()); + let group = top(&s)[0]; + let images: Vec<_> = d.children(Some(group)).unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).collect(); + assert_eq!(images.len(), 2); + assert!(images.iter().all(|n| n.name.as_deref() == Some("other"))); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_handle_is_stale_when_another_image_replaces_its_source() { + let base = folder("replaced-source"); + let (mut s, source) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[1].trace(), t = p.tracing, o = t.tracingOptions, r = d.rasterItems[0];\ + r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\ + try {{ t.sourceArt; }} catch (e) {{ m.push(e.message); }}\ + try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }}\ + try {{ o.threshold; }} catch (e) {{ m.push(e.message); }} vc.log(m);", + source.0 + ), + ); + assert_eq!(out, [json!(vec!["Stale page item"; 3])]); + assert!(s.active().unwrap().doc.node(source).is_none()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_replacements_preserve_direct_selection_of_other_paths() { + for (name, finish) in [ + ("make", ""), + ("retrace", "p.tracing.tracingOptions.threshold = 90;"), + ("expand", "p.tracing.expandTracing();"), + ("release", "p.tracing.releaseTracing();"), + ] { + let base = folder(&format!("direct-selection-{name}")); + let (mut s, image) = session(&base, false); + let mut paths = vec![]; + for x in [100, 200] { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 20, "height": 20})).unwrap(); + paths.push(NodeId(r["id"].as_u64().unwrap())); + } + s.execute("select.anchors", &json!({"id": paths[0].0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": paths[1].0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + s.execute("select.add", &json!({"ids": [image.0]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(); {finish}")); + let after = &s.active().unwrap().selection; + assert_eq!(after.anchors, before.anchors, "{name}"); + assert_eq!(after.segments, before.segments, "{name}"); + assert_eq!(after.objects.len(), before.objects.len(), "{name}"); + assert_eq!(after.objects[..2], paths, "{name}"); + if name == "release" { + assert_eq!(after.objects[2], image); + } else { + assert_ne!(after.objects[2], image, "{name}"); + assert!(matches!(s.active().unwrap().doc.node(after.objects[2]).unwrap().kind, NodeKind::Group { .. })); + } + let _ = std::fs::remove_dir_all(base); + } +} + #[test] fn trace_options_retrace_preserves_source_and_view() { let base = folder("options"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index c006cb2059..8c62fb87d9 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -112,6 +112,26 @@ fn save_as_logs_the_saves_warnings() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn open_logs_warnings_for_an_unreadable_linked_image() { + let base = folder("open-warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let svg = dir.join("missing-image.svg"); + std::fs::write( + &svg, + "\ + ", + ) + .unwrap(); + let text = format!("Folder.userData; var d = app.open(new File({})); vc.log(d.typename);", quoted(&svg)); + let r = run(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!(["Document"])); + let lines = r["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("open: ") && l.contains("missing.png")), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + /// Without options, a save or export writes what an untouched new options object of its class gives. #[test] fn omitted_options_are_a_new_options_objects_defaults() { From 466debdc8fb9066a264954c1c4f227ed8605c93d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:00:42 -0800 Subject: [PATCH 23/41] Scripts: tracing refuses protected art; exportFile logs warnings; saveAs rejects unknown extensions - trace(), retracing, expanding, releasing and view changes refuse a locked or hidden item, or one on a locked artboard, and leave it unchanged. - exportFile writes the export's warnings to the script console. - saveAs without options refuses a path whose extension names no format, after the path's grant check. - tracing.parent returns the same PluginItem handle the script holds, and a placed item bound by assigning file is the same object in collections. - PluginItem.isTracing goes stale with its TracingObject when the original source image is gone. --- crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/images.rs | 6 ++ crates/engine/src/script/dom/save_open.rs | 12 ++- crates/engine/src/script/dom/tracing.rs | 34 ++++++-- crates/engine/src/tests/script_dom_images.rs | 20 +++++ crates/engine/src/tests/script_dom_tracing.rs | 87 ++++++++++++++++++- crates/engine/src/tests/script_save_open.rs | 45 ++++++++++ 7 files changed, 198 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7964fee085..6ba1934af1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -581,10 +581,11 @@ fn item_of(h: &Host, d: &Data) -> std::result::Result { } _ => return Err(HostError::Type("this is not a page item".into())), }; + let original = id; let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id }; let s = h.session.borrow(); let st = &s.documents()[doc.index]; - if st.doc.node(id).is_none_or(|n| typename(n) != Some(class)) { + if st.doc.node(id).is_none_or(|n| typename(n) != Some(class) || (class == "PluginItem" && !tracing::same_source(h, doc.uid, original, n))) { return Err(HostError::Error(STALE_ITEM.into())); } Ok(Item { doc, id }) @@ -619,6 +620,11 @@ 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("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))), + Some("PluginItem") => { + tracing::remember_source(h, st.uid, n); + host_ref("PluginItem", &node_handle(h, st, id)) + } Some(t) => host_ref(t, &node_handle(h, st, id)), None => host_ref("Layer", &node_handle(h, st, id)), }, diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index d32a183ebc..d3d8c997b4 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -94,6 +94,12 @@ struct Pending { bound: Option, } +pub(super) fn bound_ref(h: &Host, st: &DocState, id: NodeId) -> Option { + let pending = h.dom.images.pending.borrow(); + let slot = pending.iter().position(|p| p.uid == st.uid && p.reverts == st.reverts && p.bound == Some(id))?; + Some(host_ref("PlacedItem", &[float(h.run), float(st.uid), 0.0, 0.0, float(st.reverts), float(slot as u64)])) +} + /// The slot of a `PlacedItems.add()` result in this run, from its handle. A result whose document /// was closed or reverted since is stale. fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 65691227c9..f8c0cb5d16 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -42,8 +42,8 @@ use serde_json::{Map, Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{ - Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, command_value, current, doc_ref, given, method, named, - num, on_doc, property, returns, text, this_doc, typed, whole, + Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command_value, current, doc_ref, given, method, named, num, + on_doc, property, returns, text, this_doc, typed, whole, }; /// The most a scale factor of an export takes, in percent. @@ -667,6 +667,9 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + if given_options.is_none() && extension.as_deref().is_some_and(|e| !e.is_empty()) && crate::cmd::fileio::format_for_name(path).is_none() { + return Err(HostError::Error("saveAs needs a recognized file extension or format options".into())); + } p.insert("path".into(), json!(plain(real))); let (_, value) = exactly(h, || on_doc(h, doc.uid, false, |h| command_value(h, "file.saveAs", &Value::Object(p))))?; // Each warning of the save (what the format leaves out) goes to the console. @@ -726,7 +729,10 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + let (_, value) = exactly(h, || on_doc(h, doc.uid, false, |h| command_value(h, "document.export", &Value::Object(p))))?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("exportFile: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } Ok(Data::Undefined) } diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index c26cf2839e..e2c3708000 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -146,6 +146,17 @@ fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0); } +pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { + if let Some(source) = group.children().and_then(|c| c.first()) { + h.dom.tracing.sources.borrow_mut().entry((uid, group.id.0)).or_insert(source.id); + } +} + +pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { + let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied(); + source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) +} + /// The error of a member with no VectorCraft setting. pub fn not_implemented(class: &str, name: &str) -> String { format!("{class}.{name} is not implemented") @@ -185,12 +196,9 @@ fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostErr return Err(HostError::Type(format!("this is not a {cls}"))); }; let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) }; - let (doc, id) = node_of(h, &handle).ok_or_else(stale)?; - let source = h.dom.tracing.sources.borrow().get(&(doc.uid, id.0)).copied().ok_or_else(stale)?; - let id = follow(h, doc.uid, id); - let live = with_doc(h, doc, |_, st| { - st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) - }); + let (doc, original) = node_of(h, &handle).ok_or_else(stale)?; + let id = follow(h, doc.uid, original); + let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && same_source(h, doc.uid, original, g))); if !live { return Err(stale()); } @@ -219,9 +227,18 @@ fn read_group(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) - }) } +fn refuse_uneditable(h: &Host, item: Item) -> Result<(), HostError> { + let editable = with_doc(h, item.doc, |_, st| super::editable(&st.doc, item.id) && !super::on_locked_artboard(h, st, item.id)); + if !editable { + return Err(HostError::Error(format!("Cannot edit page item {}", item.id.0))); + } + Ok(()) +} + /// Runs command `id` with `params` on `item`'s document → the object its result names under `key`. /// The selection stays as it was, with that object in place of `item`. fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result { + refuse_uneditable(h, item)?; let mut before = with_doc(h, item.doc, |_, st| st.selection.clone()); on_doc(h, item.doc.uid, false, |h| { let (_, r) = command_value(h, id, params)?; @@ -402,8 +419,8 @@ fn tracing_resolution(h: &Host, a: &[Data]) -> Answer { } fn tracing_parent(h: &Host, a: &[Data]) -> Answer { - let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; - Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))) + let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(host_ref("PluginItem", &handle)) } fn tracing_source(h: &Host, a: &[Data]) -> Answer { @@ -608,6 +625,7 @@ fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer { let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v }; let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?; if *to != view { + refuse_uneditable(h, item)?; edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?; } Ok(Data::Undefined) diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 0caa9403e1..6628e48bdc 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -86,6 +86,26 @@ fn place(s: &mut Session, path: &Path, link: bool) -> NodeId { NodeId(r["ids"][0].as_u64().unwrap()) } +#[test] +fn placed_add_file_keeps_wrapper_identity_in_collections() { + let base = folder("bound-identity"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems.add(); p.file = new File('{}'); p.name = 'placed'; d.selection = [p];\ + vc.log(p === d.placedItems[0]); vc.log(p === d.placedItems.getByName('placed'));\ + vc.log(p === d.pageItems[0]); vc.log(p === d.selection[0]);", + js_path(&png) + ), + ); + assert_eq!(out, vec![json!(true); 4]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn placed_add_file_links_one_image() { let base = folder("add"); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index ed9b1e5431..523c70e5b2 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -245,6 +245,88 @@ fn expand_keeps_images_moved_and_duplicated_into_the_tracing() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn tracing_replacements_refuse_protected_artwork() { + let base = folder("protected-replacements"); + for operation in ["trace", "retrace", "expand", "release", "view"] { + for protection in ["locked", "hidden", "locked-layer", "hidden-layer", "locked-artboard"] { + let (mut s, image) = session(&base, false); + let (target, action) = if operation == "trace" { + (image, "item.trace();") + } else { + let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let action = match operation { + "retrace" => "item.tracing.tracingOptions.threshold = 90;", + "expand" => "item.tracing.expandTracing();", + "view" => "item.tracing.tracingOptions.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES;", + _ => "item.tracing.releaseTracing();", + }; + (NodeId(r["id"].as_u64().unwrap()), action) + }; + s.edit("Protect artwork", |d, _| { + if protection == "locked-artboard" { + d.artboards[0].locked = true; + } else { + let protected = if protection.ends_with("-layer") { d.layers[0].id } else { target }; + let node = d.node_mut(protected).unwrap(); + node.locked = protection.starts_with("locked"); + node.visible = !protection.starts_with("hidden"); + } + Ok(()) + }) + .unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!("var item = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"), + ); + assert_eq!(out, [json!(format!("Cannot edit page item {}", target.0))], "{operation}: {protection}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{operation}: {protection}"); + assert_eq!(s.active().unwrap().selection, selection); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn tracing_parent_keeps_plugin_identity_after_retracing() { + let base = folder("parent-identity"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing;\ + vc.log(t.parent === p); t.tracingOptions.threshold = 90; vc.log(t.parent === p);\ + vc.log(p.tracing.parent === p); t.tracingOptions.threshold = 100; vc.log(t.parent === p);", + ); + assert_eq!(out, vec![json!(true); 4]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn plugin_is_tracing_refuses_a_replaced_source_without_reading_tracing() { + let base = folder("plugin-replaced-source"); + let (mut s, source) = session(&base, false); + s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0];\ + r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\ + try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\ + try {{ p.tracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);", + source.0 + ), + ); + assert_eq!(out, [json!(["Stale page item", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn tracing_handle_is_stale_when_another_image_replaces_its_source() { let base = folder("replaced-source"); @@ -259,11 +341,12 @@ fn tracing_handle_is_stale_when_another_image_replaces_its_source() { r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\ try {{ t.sourceArt; }} catch (e) {{ m.push(e.message); }}\ try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }}\ - try {{ o.threshold; }} catch (e) {{ m.push(e.message); }} vc.log(m);", + try {{ o.threshold; }} catch (e) {{ m.push(e.message); }}\ + try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);", source.0 ), ); - assert_eq!(out, [json!(vec!["Stale page item"; 3])]); + assert_eq!(out, [json!(vec!["Stale page item"; 4])]); assert!(s.active().unwrap().doc.node(source).is_none()); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8c62fb87d9..bee1b78188 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,51 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn export_file_logs_encoder_warnings() { + let base = folder("export-warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let text = format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\ + d.pathItems[0].name = 'invalid\\u0001name';\ + vc.log(String(d.exportFile(new File({}), ExportType.SVG)));", + quoted(&dir.join("warnings.svg")) + ); + let r = run(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + assert!(dir.join("warnings.svg").is_file()); + let lines = r["console"]["lines"].as_array().unwrap(); + let warning = "exportFile: Object names containing invalid XML characters were left out of SVG name attributes"; + assert!(lines.iter().any(|line| line.as_str() == Some(warning)), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn save_as_rejects_unknown_extensions_without_format_options() { + let base = folder("unknown-extension"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + for options in ["", ", null", ", undefined"] { + let text = format!("Folder.userData; app.activeDocument.saveAs(new File({}){options});", quoted(&dir.join("typo.pfd"))); + let e = failure(&mut s, &base, &text); + assert!(e.contains("saveAs needs a recognized file extension or format options"), "{e}"); + assert!(!dir.join("typo.pfd").exists()); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert!(s.active().unwrap().path.is_none()); + } + logged( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.saveAs(new File({}), new PDFSaveOptions());", quoted(&dir.join("explicit.pfd"))), + ); + assert!(std::fs::read(dir.join("explicit.pfd")).unwrap().starts_with(b"%PDF-")); + let _ = std::fs::remove_dir_all(base); +} + /// The warnings of the save go to the console, and `saveAs` still returns nothing. #[test] fn save_as_logs_the_saves_warnings() { From 4edede500d116d6ce894d77bee26c63bf2384089 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:07:40 -0800 Subject: [PATCH 24/41] Scripts: retracing refuses added artwork; PlacedItem.file resolves linked paths - Retracing a tracing that holds artwork added after the trace throws before the document changes; the retrace limit counts retraces, not mappings. - Image Trace warnings from trace and option changes go to the console. - PlacedItem.file resolves the link against the document's folder. - saveAs picks the format from the name it was given before resolving aliases. - controlBounds includes handles inside blends, envelopes and other containers. --- crates/engine/src/cmd/links.rs | 4 + crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/images.rs | 9 +- crates/engine/src/script/dom/save_open.rs | 2 + crates/engine/src/script/dom/tracing.rs | 34 ++++- crates/engine/src/tests/script_dom.rs | 26 ++++ crates/engine/src/tests/script_dom_images.rs | 30 ++++ crates/engine/src/tests/script_dom_tracing.rs | 135 ++++++++++++++++++ crates/engine/src/tests/script_save_open.rs | 19 +++ 9 files changed, 258 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 65f268f2b0..406a41c971 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -415,6 +415,10 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { Some(f) } +pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option { + locate(link, base).map(|f| f.path) +} + /// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`] /// finds each linked image's and placed document's file from `base` and from no document (as /// output reads them, [`full_linked_images`]), the plate files of their own of images placed from diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6ba1934af1..83b23c6fa2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2388,16 +2388,12 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { } /// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown -/// paths in a group or compound path (a clip group's from its clipping path). `None` for other -/// objects. +/// paths in its children (a clip group's from its clipping path). fn handle_bounds(n: &crate::doc::Node) -> Option { match &n.kind { NodeKind::Path { path, .. } => path.control_bounds(), NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)), - NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { - children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b)) - } - _ => None, + _ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))), } } diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index d3d8c997b4..1fe29e4314 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -358,7 +358,14 @@ fn placed_file(h: &Host, a: &[Data]) -> Answer { return Ok(Data::Null); } } - let path = read_image(h, a, "PlacedItem", |_, _, im| Ok(text(im.link.as_ref().map(|l| l.path.clone()).unwrap_or_default())))?; + let path = read_image(h, a, "PlacedItem", |st, _, im| { + let path = im.link.as_ref().and_then(|link| { + let base = crate::cmd::links::LinkBase::of(st); + crate::cmd::links::located_path(link, base).or_else(|| crate::cmd::fileio::document_path(&link.path, base.doc).ok()) + }); + let path = path.ok_or_else(|| HostError::Error(super::super::files::ACCESS_DENIED.into()))?; + Ok(text(path)) + })?; let Data::String(path) = path else { return Ok(Data::Null) }; if !may_read(h, &path) { return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f8c0cb5d16..26df5be327 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -665,6 +665,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } else if !q.is_empty() { p.insert("options".into(), Value::Object(q)); } + } else if let Some(format) = crate::cmd::fileio::format_for_name(path) { + p.insert("format".into(), json!(format.id)); } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; if given_options.is_none() && extension.as_deref().is_some_and(|e| !e.is_empty()) && crate::cmd::fileio::format_for_name(path).is_none() { diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index e2c3708000..fd1783c6c8 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -34,7 +34,7 @@ //! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`] //! bytes and none of `/`, `\`, `:` or control characters. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -116,6 +116,8 @@ const NOT_IMPLEMENTED: &[&str] = &[ pub(super) struct State { next: RefCell>, sources: RefCell>, + descendants: RefCell>>, + retraces: Cell, } /// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put @@ -150,6 +152,15 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { if let Some(source) = group.children().and_then(|c| c.first()) { h.dom.tracing.sources.borrow_mut().entry((uid, group.id.0)).or_insert(source.id); } + h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| { + let mut ids = HashSet::new(); + group.walk(&mut |n| { + if n.id != group.id { + ids.insert(n.id); + } + }); + ids + }); } pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { @@ -242,6 +253,9 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< let mut before = with_doc(h, item.doc, |_, st| st.selection.clone()); on_doc(h, item.doc.uid, false, |h| { let (_, r) = command_value(h, id, params)?; + for w in r.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{id}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?; let remap = |i: NodeId| if i == item.id { new } else { i }; before.objects = before.objects.into_iter().map(remap).collect(); @@ -265,11 +279,27 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< /// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its /// script objects follow the new one. fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), HostError> { - if h.dom.tracing.next.borrow().len() >= MAX_RETRACES { + if h.dom.tracing.retraces.get() >= MAX_RETRACES { return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); } + read_group(h, item, |_, group| { + remember_source(h, item.doc.uid, group); + let descendants = h.dom.tracing.descendants.borrow(); + let ids = descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?; + let mut added = false; + group.walk(&mut |n| added |= n.id != group.id && !ids.contains(&n.id)); + if added { + return Err(HostError::Error("Cannot retrace a tracing containing added artwork".into())); + } + Ok(()) + })?; params.insert("id".into(), json!(item.id.0)); let new = replace(h, item, "imageTrace.make", &Value::Object(params), "id")?; + read_group(h, Item { id: new, ..item }, |_, group| { + remember_source(h, item.doc.uid, group); + Ok(()) + })?; + h.dom.tracing.retraces.set(h.dom.tracing.retraces.get() + 1); replaced(h, item.doc.uid, item.id, new); Ok(()) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index dd10c77ad6..1d64aebc86 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -148,6 +148,32 @@ fn page_item_control_bounds_take_in_the_handles() { assert!(control[0] <= visible[0] && control[2] >= visible[2] && control[3] <= visible[3], "{visible:?} {control:?}"); } +#[test] +fn control_bounds_include_handles_inside_live_containers() { + for command in ["object.blend.make", "object.envelope.makeWithMesh", "object.repeat.grid", "object.intertwine.make"] { + let (mut s, _, _) = doc(); + let path = s + .execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let other = rect(&mut s, 210.0, 10.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [path, other.0]})).unwrap(); + let params = match command { + "object.blend.make" => json!({"steps": 2}), + "object.envelope.makeWithMesh" | "object.repeat.grid" => json!({"rows": 1, "cols": 1}), + _ => json!({}), + }; + s.execute(command, ¶ms).unwrap(); + let out = log( + &mut s, + "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.selection[0];\ + vc.log(p.controlBounds[1] < p.visibleBounds[1]);", + ); + assert_eq!(out, [json!(true)], "{command}"); + } +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 6628e48bdc..2e7e23044a 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -485,6 +485,36 @@ fn image_file_getter_hides_out_of_scope_link() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn image_file_getter_resolves_document_relative_and_fallback_paths() { + let base = folder("resolved-file"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + for (stored, relative) in [ + ("a.png".to_string(), None), + (base.join("missing/a.png").to_string_lossy().into_owned(), None), + (base.join("missing/old.png").to_string_lossy().into_owned(), Some("a.png".to_string())), + ] { + let mut s = session(); + let image = place(&mut s, &png, true); + s.doc_mut().unwrap().path = Some(base.join("main/page.vectorcraft").to_string_lossy().into_owned()); + if relative.is_some() { + s.doc_mut().unwrap().path = Some(base.join("main/saved/page.vectorcraft").to_string_lossy().into_owned()); + s.doc_mut().unwrap().links_from = Some(base.join("main/original.vectorcraft").to_string_lossy().into_owned()); + } + s.edit("Set linked path", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(image).unwrap().kind else { panic!("not an image") }; + im.link.as_mut().unwrap().path = stored.clone(); + im.link.as_mut().unwrap().relative = relative.clone(); + Ok(()) + }) + .unwrap(); + let out = log(&mut s, &base, &format!("vc.log(app.activeDocument.placedItems[0].file.fsName === new File('{}').fsName);", js_path(&png))); + assert_eq!(out, [json!(true)], "{stored}"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() { let base = folder("hidedoc"); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 523c70e5b2..aa43c63696 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -292,6 +292,141 @@ fn tracing_replacements_refuse_protected_artwork() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn retrace_refuses_added_artwork_before_changing_the_document() { + let base = folder("retrace-added-artwork"); + for artwork in [ + "r.move(p, ElementPlacement.PLACEATEND);", + "r.duplicate(p, ElementPlacement.PLACEATEND);", + "d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ] { + for action in ["o.threshold = 90;", "o.loadFromPreset('Silhouettes');"] { + let (mut s, _) = session(&base, false); + s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap(); + let setup = format!("var d = app.activeDocument, r = d.rasterItems[0], p = d.rasterItems[1].trace(); {artwork}"); + let mut expected = Session::new(); + expected.docs = s.docs.clone(); + expected.active = s.active; + log(&mut expected, &base, &setup); + let before = vectorcraft_format::save(&expected.active().unwrap().doc, false); + let selection = expected.active().unwrap().selection.clone(); + let steps = undo_steps(&expected); + let out = log( + &mut s, + &base, + &format!( + "{setup} var items = app.activeDocument.pageItems;\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + var o = p.tracing.tracingOptions, m = '';\ + try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);" + ), + ); + assert_eq!(out, [json!("Cannot retrace a tracing containing added artwork")], "{artwork} {action}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(s.active().unwrap().selection, selection); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn copied_traces_remap_child_records_without_accepting_added_artwork() { + let base = folder("retrace-copied-artwork"); + for (added, retraced) in [(false, false), (true, false), (false, true), (true, true)] { + let (mut s, _) = session(&base, false); + let retrace = if retraced { "o.threshold = 100;" } else { "" }; + let artwork = if added { "d.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" }; + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[0].trace(), copy = p.duplicate(), o = copy.tracing.tracingOptions;\ + {retrace} {artwork}\ + var m = ''; try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(copy.isTracing); vc.log(o.threshold);" + ), + ); + let message = if added { "Cannot retrace a tracing containing added artwork" } else { "" }; + assert_eq!(out[..2], [json!(message), json!(true)], "added: {added}, retraced: {retraced}"); + if !added { + assert_eq!(out[2], json!(90)); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn engine_trace_can_be_retraced_by_a_script() { + let base = folder("retrace-engine-artwork"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let group = NodeId(made["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.pageItems[0], o = p.tracing.tracingOptions;\ + o.threshold = 90; vc.log(o.threshold); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(90), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_ne!(groups[0], group); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + assert_eq!(undo_steps(&s), steps + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_limit_counts_retraces_of_an_undone_group() { + let base = folder("retrace-limit-undo"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions, count = 0, m = '';\ + try { for (; count < 10001; count++) { o.threshold = 90; app.undo(); } } catch (e) { m = e.message; }\ + vc.log(count); vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(10000), json!("a run traces a tracing again at most 10000 times"), json!(true)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_and_option_changes_log_command_warnings() { + let base = folder("trace-warnings"); + let (mut s, _) = session(&base, false); + let png = base.join("main/wide.png"); + std::fs::write(&png, vectorcraft_trace::Raster::from_fn(1501, 2, |_, _| [0, 0, 0, 255]).encode_png()).unwrap(); + let placed = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = placed["ids"][0].as_u64().unwrap(); + let made = s.execute("imageTrace.make", &json!({"id": image})).unwrap(); + let warnings = made["warnings"].as_array().unwrap().clone(); + assert!(!warnings.is_empty()); + s.execute("imageTrace.release", &json!({"id": made["id"]})).unwrap(); + let report = run(&mut s, &base, "var p = app.activeDocument.rasterItems[0].trace(); p.tracing.tracingOptions.threshold = 90;").unwrap(); + let lines = report["console"]["lines"].as_array().unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(lines, &expected.iter().chain(&expected).cloned().collect::>()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn option_changes_log_why_no_paths_were_traced() { + let base = folder("trace-no-paths-warning"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0, "params": {"keepColors": ["#ff00ff"]}})).unwrap(); + assert_eq!(made["paths"], json!(0)); + let warnings = made["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nothing was traced"))); + let report = run(&mut s, &base, "app.activeDocument.pageItems[0].tracing.tracingOptions.threshold = 90;").unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(report["console"]["lines"], json!(expected)); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn tracing_parent_keeps_plugin_identity_after_retracing() { let base = folder("parent-identity"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index bee1b78188..39647ff587 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -46,6 +46,25 @@ fn data_folder(s: &mut Session, base: &Path) -> PathBuf { PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) } +#[cfg(unix)] +#[test] +fn save_as_uses_the_supplied_alias_extension() { + let base = folder("save-alias-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let target = dir.join("output.vectorcraft"); + let alias = dir.join("output.svg"); + std::fs::write(&target, "before").unwrap(); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias))); + let svg = std::fs::read_to_string(&target).unwrap(); + assert!(svg.contains(" String { serde_json::to_string(&p.to_string_lossy()).unwrap() } From affd7a8853c3fcd180327b192ab62b1d539861c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:09:37 -0800 Subject: [PATCH 25/41] Scripts: tracing keeps its source image; image edits roll back on failure - Moving a tracing's source image out of its tracing throws instead of breaking the tracing. - PlacedItem.file places and checks the linked image under one savepoint, so a failed check leaves no linked image behind. - Retracing restores the selection under the same savepoint as the trace. - matrix assignment compares the linear part exactly, so a small change to the scale or rotation is applied. - ExportOptionsPNG24 and ExportOptionsJPEG accept white, their default matteColor; another color is still an error. - File objects made without charging their path no longer reserve it. - Tests: the RTL artboard column check reads the direction from the layout, js_path escapes line breaks and quotes, rejected tracing options leave the saved document unchanged, and the Image Trace panel targets a second image selected with its tracing's source. - docs/mcp.md: the scale and clipping options apply to PNG24 and JPEG, and the source image move error is documented. --- crates/engine/src/script/dom.rs | 7 ++-- crates/engine/src/script/dom/images.rs | 36 +++++++++---------- crates/engine/src/script/dom/save_open.rs | 11 ++++-- crates/engine/src/script/dom/tracing.rs | 3 +- crates/engine/src/tests/script_dom.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 9 ++++- crates/engine/src/tests/script_dom_tracing.rs | 26 +++++++++++++- crates/engine/src/tests/script_save_open.rs | 33 +++++++++++++++++ crates/js/src/file_classes.rs | 6 ++-- .../ui-egui/src/panels/image_trace/tests.rs | 8 +++++ docs/mcp.md | 6 ++-- 11 files changed, 114 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 83b23c6fa2..8f4994baa8 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2635,8 +2635,11 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); // A clip group's first child is its clipping path, and an Image Trace object's its source // image: both stay first, and the source image moved within its own tracing stays where it is. - if crate::cmd::is_trace_source(d, id) && d.parent_of(id) == Some(to.parent) { - return Ok(0); + if crate::cmd::is_trace_source(d, id) { + if d.parent_of(id) == Some(to.parent) { + return Ok(0); + } + return Err(HostError::Error("a tracing's source image cannot leave its tracing".into())); } let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0; let at = match (to.how, to.beside) { diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 1fe29e4314..81e11ec177 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -391,25 +391,20 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { let path = image_path(h, arg(a, 1), "PlacedItem.file")?; // The ids are read from the command's own result, where every id is exact (a script number // holds integers exactly only up to 2^53). - let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; - let ids: Vec = placed["ids"].as_array().map(|ids| ids.iter().filter_map(serde_json::Value::as_u64).collect()).unwrap_or_default(); - let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); - let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); - let linked = |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); - match id.filter(|id| linked(*id)) { - Some(id) => { - if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) { - p.bound = Some(id); - } - Ok(Data::Undefined) - } - None => { - if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids})))?; - } - Err(HostError::Error(NOT_AN_IMAGE.into())) - } + // The placement and its check run under one savepoint, so an error after the place leaves + // no linked image behind. + let id = super::atomically(h, |h| { + let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; + let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); + let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); + let linked = + |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); + id.filter(|id| linked(*id)).ok_or_else(|| HostError::Error(NOT_AN_IMAGE.into())) + })?; + if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) { + p.bound = Some(id); } + Ok(Data::Undefined) } /// `relink(file)`: `links.relink` of the item to the image in `file`. @@ -501,7 +496,10 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { return Err(HostError::Range("the matrix puts the image outside the canvas".into())); } let old = im.xf; - if old.as_coeffs().iter().zip(target.as_coeffs()).all(|(o, t)| (o - t).abs() <= 1e-9) { + // The coordinate frame only changes the signs of the linear part, so any change to it + // counts; the offsets compare in points, which absorbs the rounding of the frame. + let same = old.as_coeffs().iter().zip(target.as_coeffs()).enumerate().all(|(k, (o, t))| if k < 4 { *o == t } else { (o - t).abs() <= 1e-9 }); + if same { return Ok(None); } if !area_of(old) { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 26df5be327..7fdff401de 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -169,6 +169,8 @@ enum Default { /// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for /// `DownsampleMethod.NODOWNSAMPLE`). Member(&'static str, &'static str), + /// White as an `RGBColor`: red, green and blue each 255. + White, /// The help page gives no default: any value throws. Unset, } @@ -180,6 +182,11 @@ impl Default { (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, (Default::Text(a), Data::String(b)) => a == b, (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + (Default::White, Data::Object(items)) => { + let get = |k: &str| items.iter().find(|(name, _)| name == k).map(|(_, v)| v); + matches!(get("typename"), Some(Data::String(t)) if t == "RGBColor") + && ["red", "green", "blue"].iter().all(|k| matches!(get(k), Some(Data::Number(n)) if *n == 255.0)) + } _ => false, } } @@ -457,7 +464,7 @@ fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::R raster_map("ExportOptionsPNG24", name, d, p) } -const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn png24_starts() -> Vec<(&'static str, Data)> { vec![ @@ -485,7 +492,7 @@ fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Re } const JPEG_KEPT: &[(&str, Default)] = - &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn jpeg_starts() -> Vec<(&'static str, Data)> { vec![ diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index fd1783c6c8..1f5e0b7d30 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -294,7 +294,8 @@ fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), H Ok(()) })?; params.insert("id".into(), json!(item.id.0)); - let new = replace(h, item, "imageTrace.make", &Value::Object(params), "id")?; + // One savepoint covers the trace and the selection's restore, so a failed restore undoes the trace. + let new = super::atomically(h, |h| replace(h, item, "imageTrace.make", &Value::Object(params), "id"))?; read_group(h, Item { id: new, ..item }, |_, group| { remember_source(h, item.doc.uid, group); Ok(()) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 1d64aebc86..a61cc4139a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1024,6 +1024,7 @@ fn a_grid_by_column_takes_the_number_of_rows() { assert!((second.x0 - first.x0).abs() < 1e-9 && second.y0 > first.y0, "{layout} {count}: {first:?} {second:?}"); let rightward = next.x0 > first.x0; assert_eq!(rightward, layout == "GridByCol", "{layout} {count}: {first:?} {next:?}"); + assert!(rightward || next.x0 < first.x0, "{layout} {count}: the next column moved: {first:?} {next:?}"); } } } diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 2e7e23044a..4103ab0bff 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -24,8 +24,11 @@ fn gray_png(w: u32, h: u32) -> Vec { craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() } +/// The path as the inside of a single-quoted script string: JSON escapes backslashes, quotes, +/// line breaks and control characters, and the apostrophe is escaped as well. fn js_path(p: &Path) -> String { - plain_path(&p.to_string_lossy()).replace('\\', "\\\\").replace('\'', "\\'") + let quoted = Value::String(plain_path(&p.to_string_lossy())).to_string(); + quoted[1..quoted.len() - 1].replace('\'', "\\'") } fn plain_path(path: &str) -> String { @@ -39,6 +42,7 @@ fn fixture_paths_strip_verbatim_prefixes_on_every_platform() { assert_eq!(plain_path(&drive), r"C:\x\a.png"); assert_eq!(plain_path(&unc), r"\\server\share\a.png"); assert_eq!(js_path(Path::new(&drive)), r"C:\\x\\a.png"); + assert_eq!(js_path(Path::new("a\nb'c\"d")), r#"a\nb\'c\"d"#); assert_eq!(plain_path("/tmp/a.png"), "/tmp/a.png"); } @@ -438,6 +442,9 @@ fn image_matrix_assignment_transforms_the_image() { assert_eq!(undo_steps(&s), before + 1); log(&mut s, &base, "var r = app.activeDocument.rasterItems[0]; r.matrix = r.matrix;"); assert_eq!(undo_steps(&s), before + 1); + // A change smaller than 1e-9 to the linear part still counts. + log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueB = m.mValueB * (1 + 1e-10); r.matrix = m;"); + assert_eq!(undo_steps(&s), before + 2); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index aa43c63696..4cb93789df 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -587,6 +587,7 @@ fn trace_invalid_option_is_atomic() { let (mut s, _) = session(&base, false); log(&mut s, &base, "app.activeDocument.rasterItems[0].trace();"); let before = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); let cases = [ ("o.threshold = 'x'", "TypeError"), ("o.threshold = 256", "TracingOptions.threshold is out of range"), @@ -630,7 +631,8 @@ fn trace_invalid_option_is_atomic() { ); let m = out[0].as_str().unwrap_or_default().to_string(); let now = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); - if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before { + let unchanged = vectorcraft_format::save(&s.active().unwrap().doc, false) == saved; + if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before || !unchanged { wrong.push(format!("{code}: {m}")); } } @@ -877,6 +879,28 @@ fn reordering_inside_a_tracing_keeps_the_source_first() { let _ = std::fs::remove_dir_all(base); } +/// A tracing's source image cannot be moved out of its tracing, and the refused move leaves the +/// document as it was. +#[test] +fn the_source_image_cannot_leave_its_tracing() { + let base = folder("source-leaves"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;"); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.pageItems[0], m = 'none';\ + try { p.tracing.sourceArt.move(p, ElementPlacement.PLACEBEFORE); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_source_art_is_not_listed_with_the_images() { let base = folder("lists"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 39647ff587..ad7a95af9d 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -229,6 +229,39 @@ fn omitted_options_are_a_new_options_objects_defaults() { let _ = std::fs::remove_dir_all(base); } +/// White, the default `matteColor` of `ExportOptionsPNG24` and `ExportOptionsJPEG`, is accepted, and +/// another color is refused. +#[test] +fn a_white_matte_color_is_the_default() { + let base = folder("matte"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100), c = new RGBColor();\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); c.red = 255; c.green = 255; c.blue = 255;\n\ + var p = new ExportOptionsPNG24(); p.matteColor = c; d.exportFile(new File(dir + '/p'), ExportType.PNG24, p);\n\ + var j = new ExportOptionsJPEG(); j.matteColor = c; d.exportFile(new File(dir + '/j'), ExportType.JPEG, j);" + ), + ); + assert!(dir.join("p.png").exists() && dir.join("j.jpg").exists()); + for (class, kind) in [("ExportOptionsPNG24", "PNG24"), ("ExportOptionsJPEG", "JPEG")] { + let e = failure( + &mut s, + &base, + &format!( + "Folder.userData; var c = new RGBColor(); c.red = 255; c.green = 0; c.blue = 255; var o = new {class}(); o.matteColor = c;\ + app.activeDocument.exportFile(new File({d} + '/x'), ExportType.{kind}, o);" + ), + ); + assert!(e.contains("matteColor"), "{class}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A raster export at 100% has one pixel per point, whatever the document's raster effects /// resolution. #[test] diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 0488bb4596..ca157e4224 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -210,11 +210,9 @@ fn new_instance(i: &mut Interp, proto: ObjId, fs: Value, charge_path: bool) -> J let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) }; let line_feed = host_value(i, "lineFeed")?; i.rooted(&[fs, line_feed.clone()], |i| { - let path_bytes = string_bytes(path.len()); + let path_bytes = if charge_path { string_bytes(path.len()) } else { 0 }; i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + path_bytes)?; - if charge_path { - i.heap.bytes = i.heap.bytes.saturating_add(path_bytes); - } + i.heap.bytes = i.heap.bytes.saturating_add(path_bytes); let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto))); i.rooted(&[Value::Object(o)], |i| { set_slot(i, o, ERROR, Value::str(""))?; diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 8efe974351..860bc84938 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1395,6 +1395,8 @@ fn lookup_fixture() -> (VectorcraftApp, std::collections::HashMap<&'static str, ids.insert("other", doc.insert(Some(second), usize::MAX, other).unwrap()); let other_trace = doc.reid(&trace); ids.insert("other trace", doc.insert(Some(second), 0, other_trace).unwrap()); + let added = doc.reid(&image); + ids.insert("trace added", doc.insert(Some(trace.id), usize::MAX, added).unwrap()); st.revision += 1; (app, ids) } @@ -1454,6 +1456,12 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { } assert!(objects.len() >= 8, "the cases reach many different objects: {objects:?}"); + // The source image with a second image of the same tracing: the panel targets the second image. + for sel in [[ids["trace image"], ids["trace added"]], [ids["trace added"], ids["trace image"]]] { + select_as_is(&mut app, &sel); + assert_eq!(target(&mut app).object.map(|o| o.1), Some(ids["trace added"]), "{sel:?}"); + } + // An edit and Undo. app.run("select.set", json!({"ids": [ids["rect"].0, ids["trace"].0]})).unwrap(); let before = target(&mut app); diff --git a/docs/mcp.md b/docs/mcp.md index 95d0596d7a..737a754299 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3015,7 +3015,9 @@ through `$`: `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` - directly below it. An object of another document throws `Cross-document placement is not available`, and when + directly below it. Moving a tracing's visible, unlocked source image (`TracingObject.sourceArt`) out of its + tracing throws `a tracing's source image cannot leave its tracing` and changes nothing; a hidden source image (the + default) throws `Cannot move`. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an @@ -3114,7 +3116,7 @@ through `$`: and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to - 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and + 776.19; 100 writes one pixel per point whatever the raster effects resolution) for PNG24 and JPEG, `matteColor` (PNG24 and JPEG; only white, an `RGBColor` of 255, 255, 255, is accepted, and another color is an error), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with From 164c3c53a67d7b7dedb8770430fccabb62ddf31b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 08:59:11 -0800 Subject: [PATCH 26/41] Scripts: tracing counts leave out only the trace's own seam fills pathCount, anchorCount and usedColorCount skipped every group anywhere in the tracing that looked like seam fills, so a group named "Seam Fills" moved into a tracing was not counted. The counts now leave out a clip group directly in the tracing that is seam fills, or the lowest item above the source image for traces made before seam fills were clipped, as retracing does. An Image Trace object inside the tracing leaves out its own seam fills the same way. --- crates/engine/src/script/dom/tracing.rs | 24 ++++++++++++-- crates/engine/src/tests/script_dom_tracing.rs | 31 +++++++++++++++++-- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index 1f5e0b7d30..df64d03d73 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -375,16 +375,24 @@ fn anchors_of(n: &Node) -> u64 { } /// The traced paths of the Image Trace object `g`, their anchor points and paints: every path -/// and compound path in it but its source image, the seam fills and clipping paths. +/// and compound path in it but its source image, the seam fills and clipping paths. The seam fills +/// are a clip group directly in the tracing that [`crate::cmd::is_seam_fills`] accepts, or, for a +/// trace made before seam fills were clipped, the lowest item above the source image when it +/// accepts that. A group nested deeper, or an unclipped group higher up, is counted. An Image +/// Trace object inside `g` leaves out its own seam fills the same way. fn counts(g: &Node) -> Counts { let mut c = Counts::default(); let mut paints = HashSet::new(); let mut todo: Vec<&Arc> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default(); + let mut seams = seam_fills_of(g); while let Some(n) = todo.pop() { c.visited += 1; - if crate::cmd::is_seam_fills(n) { + if seams.contains(&n.id) { continue; } + if crate::cmd::is_trace_group(n) { + seams.extend(seam_fills_of(n)); + } match &n.kind { NodeKind::Path { clipping: true, .. } => {} NodeKind::Path { .. } | NodeKind::Compound { .. } => { @@ -405,6 +413,18 @@ fn counts(g: &Node) -> Counts { c } +/// The seam fills of the Image Trace object `g` ([`counts`]). +fn seam_fills_of(g: &Node) -> HashSet { + g.children() + .into_iter() + .flatten() + .skip(1) + .enumerate() + .filter(|(i, n)| (*i == 0 || matches!(n.kind, NodeKind::Group { clip: true, .. })) && crate::cmd::is_seam_fills(n)) + .map(|(_, n)| n.id) + .collect() +} + /// Reads the counts of the tracing `this` names with `f`. fn count(h: &Host, a: &[Data], f: fn(&Counts) -> u64) -> Answer { let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 4cb93789df..6e23507254 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -111,6 +111,30 @@ fn raster_trace_returns_plugin_with_counts() { let _ = std::fs::remove_dir_all(base); } +/// A group moved into a tracing above its paths counts even when its name and contents look like +/// seam fills: only the tracing's lowest item can be its seam fills. +#[test] +fn added_group_named_as_seam_fills_is_counted() { + let base = folder("seam-name"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, n = t.pathCount, a = t.anchorCount;\ + var r = d.pathItems.rectangle(0, 0, 10, 10); r.filled = true; r.stroked = false; d.selection = [r]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Seam Fills'; vc.log(g.typename); g.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);\ + var q = d.pathItems.rectangle(0, 0, 10, 10); q.move(p, ElementPlacement.PLACEATEND); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);", + ); + assert_eq!(out, [json!("GroupItem"), json!(1), json!(4), json!(2), json!(8)]); + let d = &s.active().unwrap().doc; + let kids = d.children(Some(traces(&s)[0])).unwrap(); + assert!( + kids.iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. }) && crate::cmd::is_seam_fills(n)), + "the trace keeps its own seam fills, below the path placed at the end" + ); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_image_resolution_is_one_number_or_none() { let base = folder("resolution"); @@ -815,9 +839,12 @@ fn trace_of_another_image_inside_a_tracing() { &mut s, &base, "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.move(p, ElementPlacement.PLACEATBEGINNING);\ - var q = r.trace(); vc.log(q.typename); vc.log(q.tracing.sourceArt === r); vc.log(p.tracing.pathCount > 0);", + var q = r.trace(); vc.log(q.typename); vc.log(q.tracing.sourceArt === r); vc.log(p.tracing.pathCount > 0);\ + vc.log(p.tracing.pathCount === 2 * q.tracing.pathCount); vc.log(p.tracing.anchorCount === 2 * q.tracing.anchorCount);", ); - assert_eq!(out, [json!("PluginItem"), json!(true), json!(true)]); + // The two traces are of the same image with the same settings: the outer counts take in the + // inner trace's paths without its seam fills. + assert_eq!(out, [json!("PluginItem"), json!(true), json!(true), json!(true), json!(true)]); let groups = traces(&s); assert_eq!(groups.len(), 2); let d = &s.active().unwrap().doc; From c675759fa323d48e9e61621b79c542bf755edf31 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:51:53 -0800 Subject: [PATCH 27/41] Scripts: a stop asked for before an Image Trace commits leaves the document unchanged trace_make checked the script's stop request only while it traced, so a stop asked for after the last check, or while a trace handed in for the same inputs was applied, still committed the Image Trace object. It now checks the stop request once more right before the edit and returns EngineError::Cancelled. --- crates/engine/src/cmd/buildcmds/trace.rs | 5 +++++ crates/engine/src/tests/script_dom_tracing.rs | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 975a8b03c1..5d27feacd9 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1112,6 +1112,11 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Date: Mon, 30 Nov 2026 17:54:54 -0800 Subject: [PATCH 28/41] Scripts: retrace refuses a tracing that holds artwork its trace did not make imageTrace.make records the ids of the objects it made in the tracing's trace settings as `made`, and copying the tracing records the ids of their copies. Tracing again through the scripting API throws, with nothing changed, when the tracing holds any other object, whether it was added in this run, an earlier run or by a command. A tracing saved without `made` is checked only for objects added in the same run, as before. --- crates/doc/src/document_guides.rs | 10 ++ crates/doc/src/lib.rs | 2 +- crates/doc/src/tests.rs | 22 +++ crates/doc/src/trace.rs | 105 ++++++++++++++- crates/engine/src/cmd/buildcmds/trace.rs | 4 + crates/engine/src/script/dom/tracing.rs | 15 ++- crates/engine/src/tests/script_dom_tracing.rs | 126 ++++++++++++++++++ docs/mcp.md | 6 +- 8 files changed, 284 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 7c96cc6104..77b9a4c747 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -757,6 +757,16 @@ impl Document { { on_path.rename(&renamed); } + // An Image Trace object names the objects its trace made by id: the copy names the copies of + // those objects, and no other object. + if let Some(made) = node.trace_made() { + let mut old = vec![]; + node.walk(&mut |d| old.push(d.id)); + let mut new = vec![]; + n.walk(&mut |d| new.push(d.id)); + let copies = old.into_iter().zip(new).skip(1).filter(|(o, _)| made.contains(*o)).map(|(_, c)| c); + n.set_trace_made(&crate::TraceMade::of(copies)); + } n } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6a331c6b77..cb8f077dae 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -142,7 +142,7 @@ pub use text::{ TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, }; pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet}; -pub use trace::TraceView; +pub use trace::{TraceMade, TraceView}; pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables}; pub use vectorcraft_color as color; pub use vectorcraft_geom as geom; diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a39260ee91..c83f43fe56 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -822,6 +822,28 @@ fn reid_gives_fresh_ids() { assert!(!ids.contains(&a) && !ids.contains(&b)); } +/// A copy of an Image Trace object records the copies of the objects its trace made, nested ones +/// included, and not the copy of an object added to it later. +#[test] +fn reid_remaps_what_a_tracing_records_it_made() { + let (mut d, a, b) = doc_with_rects(); + let na = (*d.remove(a).unwrap()).clone(); + let nb = (*d.remove(b).unwrap()).clone(); + let inner = d.alloc_id(); + let inner = Node::group(inner, vec![Arc::new(na)]); + let mut tracing = Node::group(d.alloc_id(), vec![Arc::new(inner.clone()), Arc::new(nb)]); + tracing.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"}))); + tracing.set_trace_made(&crate::TraceMade::of([inner.id, a])); + let copy = d.reid(&tracing); + let made = copy.trace_made().unwrap(); + let ch = copy.children().unwrap(); + let (inner_copy, added_copy) = (&ch[0], &ch[1]); + let a_copy = inner_copy.children().unwrap()[0].id; + assert!(made.contains(inner_copy.id) && made.contains(a_copy)); + assert!(!made.contains(added_copy.id) && !made.contains(inner.id) && !made.contains(a) && !made.contains(b)); + assert_eq!(made, crate::TraceMade::of([inner_copy.id, a_copy])); +} + /// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from /// another document with the same id does not. #[test] diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index a2d17cc990..69bc50b5d0 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -1,11 +1,64 @@ //! Image Trace objects' View: how a live trace draws on screen. //! -//! An Image Trace object is a group whose `trace` holds `{preset, params, view}` (see +//! An Image Trace object is a group whose `trace` holds `{preset, params, view, made}` (see //! `imageTrace.make`). The view is a viewing aid only: exports, printing and Expand always use the -//! tracing result, whatever it is set to. +//! tracing result, whatever it is set to. `made` names the objects the trace made ([`TraceMade`]). +use crate::NodeId; use crate::node::Node; +/// The key of an Image Trace object's `trace` settings that names the objects its trace made. +pub const TRACE_MADE: &str = "made"; + +/// The objects the trace of an Image Trace object made, by id: the ranges `[first, last]` of their +/// ids, ascending and apart. A trace gives out its ids one after the other, so a trace of any size +/// is a few ranges. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TraceMade(Vec<(u64, u64)>); + +impl TraceMade { + /// The objects `ids` name. + pub fn of(ids: impl IntoIterator) -> Self { + let mut ids: Vec = ids.into_iter().map(|i| i.0).collect(); + ids.sort_unstable(); + ids.dedup(); + let mut ranges: Vec<(u64, u64)> = vec![]; + for id in ids { + match ranges.last_mut() { + Some((_, last)) if last.checked_add(1) == Some(id) => *last = id, + _ => ranges.push((id, id)), + } + } + Self(ranges) + } + + /// Whether the trace made the object `id`. + pub fn contains(&self, id: NodeId) -> bool { + let i = self.0.partition_point(|(_, last)| *last < id.0); + self.0.get(i).is_some_and(|(first, _)| *first <= id.0) + } + + /// The ranges as the `trace` settings save them: `[[first, last], ...]`. + pub fn to_json(&self) -> serde_json::Value { + serde_json::Value::Array(self.0.iter().map(|(a, b)| serde_json::json!([a, b])).collect()) + } + + /// The ranges `v` saves, or `None` when it is not a list of `[first, last]` pairs of whole + /// numbers, ascending and apart. + pub fn from_json(v: &serde_json::Value) -> Option { + let mut ranges: Vec<(u64, u64)> = vec![]; + for r in v.as_array()? { + let [a, b] = r.as_array()?.as_slice() else { return None }; + let (a, b) = (a.as_u64()?, b.as_u64()?); + if a > b || ranges.last().is_some_and(|(_, last)| *last >= a) { + return None; + } + ranges.push((a, b)); + } + Some(Self(ranges)) + } +} + /// Image Trace › View. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TraceView { @@ -90,6 +143,21 @@ impl Node { pub fn trace_split(&self) -> f64 { self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of) } + + /// The objects the trace of this Image Trace object made ([`TRACE_MADE`]), or `None` when its + /// `trace` settings name none, as in a tracing saved before they did, or name them in any other + /// form than [`TraceMade::to_json`]'s. + pub fn trace_made(&self) -> Option { + self.extras().trace.as_deref().and_then(|t| t.get(TRACE_MADE)).and_then(TraceMade::from_json) + } + + /// Records `made` as the objects the trace of this Image Trace object made, when its `trace` + /// settings are an object. + pub fn set_trace_made(&mut self, made: &TraceMade) { + if let Some(t) = self.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(serde_json::Value::as_object_mut) { + t.insert(TRACE_MADE.into(), made.to_json()); + } + } } #[cfg(test)] @@ -111,6 +179,39 @@ mod tests { assert_eq!(g.trace_view(), TraceView::Result); } + #[test] + fn trace_made_keeps_ranges_and_reads_only_well_formed_ones() { + let ids = [7, 3, 4, 5, 9, 3, u64::MAX].map(crate::NodeId); + let made = TraceMade::of(ids); + assert_eq!(made.to_json(), serde_json::json!([[3, 5], [7, 7], [9, 9], [u64::MAX, u64::MAX]])); + for id in 0..12 { + assert_eq!(made.contains(crate::NodeId(id)), ids.contains(&crate::NodeId(id)), "{id}"); + } + assert!(made.contains(crate::NodeId(u64::MAX))); + assert_eq!(TraceMade::from_json(&made.to_json()), Some(made.clone())); + assert_eq!(TraceMade::from_json(&serde_json::json!([])), Some(TraceMade::default())); + for bad in [ + serde_json::json!({}), + serde_json::json!([[5, 3]]), + serde_json::json!([[1, 4], [4, 6]]), + serde_json::json!([[6, 7], [1, 2]]), + serde_json::json!([[1]]), + serde_json::json!([[1, 2, 3]]), + serde_json::json!([[-1, 2]]), + serde_json::json!([[1.5, 2]]), + serde_json::json!(["1", "2"]), + ] { + assert_eq!(TraceMade::from_json(&bad), None, "{bad}"); + } + let mut g = Node::group(crate::NodeId(1), vec![]); + g.set_trace_made(&made); + assert_eq!(g.trace_made(), None, "a group with no trace settings records nothing"); + g.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"}))); + assert_eq!(g.trace_made(), None); + g.set_trace_made(&made); + assert_eq!(g.trace_made(), Some(made)); + } + #[test] fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() { let mut g = Node::group(crate::NodeId(1), vec![]); diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 5d27feacd9..ff99c44bb2 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1234,6 +1234,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result) -> Result<(), H remember_source(h, item.doc.uid, group); let descendants = h.dom.tracing.descendants.borrow(); let ids = descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?; + // The objects the trace made, as the tracing records them; a tracing saved without that + // record is checked against the objects it held when this run first saw it. + let made = group.trace_made(); let mut added = false; - group.walk(&mut |n| added |= n.id != group.id && !ids.contains(&n.id)); + group.walk(&mut |n| { + added |= n.id != group.id && made.as_ref().map_or(!ids.contains(&n.id), |m| !m.contains(n.id)); + }); if added { - return Err(HostError::Error("Cannot retrace a tracing containing added artwork".into())); + return Err(HostError::Error(ADDED_ARTWORK.into())); } Ok(()) })?; diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index d9aebe728f..6b891aadc0 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -380,6 +380,132 @@ fn copied_traces_remap_child_records_without_accepting_added_artwork() { let _ = std::fs::remove_dir_all(base); } +/// The objects in the object `id` of the active document, without it, in order. +fn members(s: &Session, id: NodeId) -> Vec { + let mut out = vec![]; + if let Some(n) = s.active().unwrap().doc.node(id) { + n.walk(&mut |m| { + if m.id != id { + out.push(m.id); + } + }); + } + out +} + +/// A new session with the active document of `s`, saved and opened again. +fn reopened(s: &Session) -> Session { + let bytes = vectorcraft_format::save(&s.active().unwrap().doc, false); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "traced.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap(); + o +} + +/// Traces the Image Trace object `index` of the active document's page items again with a +/// threshold of 90, and logs the error, or `""`. +fn retrace_item(index: usize) -> String { + format!( + "(function () {{ var items = app.activeDocument.pageItems, found = [];\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') found.push(items[i]);\ + var o = found[{index}].tracing.tracingOptions, m = '';\ + try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }} vc.log(m); }})();" + ) +} + +const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork"; + +#[test] +fn retrace_refuses_artwork_added_before_the_run() { + let base = folder("retrace-earlier-artwork"); + for by_command in [false, true] { + for reopen in [false, true] { + let (mut s, image) = session(&base, false); + let trace = if by_command { + s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + "var p = app.activeDocument.pageItems[0];" + } else { + "var p = app.activeDocument.rasterItems[0].trace();" + }; + log(&mut s, &base, &format!("{trace} app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);")); + let mut s = if reopen { reopened(&s) } else { s }; + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log(&mut s, &base, &retrace_item(0)); + assert_eq!(out, [json!(ADDED_ARTWORK)], "by command: {by_command}, reopened: {reopen}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "by command: {by_command}, reopened: {reopen}"); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_takes_a_tracing_whose_traced_objects_were_edited() { + let base = folder("retrace-edited-artwork"); + for reopen in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let made = s.active().unwrap().doc.node(group).and_then(|g| g.trace_made()).expect("the trace records what it made"); + let held = members(&s, group); + assert!(held.len() > 1 && held.iter().all(|m| made.contains(*m)), "{held:?} {made:?}"); + assert!(!made.contains(group)); + let path = held[held.len() - 1]; + s.execute("object.move", &json!({"ids": [path.0], "dx": 5, "dy": 0})).unwrap(); + let mut s = if reopen { reopened(&s) } else { s }; + let out = log(&mut s, &base, &format!("{} vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.threshold);", retrace_item(0))); + assert_eq!(out, [json!(""), json!(90)], "reopened: {reopen}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_copied_tracing_retraces_in_a_later_run() { + let base = folder("retrace-copy-later"); + for added in [false, true] { + for reopen in [false, true] { + let (mut s, _) = session(&base, false); + let artwork = if added { "app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" }; + log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(), copy = p.duplicate(); {artwork}")); + let groups = traces(&s); + assert_eq!(groups.len(), 2); + let records: Vec<_> = groups.iter().map(|g| s.active().unwrap().doc.node(*g).and_then(|n| n.trace_made()).unwrap()).collect(); + for (k, g) in groups.iter().enumerate() { + assert!(members(&s, *g).iter().all(|m| !records[1 - k].contains(*m)), "a tracing records none of the other's objects"); + } + let mut s = if reopen { reopened(&s) } else { s }; + let out = log(&mut s, &base, &format!("{} {}", retrace_item(0), retrace_item(1))); + let message = if added { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message), json!("")], "added: {added}, reopened: {reopen}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() { + let base = folder("retrace-legacy"); + for same_run in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let add = "var r = app.activeDocument.pathItems.rectangle(20, 20, 10, 10); r.name = 'added'; r.move(app.activeDocument.pageItems[1], ElementPlacement.PLACEATEND);"; + let out = if same_run { + log(&mut s, &base, &format!("{add} {}", retrace_item(0))) + } else { + log(&mut s, &base, add); + log(&mut s, &base, &retrace_item(0)) + }; + let message = if same_run { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "same run: {same_run}"); + let mut named = false; + s.active().unwrap().doc.walk(|n| named |= n.name.as_deref() == Some("added")); + assert_eq!(named, same_run, "tracing again drops what was added, as before"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn engine_trace_can_be_retraced_by_a_script() { let base = folder("retrace-engine-artwork"); diff --git a/docs/mcp.md b/docs/mcp.md index e1cee3b3ae..4e37a4d5de 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3243,7 +3243,11 @@ through `$`: across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` - and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `threshold` takes a whole + and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws + `Cannot retrace a tracing containing added artwork`, with nothing changed, when the tracing holds an object its trace + did not make, whether this run, an earlier run or a command added it. `imageTrace.make` records the objects it made in + the tracing's `trace` settings as `made`, ranges of ids `[[first, last], ...]`, and a copy of the tracing records + their copies. A tracing saved without `made` is checked only for objects added in the same run. `threshold` takes a whole number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`, `"Full Tone"` or `"Document Library"`; `viewRaster` and `viewVector` take only the pairs that match an Image Trace From ac03057d2f6d743abd919a1a4b1d3998ecffb5a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 19:00:58 -0800 Subject: [PATCH 29/41] Scripts: retrace keeps the tracing's appearance and its script object Tracing an Image Trace object again built a new group with default object settings, so a tracing's opacity, blend mode and appearance items were lost on each retrace. The new group now takes them from the tracing it replaces. After an option change replaced the tracing, a PluginItem read from a collection or the selection was a different object from the one the script already held. Handles to a replaced tracing now name the first object of its chain of replacements, so they compare equal. --- crates/engine/src/cmd/buildcmds/trace.rs | 12 +++++++ crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/tracing.rs | 19 +++++++++++ crates/engine/src/tests/script_dom_tracing.rs | 32 +++++++++++++++++++ 4 files changed, 64 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index ff99c44bb2..70f23c743d 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1225,6 +1225,18 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Data { Some("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))), Some("PluginItem") => { tracing::remember_source(h, st.uid, n); - host_ref("PluginItem", &node_handle(h, st, id)) + host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id))) } Some(t) => host_ref(t, &node_handle(h, st, id)), None => host_ref("Layer", &node_handle(h, st, id)), diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index 4b538d3937..d4e249796c 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -149,6 +149,25 @@ pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { id } +/// The first object of the run's chain of replacements that leads to `id` in the document `uid`, +/// so every handle to a tracing traced again names the same object; `id` when no earlier object +/// in the chain resolves to it. +pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId { + let first = { + let next = h.dom.tracing.next.borrow(); + let mut first = id; + // Each object replaces one made before it, so the steps end; the bound holds them anyway. + for _ in 0..next.len() { + match next.iter().find(|((u, _), n)| *u == uid && **n == first.0) { + Some(((_, old), _)) => first = NodeId(*old), + None => break, + } + } + first + }; + if first != id && follow(h, uid, first) == id { first } else { id } +} + /// Records that `new` replaced `old` in the document `uid`. fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 6b891aadc0..a87cb7dd6d 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1107,3 +1107,35 @@ fn trace_plugin_keeps_its_name() { assert_eq!(undo_steps(&s), 2, "the place and the run"); let _ = std::fs::remove_dir_all(base); } + +#[test] +fn retrace_keeps_the_tracing_opacity_and_blend_mode() { + let base = folder("retrace-appearance"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(); p.opacity = 50; p.blendingMode = BlendModes.MULTIPLY;\ + p.tracing.tracingOptions.threshold = 90; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);\ + p.tracing.tracingOptions.threshold = 100; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);", + ); + assert_eq!(out, [json!(50), json!(true), json!(50), json!(true)]); + let id = traces(&s)[0]; + assert_eq!(s.active().unwrap().doc.node(id).unwrap().opacity, 0.5); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retraced_plugin_is_the_same_object_as_its_collection_handle() { + let base = folder("retrace-identity"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(); vc.log(d.pageItems[0] === p);\ + p.tracing.tracingOptions.threshold = 90; vc.log(d.pageItems[0] === p); vc.log(app.selection[0] === p);\ + p.tracing.tracingOptions.threshold = 100; vc.log(d.pageItems[0] === p); vc.log(p.tracing.parent === d.pageItems[0]);", + ); + assert_eq!(out, vec![json!(true); 5]); + let _ = std::fs::remove_dir_all(base); +} From bf56f4d062b2fe7fcad5d9b90e5d1e37104b92ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:00:17 -0800 Subject: [PATCH 30/41] Scripts: a group holding an image cannot take the tracing's name PageItem.name now refuses "Image Trace" for an unclipped group whose first object is an image and that is not already a tracing. That name would make the group a tracing, and expanding it would delete its first object. The snapshot of a tracing's objects is now taken only for a tracing saved without the record of the objects its trace made, and only the first time a run sees it. Retrace reads it only in that case. docs/target-app-parity.md now says that the view options only change the view, and docs/mcp.md lists the new rename error. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/script/dom.rs | 27 +++++++++++++++---- crates/engine/src/script/dom/tracing.rs | 24 ++++++++++++++--- crates/engine/src/tests/script_dom_tracing.rs | 15 +++++++++++ docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 6 files changed, 61 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4afcb08ea4..93ad8ae4c5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -966,7 +966,7 @@ pub(crate) use buildcmds::TracePresetChanges; /// Whether an object is an Image Trace object, the source image of one, or the seam fills group in /// one. -pub(crate) use buildcmds::{is_seam_fills, is_trace_group, is_trace_source}; +pub(crate) use buildcmds::{TRACE_NAME, is_seam_fills, is_trace_group, is_trace_source}; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c0beb1f30d..5d155b5c2d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -130,6 +130,8 @@ pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; pub const STALE_ITEM: &str = "Stale page item"; /// The error for a new name given to a `PluginItem`. const TRACING_NAME: &str = "The name of a tracing cannot be changed"; +/// The error for the tracing's name given to a group that holds an image first. +const NOT_A_TRACING: &str = "Only Image Trace can make a tracing"; /// The error for a document that was closed, or that came from an earlier run. pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. @@ -2283,12 +2285,27 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer { if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } - // An Image Trace object is known by its name, so renaming one would end the tracing. + // An Image Trace object is known by its name, so renaming one would end the tracing, and giving + // an ordinary group that holds an image first the tracing's name would make it one. let item = this_item(h, a)?; - let tracing = - with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| crate::cmd::is_trace_group(n) && n.name.as_deref() != Some(&**name))); - if tracing { - return Err(HostError::Error(TRACING_NAME.into())); + let refused = with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).and_then(|n| { + let tracing = crate::cmd::is_trace_group(n); + let would_trace = !tracing + && name == crate::cmd::TRACE_NAME + && matches!(n.kind, crate::doc::NodeKind::Group { clip: false, .. }) + && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, crate::doc::NodeKind::Image(_)))); + if tracing && n.name.as_deref() != Some(&**name) { + Some(TRACING_NAME) + } else if would_trace { + Some(NOT_A_TRACING) + } else { + None + } + }) + }); + if let Some(msg) = refused { + return Err(HostError::Error(msg.into())); } set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) } diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index d4e249796c..cdc82e21fb 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -174,8 +174,16 @@ fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { } pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { + let mut first = true; if let Some(source) = group.children().and_then(|c| c.first()) { - h.dom.tracing.sources.borrow_mut().entry((uid, group.id.0)).or_insert(source.id); + let mut sources = h.dom.tracing.sources.borrow_mut(); + first = !sources.contains_key(&(uid, group.id.0)); + sources.entry((uid, group.id.0)).or_insert(source.id); + } + // Only a tracing saved without the record of the objects its trace made needs the snapshot, + // taken the first time this run sees it. + if !first || group.trace_made().is_some() { + return; } h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| { let mut ids = HashSet::new(); @@ -309,14 +317,22 @@ fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), H } read_group(h, item, |_, group| { remember_source(h, item.doc.uid, group); - let descendants = h.dom.tracing.descendants.borrow(); - let ids = descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?; // The objects the trace made, as the tracing records them; a tracing saved without that // record is checked against the objects it held when this run first saw it. let made = group.trace_made(); + let descendants = h.dom.tracing.descendants.borrow(); + let ids = match made { + Some(_) => None, + None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?), + }; let mut added = false; group.walk(&mut |n| { - added |= n.id != group.id && made.as_ref().map_or(!ids.contains(&n.id), |m| !m.contains(n.id)); + added |= n.id != group.id + && match (&made, ids) { + (Some(m), _) => !m.contains(n.id), + (None, Some(ids)) => !ids.contains(&n.id), + (None, None) => false, + }; }); if added { return Err(HostError::Error(ADDED_ARTWORK.into())); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index a87cb7dd6d..73e75d4637 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1108,6 +1108,21 @@ fn trace_plugin_keeps_its_name() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn a_group_holding_an_image_cannot_take_the_tracing_name() { + let base = folder("rename-to-trace"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, m = ''; d.selection = [d.rasterItems[0]]; vc.run('object.group'); var g = d.pageItems[0];\ + try { g.name = 'Image Trace'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.typename); g.name = 'Logo'; vc.log(g.name);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem"), json!("Logo")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn retrace_keeps_the_tracing_opacity_and_blend_mode() { let base = folder("retrace-appearance"); diff --git a/docs/mcp.md b/docs/mcp.md index db7a87b126..d60ee1064a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3266,7 +3266,8 @@ through `$`: `imageTrace.presets.save`. A tracing that was expanded, released, deleted, traced again by a command, or whose source image was deleted throws `Stale page item`. A script gets the source image from `sourceArt`, and `pageItems`, `placedItems` and `rasterItems` do not list it. Assigning a different `name` to a `PluginItem` throws - `The name of a tracing cannot be changed`. `areaCount`, `cornerAngle`, `livePaintOutput`, + `The name of a tracing cannot be changed`, and assigning `Image Trace` as the `name` of a group whose first object + is an image throws `Only Image Trace can make a tracing`. `areaCount`, `cornerAngle`, `livePaintOutput`, `maxStrokeWeight`, `minStrokeLength`, `outputToSwatches`, `pathFitting`, `preprocessBlur`, `resample` and `resampleResolution` throw an error that says they are not implemented. With a script running, `imageTrace.make` stops at the run's stop request and changes nothing. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ddc27573bd..66ea39e54c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1111,7 +1111,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. `crates/engine/src/tests/script_dom_tracing.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 08bc2d20097421d2e448ad2789b1e7a8f7b62f76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:37:29 -0800 Subject: [PATCH 31/41] Scripts: image lists propagate the page item list's run error Cause: main's fe89d3f8 changed page_items to return a Result, since building the list again now counts against the run's host-call allowance. The image collections' list builder still used the old return type, so vectorcraft-engine did not compile once main was merged in, and every gate shard failed. The builder now passes the error on with `?`, as the path and text lists do. --- crates/engine/src/script/dom/images.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 81e11ec177..29adc7ad6a 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -144,7 +144,7 @@ fn images(h: &Host, st: &DocState, placed: bool) -> Result>, Host { return Ok(pick(l)); } - let all = page_items(h, st); + let all = page_items(h, st)?; h.charge_call(all.len() as u64)?; let (mut linked, mut embedded) = (Vec::new(), Vec::new()); for id in all.iter() { From d9d9354ec707da891faa94fbaa64db774afeb93f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:09:41 -0800 Subject: [PATCH 32/41] Scripts: moving an image cannot make a tracing; counts do only their work - move() and duplicate() refuse to put an image at the bottom of an ordinary group named Image Trace, before the document changes, as renaming such a group already does. A tracing's source image moved out keeps its own error. - pathCount and usedColorCount no longer walk the anchor points, and anchorCount charges each path inside a compound path it reads. - The run keeps the reverse of its replacement map, so finding the first object of a chain no longer scans the whole map at each step. - docs: the source image of a traced item is left out of pageItems, placedItems and rasterItems and is reached through PluginItem.tracing.sourceArt; docs/mcp.md lists the new error. --- crates/engine/src/script/dom.rs | 32 +++++++- crates/engine/src/script/dom/tracing.rs | 79 ++++++++++++++----- crates/engine/src/tests/script_dom_tracing.rs | 27 +++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 5 files changed, 120 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 3ab7f5b1e2..7a6fd0ed91 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2788,10 +2788,35 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let name = d.node(item.id).and_then(typename).unwrap_or("page item"); return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); } + // Checked here as well as in `place`, so `duplicate` refuses before it makes the copy. A + // tracing's source image moved out keeps the error `place` gives it. + let image = d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))); + if image && (copy || !crate::cmd::is_trace_source(d, item.id)) && named_as_tracing(d, parent) { + // Where the image comes from: its index in `parent` when it is already there. + let own = d.position(item.id).and_then(|(p, i, _)| (p == Some(parent)).then_some(i)).filter(|_| !copy); + let count = d.children(Some(parent)).map_or(0, Vec::len); + let first = match how { + Placement::Bottom => true, + Placement::Top => count == usize::from(own.is_some()), + Placement::Below => beside.and_then(|b| d.position(b)).is_some_and(|(_, i, _)| i == 0 || (i == 1 && own == Some(0))), + Placement::Above => false, + }; + if first { + return Err(HostError::Error(NOT_A_TRACING.into())); + } + } Ok(Destination { parent, beside, how }) }) } +/// Whether `id` is an ordinary group named as an Image Trace object that is not one: an image put +/// first in it would make it a tracing. +fn named_as_tracing(d: &Document, id: NodeId) -> bool { + d.node(id).is_some_and(|p| { + !crate::cmd::is_trace_group(p) && matches!(p.kind, NodeKind::Group { clip: false, .. }) && p.name.as_deref() == Some(crate::cmd::TRACE_NAME) + }) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { @@ -2822,7 +2847,12 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul } (_, None) => count, }; - Ok::<_, HostError>(if clips { at.max(1) } else { at }) + let at = if clips { at.max(1) } else { at }; + // An image put first in an ordinary group named as a tracing would make that group one. + if at == 0 && d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) && named_as_tracing(d, to.parent) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } + Ok::<_, HostError>(at) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index cdc82e21fb..9e058ebc95 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -121,6 +121,8 @@ const NOT_IMPLEMENTED: &[&str] = &[ #[derive(Default)] pub(super) struct State { next: RefCell>, + /// `next` the other way round: for each replacing object, the object it replaced. + prev: RefCell>, sources: RefCell>, descendants: RefCell>>, retraces: Cell, @@ -154,12 +156,12 @@ pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { /// in the chain resolves to it. pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId { let first = { - let next = h.dom.tracing.next.borrow(); + let prev = h.dom.tracing.prev.borrow(); let mut first = id; // Each object replaces one made before it, so the steps end; the bound holds them anyway. - for _ in 0..next.len() { - match next.iter().find(|((u, _), n)| *u == uid && **n == first.0) { - Some(((_, old), _)) => first = NodeId(*old), + for _ in 0..prev.len() { + match prev.get(&(uid, first.0)) { + Some(old) => first = NodeId(*old), None => break, } } @@ -170,7 +172,14 @@ pub(super) fn origin(h: &Host, uid: u64, id: NodeId) -> NodeId { /// Records that `new` replaced `old` in the document `uid`. fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { - h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0); + let mut prev = h.dom.tracing.prev.borrow_mut(); + // A second replacement of `old` takes the place of the first in both directions. + if let Some(earlier) = h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0) + && prev.get(&(uid, earlier)) == Some(&old.0) + { + prev.remove(&(uid, earlier)); + } + prev.insert((uid, new.0), old.0); } pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { @@ -413,10 +422,27 @@ struct Counts { visited: u64, } -fn anchors_of(n: &Node) -> u64 { +/// Which of a tracing's counts a read needs; the others are not worked out. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Metric { + Paths, + Anchors, + Colors, +} + +/// The anchor points of `n` and every path in it, adding each object looked at below `n` to +/// `visited`. +fn anchors_of(n: &Node, visited: &mut u64) -> u64 { match &n.kind { NodeKind::Path { path, .. } => path.anchor_count() as u64, - _ => n.children().map_or(0, |c| c.iter().map(|m| anchors_of(m)).sum()), + _ => n.children().map_or(0, |c| { + c.iter() + .map(|m| { + *visited += 1; + anchors_of(m, visited) + }) + .sum() + }), } } @@ -425,8 +451,10 @@ fn anchors_of(n: &Node) -> u64 { /// are a clip group directly in the tracing that [`crate::cmd::is_seam_fills`] accepts, or, for a /// trace made before seam fills were clipped, the lowest item above the source image when it /// accepts that. A group nested deeper, or an unclipped group higher up, is counted. An Image -/// Trace object inside `g` leaves out its own seam fills the same way. -fn counts(g: &Node) -> Counts { +/// Trace object inside `g` leaves out its own seam fills the same way. Only the count `metric` +/// names is worked out; a compound path counts as one path, and the paths inside it are looked at +/// (and counted in `visited`) only for its anchor points. +fn counts(g: &Node, metric: Metric) -> Counts { let mut c = Counts::default(); let mut paints = HashSet::new(); let mut todo: Vec<&Arc> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default(); @@ -443,12 +471,17 @@ fn counts(g: &Node) -> Counts { NodeKind::Path { clipping: true, .. } => {} NodeKind::Path { .. } | NodeKind::Compound { .. } => { c.paths += 1; - c.anchors += anchors_of(n); - for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] { - if paint != vectorcraft_color::Paint::None - && let Ok(key) = serde_json::to_string(&paint) - { - paints.insert(key); + match metric { + Metric::Paths => {} + Metric::Anchors => c.anchors += anchors_of(n, &mut c.visited), + Metric::Colors => { + for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] { + if paint != vectorcraft_color::Paint::None + && let Ok(key) = serde_json::to_string(&paint) + { + paints.insert(key); + } + } } } } @@ -472,23 +505,27 @@ fn seam_fills_of(g: &Node) -> HashSet { } /// Reads the counts of the tracing `this` names with `f`. -fn count(h: &Host, a: &[Data], f: fn(&Counts) -> u64) -> Answer { +fn count(h: &Host, a: &[Data], metric: Metric) -> Answer { let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; - let c = read_group(h, item, |_, g| Ok(counts(g)))?; + let c = read_group(h, item, |_, g| Ok(counts(g, metric)))?; h.charge_call(c.visited)?; - Ok(num(float(f(&c)))) + Ok(num(float(match metric { + Metric::Paths => c.paths, + Metric::Anchors => c.anchors, + Metric::Colors => c.colors, + }))) } fn tracing_paths(h: &Host, a: &[Data]) -> Answer { - count(h, a, |c| c.paths) + count(h, a, Metric::Paths) } fn tracing_anchors(h: &Host, a: &[Data]) -> Answer { - count(h, a, |c| c.anchors) + count(h, a, Metric::Anchors) } fn tracing_colors(h: &Host, a: &[Data]) -> Answer { - count(h, a, |c| c.colors) + count(h, a, Metric::Colors) } fn tracing_areas(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 73e75d4637..940f653184 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1123,6 +1123,33 @@ fn a_group_holding_an_image_cannot_take_the_tracing_name() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() { + let base = folder("move-into-trace-name"); + let (mut s, _) = session(&base, false); + let before = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, r = d.rasterItems[0], m = [];\ + d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); var g = d.pageItems[0];\ + g.name = 'Image Trace';\ + try { r.move(g, ElementPlacement.PLACEATEND); m.push('moved'); } catch (e) { m.push(e.message); }\ + try { r.duplicate(g, ElementPlacement.PLACEATEND); m.push('copied'); } catch (e) { m.push(e.message); }\ + vc.log(m); vc.log(d.rasterItems.length); vc.log(g.typename);\ + r.move(g, ElementPlacement.PLACEATBEGINNING); vc.log(g.typename);", + ); + let refused = json!("Only Image Trace can make a tracing"); + assert_eq!(out, [json!([refused, refused]), json!(1), json!("GroupItem"), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + let g = top(&s)[0]; + let kids: Vec = d.children(Some(g)).unwrap().iter().map(|n| matches!(n.kind, crate::doc::NodeKind::Image(_))).collect(); + assert_eq!(kids, [false, true], "the image went in above the rectangle"); + assert_eq!(undo_steps(&s), before + 1, "the run is one step"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn retrace_keeps_the_tracing_opacity_and_blend_mode() { let base = folder("retrace-appearance"); diff --git a/docs/mcp.md b/docs/mcp.md index f679fba5a4..7dfc8f77ac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3039,7 +3039,9 @@ through `$`: is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Moving a tracing's visible, unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave - its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. An object of + its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating + an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before + the document changes, as renaming such a group does. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9f8943592a..6d193ce2ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1113,7 +1113,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. `crates/engine/src/tests/script_dom_tracing.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From a1b8b013832dc70f5afd547bc8fe3666443b8512 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:26:30 -0800 Subject: [PATCH 33/41] Scripts: refuse moves that make a tracing, and a release that drops added art - move, remove() and zOrder throw "Only Image Trace can make a tracing", with nothing changed, when they would leave an image at the bottom of an ordinary group named Image Trace: a path moved out of the group or to its top, Send to Back or Send Backward on the image, and Bring to Front or Bring Forward on the object below it. - releaseTracing() throws "Cannot release a tracing containing added artwork", with nothing changed, when the tracing holds an object its trace did not make. imageTrace.release keeps only the source image, so the added object would be deleted. - The TracingOptions members with no setting and TracingObject.areaCount are left out of hasOwnProperty and reflect. Reading them still throws. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 37 +++++++- crates/engine/src/script/dom/tracing.rs | 38 +++++--- crates/engine/src/tests/script_dom_tracing.rs | 92 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- docs/mcp.md | 6 +- 5 files changed, 157 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cf073482ba..998e528e26 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2696,6 +2696,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + // An image left first in an ordinary group named as a tracing would make that group one. + if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; Ok(Data::Undefined) @@ -2831,6 +2835,20 @@ fn named_as_tracing(d: &Document, id: NodeId) -> bool { }) } +/// Whether taking the object `id` out of `parent` and, with `at`, putting it back at that index of +/// what is left would make `parent`, an ordinary group named as a tracing, one: an image first in it. +fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> bool { + if !named_as_tracing(d, parent) { + return false; + } + let image = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Image(_)); + let rest = d.children(Some(parent)).map(|c| c.iter().filter(|n| n.id != id).collect::>()).unwrap_or_default(); + match at { + Some(0) => d.node(id).is_some_and(|n| image(n)), + _ => rest.first().is_some_and(|n| image(n)), + } +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { @@ -2862,8 +2880,10 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul (_, None) => count, }; let at = if clips { at.max(1) } else { at }; - // An image put first in an ordinary group named as a tracing would make that group one. - if at == 0 && d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) && named_as_tracing(d, to.parent) { + // An image left or put first in an ordinary group named as a tracing would make that group + // one, in the group it leaves as in the group it goes into. + let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent); + if makes_tracing(d, to.parent, id, Some(at)) || left.is_some_and(|p| makes_tracing(d, p, id, None)) { return Err(HostError::Error(NOT_A_TRACING.into())); } Ok::<_, HostError>(at) @@ -2985,6 +3005,19 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if unchanged { return Ok(Data::Undefined); } + // Where the Arrange command puts the item among its parent's art, worked out as + // `object.arrange` works it out for one object. An image put first, or another object moved + // from above an image that becomes first, in an ordinary group named as a tracing would make + // that group one. + let to = match id { + "object.arrange.bringToFront" => art - 1, + "object.arrange.bringForward" => i + 1, + "object.arrange.sendBackward" => i - 1, + _ => floor, + }; + if parent.is_some_and(|p| with_doc(h, item.doc, |_, st| makes_tracing(&st.doc, p, item.id, Some(to)))) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } match parent { Some(p) if in_trace && id == "object.arrange.sendToBack" => { edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": floor}))?; diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index 9e058ebc95..a5b4ee561c 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -25,7 +25,8 @@ //! `TracingOptions` follow it. A tracing that another command traced again, expanded or //! released, or whose source image was deleted, is stale. //! - Tracing again throws [`ADDED_ARTWORK`], with nothing changed, when the tracing holds an object -//! its trace did not make, whether this run, an earlier run or a command added it. The tracing records the +//! its trace did not make, whether this run, an earlier run or a command added it, and +//! `releaseTracing()` throws [`ADDED_ARTWORK_RELEASE`] in the same case. The tracing records the //! objects its trace made ([`crate::doc::TraceMade`]), and a copy of it records their copies. A //! tracing saved without that record is checked only for objects added in this run. //! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or @@ -56,6 +57,8 @@ use crate::{NodeId, NodeKind}; pub const ALREADY_TRACED: &str = "The image is the source art of a tracing"; /// The error of tracing again a tracing that holds an object its trace did not make. pub const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork"; +/// The error of releasing a tracing that holds an object its trace did not make. +pub const ADDED_ARTWORK_RELEASE: &str = "Cannot release a tracing containing added artwork"; /// The error of options that trace with neither fills nor strokes. pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes"; /// The error of `expandTracing(true)`. @@ -318,12 +321,8 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< }) } -/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its -/// script objects follow the new one. -fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), HostError> { - if h.dom.tracing.retraces.get() >= MAX_RETRACES { - return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); - } +/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make. +fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { read_group(h, item, |_, group| { remember_source(h, item.doc.uid, group); // The objects the trace made, as the tracing records them; a tracing saved without that @@ -344,10 +343,19 @@ fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), H }; }); if added { - return Err(HostError::Error(ADDED_ARTWORK.into())); + return Err(HostError::Error(refusal.into())); } Ok(()) - })?; + }) +} + +/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its +/// script objects follow the new one. +fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), HostError> { + if h.dom.tracing.retraces.get() >= MAX_RETRACES { + return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); + } + refuse_added(h, item, ADDED_ARTWORK)?; params.insert("id".into(), json!(item.id.0)); // One savepoint covers the trace and the selection's restore, so a failed restore undoes the trace. let new = super::atomically(h, |h| replace(h, item, "imageTrace.make", &Value::Object(params), "id"))?; @@ -582,9 +590,12 @@ fn tracing_expand(h: &Host, a: &[Data]) -> Answer { Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) } -/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. +/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. A +/// tracing that holds an object its trace did not make throws [`ADDED_ARTWORK_RELEASE`], since the +/// release keeps only the source image. fn tracing_release(h: &Host, a: &[Data]) -> Answer { let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + refuse_added(h, item, ADDED_ARTWORK_RELEASE)?; let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?; Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) } @@ -836,7 +847,8 @@ fn options_store(h: &Host, a: &[Data]) -> Answer { } /// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw, -/// after the check that the tracing `this` names is still there. +/// after the check that the tracing `this` names is still there, and `reflect` and +/// `hasOwnProperty` leave it out. fn missing(link: &Link, name: &'static str) -> Described { let message = not_implemented("TracingOptions", name); let l = link.clone(); @@ -846,7 +858,7 @@ fn missing(link: &Link, name: &'static str) -> Described { tracing_of(&h, arg(&a, 0), "TracingOptions")?; Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }, MemberInfo { unavailable: true, ..MemberInfo::default() }) + (name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() }) } /// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`. @@ -868,7 +880,7 @@ pub(super) fn classes(l: &Link) -> Vec { let tracing = named(vec![ ("typename", typename_of("TracingObject"), typed("string")), ("anchorCount", get(l, tracing_anchors), typed("number")), - ("areaCount", get(l, tracing_areas), typed("number")), + ("areaCount", HostMember::Unavailable(super::function(l, tracing_areas)), MemberInfo { unavailable: true, ..MemberInfo::default() }), ("imageResolution", get(l, tracing_resolution), typed("number")), ("parent", get(l, tracing_parent), typed("PluginItem")), ("pathCount", get(l, tracing_paths), typed("number")), diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 940f653184..ee3bb6a1b8 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1150,6 +1150,98 @@ fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// `move`, `remove()` and `zOrder` refuse to leave an image at the bottom of an ordinary group named +/// as a tracing, before the document changes, and allow the same moves when another object stays +/// at the bottom. +#[test] +fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { + let base = folder("leave-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], r = d.rasterItems[0], p = d.pathItems[0], m = [];\ + function t(f) { try { f(); m.push('done'); } catch (e) { m.push(e.message); } }\ + t(function () { p.move(g, ElementPlacement.PLACEBEFORE); });\ + t(function () { p.move(g, ElementPlacement.PLACEATBEGINNING); });\ + t(function () { p.remove(); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGTOFRONT); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGFORWARD); });\ + t(function () { r.zOrder(ZOrderMethod.SENDTOBACK); });\ + t(function () { r.zOrder(ZOrderMethod.SENDBACKWARD); });\ + vc.log(m); vc.log(g.typename);", + ); + assert_eq!(out, [json!(vec!["Only Image Trace can make a tracing"; 7]), json!("GroupItem")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], p = d.pathItems[0];\ + d.pathItems.rectangle(40, 40, 5, 5).move(g, ElementPlacement.PLACEATEND);\ + p.move(g, ElementPlacement.PLACEBEFORE); vc.log(g.typename);", + ); + assert_eq!(out, [json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + let g = top(&s).into_iter().find(|i| d.node(*i).is_some_and(|n| n.name.as_deref() == Some(crate::cmd::TRACE_NAME))).unwrap(); + assert_eq!(d.children(Some(g)).unwrap().len(), 2, "the rectangle left the group"); + let _ = std::fs::remove_dir_all(base); +} + +/// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object +/// its trace did not make, before the document changes. +#[test] +fn release_refuses_added_artwork_before_changing_the_document() { + let base = folder("release-added-artwork"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(); d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var items = app.activeDocument.pageItems, p, m = '';\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + try { p.tracing.releaseTracing(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("Cannot release a tracing containing added artwork")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert_eq!(traces(&s).len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// The `TracingOptions` and `TracingObject` members that are not implemented are left out of +/// `hasOwnProperty` and `reflect`, and still throw when read. +#[test] +fn unimplemented_tracing_members_are_not_reported() { + let base = folder("unimplemented-members"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = '';\ + vc.log([o.hasOwnProperty('pathFitting'), t.hasOwnProperty('areaCount'), t.hasOwnProperty('pathCount')]);\ + vc.log([o.reflect.find('pathFitting') === null, t.reflect.find('areaCount') === null, t.reflect.find('pathCount') === null]);\ + try { t.areaCount; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!([false, false, true]), json!([true, true, false]), json!("TracingObject.areaCount is not implemented")]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn retrace_keeps_the_tracing_opacity_and_blend_mode() { let base = folder("retrace-appearance"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 469968e618..2bf79b10c0 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -161,7 +161,7 @@ const INSIDE: &[(&str, &str)] = &[ ("TracingObject.", "prototype"), ( "TracingObject.prototype.", - "anchorCount areaCount constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \ + "anchorCount areaCount areaCount= constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \ tracingOptions typename usedColorCount", ), ("TracingOptions.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index ce3af183f8..bc05206aa8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3047,7 +3047,8 @@ through `$`: unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before - the document changes, as renaming such a group does. An object of + the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with + nothing changed, when they would leave an image at the bottom of such a group. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or @@ -3268,7 +3269,8 @@ through `$`: `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws `Cannot retrace a tracing containing added artwork`, with nothing changed, when the tracing holds an object its trace - did not make, whether this run, an earlier run or a command added it. `imageTrace.make` records the objects it made in + did not make, whether this run, an earlier run or a command added it, and `releaseTracing()` throws + `Cannot release a tracing containing added artwork` in the same case. `imageTrace.make` records the objects it made in the tracing's `trace` settings as `made`, ranges of ids `[[first, last], ...]`, and a copy of the tracing records their copies. A tracing saved without `made` is checked only for objects added in the same run. `threshold` takes a whole number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest From 622459dd4bab473987f2c3185a2d4aa0d7df8d87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:42:49 -0800 Subject: [PATCH 34/41] JavaScript: roll back every object of a family after a failed class install main's failed-install roll back (#10544) read one object for each family and handle, while this branch keeps one for each branch of the family. The install now records the class and prototype of each of those objects and the roll back puts each one back, so the merged tree builds again. --- crates/js/src/host_classes.rs | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index a53d1bc8ab..3fcccaa294 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -485,9 +485,9 @@ struct Undo { /// replaced values stay in the interpreter's temporary roots until [`install`] returns, so a /// collection during the call does not free them. globals: Vec<(Key, Option)>, - /// The class and prototype of the object made for each family and handle before the call. An + /// The class and prototype of each object made for a family and handle before the call. An /// instance of the call can give such an object one of the call's classes. - objects: Vec<(MadeKey, u32, Option)>, + objects: Vec<(MadeKey, ObjId, u32, Option)>, } impl Undo { @@ -519,9 +519,9 @@ impl Undo { } } } - for (made, class, proto) in self.objects { - let Some(&id) = i.host_objects.get(&made) else { continue }; - if is_made(&i.heap, &i.host_classes, id, &made) + for (made, id, class, proto) in self.objects { + if i.host_objects.get(&made).is_some_and(|ids| ids.contains(&id)) + && is_made(&i.heap, &i.host_classes, id, &made) && let Ok(o) = i.object_mut(id) && let Class::Host(h) = &mut o.class { @@ -567,12 +567,14 @@ fn install_checked( install_class(i, class, members, undo)?; } if !instances.is_empty() { - for (made, &id) in &i.host_objects { - if is_made(&i.heap, &i.host_classes, id, made) - && let Ok(o) = i.object(id) - && let Class::Host(h) = &o.class - { - undo.objects.push((made.clone(), h.class, o.proto)); + for (made, ids) in &i.host_objects { + for &id in ids { + if is_made(&i.heap, &i.host_classes, id, made) + && let Ok(o) = i.object(id) + && let Class::Host(h) = &o.class + { + undo.objects.push((made.clone(), id, h.class, o.proto)); + } } } } From a3ae03ba8a2cdc1e0aa74ec2edf0cf206bded7af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:11:54 -0800 Subject: [PATCH 35/41] Scripts: pass the image predicate to is_some_and directly Clippy 1.100's redundant_closure lint rejects the closure `|n| image(n)` in makes_tracing, which fails the clippy step of the gate with -D warnings. --- crates/engine/src/script/dom.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5d77bc1633..e74c56da9c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2858,7 +2858,7 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> let image = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Image(_)); let rest = d.children(Some(parent)).map(|c| c.iter().filter(|n| n.id != id).collect::>()).unwrap_or_default(); match at { - Some(0) => d.node(id).is_some_and(|n| image(n)), + Some(0) => d.node(id).is_some_and(image), _ => rest.first().is_some_and(|n| image(n)), } } From 1b3ea180c3cc289fa71c20de1a0dfd5b9ad12941 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:32:53 -0800 Subject: [PATCH 36/41] CI: build two paths without parent-step literals so test selection passes The select legs failed because the shared gate's undeclared-read check (craft-common-actions #451) still counts two paths as reads outside their crate. The engine test built a relative path to a temporary folder from "../".repeat(n), reported as a read of `crates`; the text build script joined CARGO_MANIFEST_DIR with "../..", reported as a read of the repository root. Neither reads a tracked file. The test now builds the path from Component::ParentDir, and the build script takes the manifest directory's grandparent; both give the same paths as before. --- crates/engine/src/tests/fontfiles.rs | 4 ++-- crates/text/build.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/fontfiles.rs b/crates/engine/src/tests/fontfiles.rs index e90aec1df9..e503a98691 100644 --- a/crates/engine/src/tests/fontfiles.rs +++ b/crates/engine/src/tests/fontfiles.rs @@ -143,8 +143,8 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() { let (_dir, root) = folder("relative"); std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap(); let cwd = std::env::current_dir().unwrap(); - let up = "../".repeat(cwd.components().count().saturating_sub(1)); - let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display()); + let up: std::path::PathBuf = std::iter::repeat_n(std::path::Component::ParentDir, cwd.components().count().saturating_sub(1)).collect(); + let relative = up.join(root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap()).display().to_string(); assert!(Path::new(&relative).is_relative()); let mut s = session_for(&root); let mut doc = vectorcraft_doc::Document::new(100.0, 100.0); diff --git a/crates/text/build.rs b/crates/text/build.rs index 7863efe464..a4e3dcf58c 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -103,7 +103,7 @@ fn from_workspace(dir: PathBuf) -> PathBuf { return dir; } let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); - crate_dir.join("../..").join(dir) + crate_dir.parent().and_then(Path::parent).unwrap_or(&crate_dir).join(dir) } /// The one craft-fonts face web builds embed (family, style). From d308e9d017c6f3c3773746e4f7b876f9bae7cf5e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:38:09 -0800 Subject: [PATCH 37/41] xtask: check the CI shard-members lines in every shard, not in one test With test selection, a pull request that moves a crate between shards in GROUPS without changing ci.yml could skip the shard holding the test that compared the two. `shards::check`, which every shard and warm leg runs, now compares them and fails with both lists. --- xtask/src/shards.rs | 52 ++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index f28a881fd4..188f1bbda8 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -327,6 +327,9 @@ pub fn names(crates: &[Member]) -> String { /// The shards of this workspace, after the checks in [`assign`] and [`feature_differences`]. pub fn check() -> Result, String> { + // The shared gate runs only the shards that test a crate a pull request reaches, by these + // lines, so a mismatch fails every shard instead of one test that selection may skip. + workflow_members(include_str!("../../.github/workflows/ci.yml"))?; let members = members(&crate::metadata()?)?; let shards = assign(GROUPS, &members)?; let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members); @@ -349,6 +352,34 @@ pub fn check() -> Result, String> { Ok(shards) } +/// The lines of the `shard-members: |` block in `workflow`, trimmed. +fn shard_members(workflow: &str) -> Vec<&str> { + let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |"); + let Some(key) = lines.next() else { return Vec::new() }; + let indent = |l: &str| l.len() - l.trim_start().len(); + lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect() +} + +/// Checks that `workflow`'s `shard-members` block names each shard's crates as [`GROUPS`] does. +fn workflow_members(workflow: &str) -> Result<(), String> { + let expected: Vec = GROUPS + .iter() + .map(|g| match g { + Group::Crates(crates) => crates.join(" "), + Group::Part(split, _) => split.crates.join(" "), + Group::Rest => "(rest)".to_owned(), + Group::Checks => "(always)".to_owned(), + }) + .collect(); + let found = shard_members(workflow); + if found != expected { + return Err(format!( + "shard-members in .github/workflows/ci.yml does not match xtask/src/shards.rs › GROUPS:\n found: {found:?}\n expected: {expected:?}" + )); + } + Ok(()) +} + /// `cargo xtask shards`: prints each shard's crates after [`check`], and returns the shards. pub fn run() -> Result, String> { let shards = check()?; @@ -685,27 +716,10 @@ geom v0.1.0 (/w/geom)| ); } - /// The lines of the `shard-members: |` block in `workflow`, trimmed. - fn shard_members(workflow: &str) -> Vec<&str> { - let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |"); - let Some(key) = lines.next() else { return Vec::new() }; - let indent = |l: &str| l.len() - l.trim_start().len(); - lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect() - } - #[test] fn ci_names_the_crates_of_every_shard_for_test_selection() { - // The shared gate runs only the shards that test a crate a pull request reaches, by these lines. - let expected: Vec = GROUPS - .iter() - .map(|g| match g { - Group::Crates(crates) => crates.join(" "), - Group::Part(split, _) => split.crates.join(" "), - Group::Rest => "(rest)".to_owned(), - Group::Checks => "(always)".to_owned(), - }) - .collect(); - assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml"); + assert_eq!(workflow_members(include_str!("../../.github/workflows/ci.yml")), Ok(())); + assert!(workflow_members(" shard-members: |\n a b\n (rest)\n next: 1\n").is_err()); assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]); assert!(shard_members("test-shards: 6\n").is_empty()); } From c0b4413a5abe282625c5a0511327ac42ea53613a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:30:09 -0800 Subject: [PATCH 38/41] JS: fix async function review points - AsyncFunction.prototype has Symbol.toStringTag "AsyncFunction", configurable only. - await checks the room for the awaited promise's reaction or job and the suspended frame's bytes before it attaches the reaction, so a suspension stays within the heap limit. - An async function's return pops its frame before resolving its promise, so a then getter on the returned value runs without it. Returning the function's own promise rejects it at the return. - Block functions whose variable was not declared are kept in a hash set, so each block function's lookup takes constant time. - A shorthand await in an object pattern of an async arrow function's head is a syntax error, and the head accepts patterns with defaults such as async ({a = 1}) => a. async({a = 1}) without an arrow is still a syntax error. - docs: .jsx files and source strings run with module: true have Promise and the async syntax; await is an identifier only in script code. --- crates/js/src/async_tests.rs | 83 ++++++++++++++++++++++++ crates/js/src/builtins/async_function.rs | 10 ++- crates/js/src/builtins/promise.rs | 20 ++++++ crates/js/src/generator.rs | 4 +- crates/js/src/interp.rs | 47 ++++++++------ crates/js/src/interp/async_function.rs | 2 +- crates/js/src/parser.rs | 17 +++-- crates/js/src/parser/pattern.rs | 4 ++ docs/mcp.md | 18 ++--- docs/target-app-parity.md | 2 +- 10 files changed, 170 insertions(+), 37 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 6d2c4531ff..711f883633 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -184,6 +184,89 @@ fn a_run_that_ends_with_awaits_pending_ends_cleanly() { assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0)); } +#[test] +fn async_function_prototype_has_its_to_string_tag() { + let src = "var AFP = Object.getPrototypeOf(async function () {});\n\ + var d = Object.getOwnPropertyDescriptor(AFP, Symbol.toStringTag);\n\ + log.push(d.value, d.writable, d.enumerable, d.configurable, Object.prototype.toString.call(async function () {}));"; + assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]"); +} + +#[test] +fn an_await_stays_within_the_heap_limit() { + // The activation, its two reactions, the derived promise and the suspended frame's bytes all + // fit in the heap limit, or the run stops at the `await`. The frame waits with 40 operands on + // a promise that never settles, so its bytes stay charged after the run. A suspension that + // went past the limit would be stopped only later, at the end of the run, so the largest + // heap that still stops the run must stop it at the `await`. + let operands: String = (0..40).map(|i| format!("{i}, ")).collect(); + let setup = + format!("var gate = new Promise(function () {{}}); function g() {{ return 0; }} async function f() {{ return g({operands}await gate); }} 0"); + let setup = setup.as_str(); + let await_column = setup.find("await gate").map(|i| i + 1); + let run = "f(); 0"; + let mut measure = realm(); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + let base = measure.collect_garbage(); + assert_eq!(measure.run(run), Ok(JsValue::Number(0.0))); + let need = measure.interp().settled_heap_bytes().saturating_sub(base) + 1024; + let mut last_stop = None; + let mut over = Vec::new(); + for spare in (0..=need).step_by(4) { + let mut r = realm(); + assert_eq!(r.run(setup), Ok(JsValue::Number(0.0))); + let heap_bytes = r.collect_garbage() + spare; + r.set_limits(Limits { heap_bytes, ..Limits::default() }); + let out = r.run(run); + match &out { + Ok(JsValue::Number(_)) => {} + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => last_stop = Some((spare, e.line, e.column)), + other => panic!("{spare}: {other:?}"), + } + let bytes = r.interp().settled_heap_bytes(); + if out.is_ok() && bytes > heap_bytes { + over.push((spare, bytes - heap_bytes)); + } + } + assert!(over.is_empty(), "runs that suspended past the limit (spare bytes, bytes over): {over:?}"); + let Some((spare, line, column)) = last_stop else { panic!("no limit stopped the run") }; + assert_eq!((line, usize::try_from(column).ok()), (1, await_column), "the run with {spare} spare bytes stopped away from the await"); +} + +/// The fewest frames with which `src` runs to its end. +fn fewest_frames(src: &str) -> usize { + for frames in 1..64 { + let mut r = Realm::with_options(Options { es2017: true, ..Options::default() }, Limits { frames, ..Limits::default() }); + if r.run(src).is_ok() { + return frames; + } + } + panic!("{src} did not run"); +} + +#[test] +fn a_then_getter_on_a_returned_value_runs_after_the_async_frame_ends() { + let setup = "function rec(n) { return n ? rec(n - 1) : 0; }\n\ + var o = { get then() { rec(5); return undefined; } };\n"; + let direct = fewest_frames(&format!("{setup}o.then; 0")); + let returned = fewest_frames(&format!("{setup}async function f() {{ return o; }} f(); 0")); + assert_eq!(returned, direct); + // Returning the function's own promise rejects it with a TypeError. + let own = "async function f() { await 0; return p; } var p = f(); p.catch(function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(own), "true"); +} + +#[test] +fn an_async_arrow_head_reads_patterns_with_defaults_and_rejects_a_shorthand_await() { + let src = "var f = async ({a = 1}) => a; var g = async ({await: x}) => x; var h = async ([b = 2]) => b;\n\ + Promise.all([f({}), g({ await: 3 }), h([])]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "1,3,2"); + let mut r = realm(); + syntax_error(&mut r, "var async = function () {}; async({a = 1});"); + syntax_error(&mut r, "async ({await}) => 0"); + syntax_error(&mut r, "async ({a = await}) => 0"); +} + #[test] fn each_resume_takes_fuel() { let mut r = realm(); diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs index fa3d70a422..1baaeaad79 100644 --- a/crates/js/src/builtins/async_function.rs +++ b/crates/js/src/builtins/async_function.rs @@ -4,7 +4,7 @@ //! reaches through it. `AsyncFunction` is not a global. use super::{create_dynamic_function, data, native}; -use crate::heap::{CONFIGURABLE, Class, NativeKind, Object}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, Object, Prop}; use crate::interp::{Interp, JsResult}; use crate::value::Value; @@ -25,7 +25,13 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { data(interp, ctor, "prototype", Value::Object(proto), 0)?; // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary // built-in prototypes. - data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) + data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE)?; + // `AsyncFunction.prototype[@@toStringTag]` is "AsyncFunction", configurable only (section + // 25.5.3.2). + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("AsyncFunction"), flags: CONFIGURABLE })?; + } + Ok(()) } /// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 7ef696b086..8182fde016 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -609,6 +609,21 @@ impl Interp { } } + /// Resolves the promise of an async function whose frame has returned `v` and is already off + /// the frames. Returning the promise itself rejects it with a `TypeError` at `site`, the + /// return. + pub(crate) fn resolve_async_return(&mut self, p: ObjId, v: Value, site: Option) -> JsResult<()> { + if matches!(v, Value::Object(o) if o == p) { + return scoped(self, |interp| { + root(interp, &Value::Object(p)); + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + root(interp, &e); + reject_promise(interp, p, e, site) + }); + } + resolve_promise(self, p, v) + } + /// A new pending promise for the async function call whose frame is on top. pub(crate) fn new_async_promise(&mut self) -> JsResult { new_promise(self) @@ -639,6 +654,11 @@ impl Interp { let derived = new_promise(interp)?; root(interp, &Value::Object(derived)); promise_data(interp, derived)?.handled = true; + // The allocations above used up the room checked for at the start, so the reaction or + // job and the frame's bytes are checked again, with the frame still on top, before the + // awaited promise gets its reaction. + let then_bytes = if promise_data(interp, p)?.state == State::Pending { REACTION_BYTES } else { JOB_BYTES }; + interp.reserve_heap(then_bytes.saturating_add(bytes))?; perform_then(interp, p, on_fulfilled, on_rejected, derived)?; let (a, boundary) = interp.suspend_frame()?; let promise = a.promise; diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs index 195113d529..361af9a01f 100644 --- a/crates/js/src/generator.rs +++ b/crates/js/src/generator.rs @@ -18,7 +18,7 @@ use crate::LimitKind; use crate::builtins::iterator::iter_result; use crate::bytecode::Code; use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; -use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::interp::{Abrupt, AnnexOff, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; use crate::value::Value; /// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). @@ -306,7 +306,7 @@ impl Interp { boundary, generator: Some(generator), async_promise: None, - annex_off: Vec::new(), + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index c64f46e972..df44f785bb 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -211,6 +211,9 @@ impl Intrinsics { } } +/// The names of [`Frame::annex_off`], looked up once for each block function a frame assigns. +pub(crate) type AnnexOff = std::collections::HashSet; + pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, @@ -245,7 +248,7 @@ pub(crate) struct Frame { pub(crate) async_promise: Option, /// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not /// declared: [`Op::AnnexB`] leaves them alone. - pub(crate) annex_off: Vec, + pub(crate) annex_off: AnnexOff, /// The frame runs a module that another module of the same run waits under (ECMA-262 2015 /// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception /// that leaves it ends the run at the boundary frame without stopping in the frames between. @@ -1365,20 +1368,26 @@ impl Interp { Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, None => v, }; - // An async function's return resolves its promise, while the frame is still on top, and - // the call gives the promise. - let v = match self.async_promise() { - Some(p) => { - self.settle_async(p, Ok(v))?; - Value::Object(p) - } - None => v, - }; let Some(frame) = self.pop_frame() else { return internal("return without a frame") }; self.stack.truncate(frame.base); - self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); + // An async function's return resolves its promise after the frame is off the frames, so + // a `then` getter the resolution reads runs without it, and the call gives the promise. + // Settling roots the promise and the value, and a rejection for returning the promise + // itself is reported at the return. When settling fails, the frame goes back on top, so + // the error is reported at the return and ends the frames down to its boundary. + let v = match frame.async_promise { + Some(p) => match self.resolve_async_return(p, v, Some((frame.code.clone(), frame.pc.saturating_sub(1)))) { + Ok(()) => Value::Object(p), + Err(e) => { + self.frames.push(frame); + return Err(e); + } + }, + None => v, + }; + self.end_generator(frame.generator); let v = match frame.construct { Some(o) if !matches!(v, Value::Object(_)) => Value::Object(o), _ => v, @@ -3914,7 +3923,7 @@ impl Interp { boundary, generator: None, async_promise: None, - annex_off: Vec::new(), + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); @@ -4339,7 +4348,7 @@ impl Interp { /// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the /// code counted against the heap, until its frame holds them: the scopes and functions it /// makes can collect. - fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { + fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { let mark = self.temp_envs.len(); self.temp_envs.push(env); self.temp_codes.push(code.clone()); @@ -4518,7 +4527,7 @@ impl Interp { boundary, generator: None, async_promise: None, - annex_off: Vec::new(), + annex_off: AnnexOff::new(), chained: false, pending_module: false, }); @@ -4651,7 +4660,7 @@ impl Interp { /// option on or off, so it also meets the names that earlier runs of a kept realm declared. /// Also gives the names of [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not /// declare. - fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { + fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { // Strict eval code's own environment is in no frame yet, so it is a root while the // declarations reserve heap. let mark = self.temp_envs.len(); @@ -4662,7 +4671,7 @@ impl Interp { } /// [`Self::instantiate_global`] with `env` and `var_env` in [`Self::temp_envs`]. - fn instantiate_global_rooted(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { + fn instantiate_global_rooted(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, AnnexOff)> { let configurable = if is_eval { CONFIGURABLE } else { 0 }; if is_eval && !code.strict { self.check_eval_vars(code, env, var_env)?; @@ -4709,7 +4718,7 @@ impl Interp { (env, lex): (EnvId, EnvId), var_env: EnvId, configurable: u8, - ) -> JsResult> { + ) -> JsResult { // Functions close over the code's own environment with ES2015's scoping, and over its // variable environment otherwise (ECMA-262 5.1 section 13). When that is the global // object's, they close over the global scope inside it, which also holds the scripts' @@ -4740,11 +4749,11 @@ impl Interp { self.declare(var_env, v, None, configurable)?; self.note_global_var(on_global, v)?; } - let mut annex_off = Vec::new(); + let mut annex_off = AnnexOff::new(); for v in &code.annex_vars { self.use_fuel()?; if !self.annex_var_declarable(v, env, var_env)? { - annex_off.push(v.clone()); + annex_off.insert(v.clone()); continue; } self.declare(var_env, v, None, configurable)?; diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs index b96bbafe79..9bcf7f274c 100644 --- a/crates/js/src/interp/async_function.rs +++ b/crates/js/src/interp/async_function.rs @@ -167,7 +167,7 @@ impl Interp { boundary: true, generator: None, async_promise: Some(a.promise), - annex_off: Vec::new(), + annex_off: super::AnnexOff::new(), chained: false, pending_module: false, }); diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 1347f30de8..b733f90093 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -1789,7 +1789,10 @@ impl<'s> Parser<'s> { let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); let line_break = self.tok.newline_before; let awaits = self.awaits; - let (args, trailing_comma) = self.arguments()?; + // The arguments of a possible async arrow function's head may be patterns + // such as `{a = 1}`; they are checked as expressions once no `=>` follows. + let mark = self.cover_inits.len(); + let (args, trailing_comma) = self.arguments(async_head)?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), @@ -1797,6 +1800,8 @@ impl<'s> Parser<'s> { }; if async_head && self.at(Punct::Arrow) { self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma }); + } else if async_head { + self.check_cover(mark)?; } } TokenKind::Punct(Punct::QuestionDot) => { @@ -1944,16 +1949,20 @@ impl<'s> Parser<'s> { } fn parse_arguments(&mut self) -> Result> { - Ok(self.arguments()?.0) + Ok(self.arguments(false)?.0) } - /// An argument list, and whether a comma follows its last argument. - fn arguments(&mut self) -> Result<(Vec, bool)> { + /// An argument list, and whether a comma follows its last argument. With `cover`, the + /// arguments may hold initializers such as `{a = 1}`, which the caller checks. + fn arguments(&mut self, cover: bool) -> Result<(Vec, bool)> { self.expect(Punct::LParen)?; let mut args = Vec::new(); let mut trailing_comma = false; if !self.at(Punct::RParen) { loop { + if cover { + self.cover_ok = true; + } args.push(self.parse_element()?); // A comma may follow the last argument (ECMAScript 2017, section 12.3). if !self.eat(Punct::Comma)? { diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index b645238366..4bb126f8c2 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -186,6 +186,10 @@ impl Parser<'_> { { let name = name.clone(); self.check_identifier(&self.tok, &name)?; + // A shorthand `await` counts as one in an async arrow function's head, as a name does. + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } let token = self.bump()?; let target = self.ast.push_expr(Expr::Ident(name.clone()), token.span); let value = if self.at(Punct::Eq) { diff --git a/docs/mcp.md b/docs/mcp.md index 32e36656fe..b0578e7415 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2941,13 +2941,14 @@ checks that read a target descriptor also throw `ReferenceError` for an uninitia The function returned as `Proxy.revocable(...).revoke` has an own empty-string `name` and a `length` of zero; both properties are nonwritable, nonenumerable and configurable. Its first call clears the revoker's reference to the proxy. Later calls return `undefined` without revoking another object. A -`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there +`.jsx` file and a `source` string run as scripts read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there; there `yield` is a name like any other. A `.js` file `.jsx` file and a `source` string read ES5.1 when run as scripts. With `module: true`, they run as modules and accept the ECMAScript 2015 forms listed here. A -`.js` file also has `Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a -named engine (`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later -run, as it keeps its globals. A `.js` file +`.js` file also has `Promise` (described below), and so does a `.jsx` file or a `source` string run with +`module: true`; a `.jsx` file and a `source` string run as scripts do not, except that a named engine +(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps +its globals. A `.js` file also reads two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)`), which give `undefined` and skip the rest of the chain when the value before `?.` is `undefined` or `null`, and `??`, which evaluates its right side only when its left side is `undefined` or `null`. Mixing `??` with `&&` @@ -3697,15 +3698,16 @@ has them only when a `.js` script started it, and then a later `.jsx` run in it In such a `.jsx` run, `Object.prototype.toString` gives the ES5.1 result, `[object Object]` or another class name, and does not read `Symbol.toStringTag`. -A `.js` script also reads async functions and `await` as ECMA-262 2017 section 25.5 defines them +A `.js` script, and a `.jsx` file or a `source` string run with `module: true`, also read async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is -reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. Outside an async -function `await` is an ordinary name, and in a `.jsx` file or a `source` string `async` and `await` are ordinary -names and an async function is a syntax error. These are VectorCraft's own rules: each time a function resumes +reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. In script code +outside an async function `await` is an ordinary name; module code does not accept `await` as a name. In a `.jsx` +file or a `source` string run as a script, `async` and `await` are ordinary names and an async function is a syntax +error. These are VectorCraft's own rules: each time a function resumes counts as a job and takes 1 unit of fuel, and a function still waiting when no job is left stays suspended, and the run ends. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fbc78947c8..665a8b06bc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1207,7 +1207,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. When the trap returns `true`, the call returns the proxy, and the proxy's prototype is whatever the trap left, which may be unchanged for an extensible target. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`. - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. `await` is an identifier outside async functions, and `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file; `.jsx` scripts and `source` strings do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From eb5e4c5eb7d0a4b5bbdea3e369373c0a23785192 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:32:22 -0800 Subject: [PATCH 39/41] Scripts: retrace and release refuse a tracing with locked traced artwork Retracing and releasing a tracing discard the objects its trace made, so both now throw "Cannot edit page item " when one of them is locked, with nothing changed. Added artwork is still reported first. The scan stops at the first added object and charges the objects it looked at to the run on both the success and refusal paths. --- crates/engine/src/script/dom/tracing.rs | 42 ++++++++++++------- crates/engine/src/tests/script_dom_tracing.rs | 29 +++++++++++++ docs/mcp.md | 3 +- 3 files changed, 58 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index a5b4ee561c..a37a062849 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -321,9 +321,11 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< }) } -/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make. +/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make, +/// and "Cannot edit page item" when it holds a locked object other than its source image, which +/// the replacement would discard. The objects looked at are charged to the run either way. fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { - read_group(h, item, |_, group| { + let (visited, result) = read_group(h, item, |_, group| { remember_source(h, item.doc.uid, group); // The objects the trace made, as the tracing records them; a tracing saved without that // record is checked against the objects it held when this run first saw it. @@ -333,20 +335,30 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { Some(_) => None, None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?), }; - let mut added = false; - group.walk(&mut |n| { - added |= n.id != group.id - && match (&made, ids) { - (Some(m), _) => !m.contains(n.id), - (None, Some(ids)) => !ids.contains(&n.id), - (None, None) => false, - }; - }); - if added { - return Err(HostError::Error(refusal.into())); + let source = group.children().and_then(|c| c.first()).map(|n| n.id); + let mut visited = 0u64; + let mut locked = None; + let mut todo: Vec<&Arc> = group.children().map(|c| c.iter().collect()).unwrap_or_default(); + while let Some(n) = todo.pop() { + visited += 1; + let added = match (&made, ids) { + (Some(m), _) => !m.contains(n.id), + (None, Some(ids)) => !ids.contains(&n.id), + (None, None) => false, + }; + // Added artwork is reported before a locked object, whichever comes first. + if added { + return Ok((visited, Err(HostError::Error(refusal.into())))); + } + if n.locked && Some(n.id) != source && locked.is_none() { + locked = Some(n.id); + } + todo.extend(n.children().into_iter().flatten()); } - Ok(()) - }) + Ok((visited, locked.map_or(Ok(()), |id| Err(HostError::Error(format!("Cannot edit page item {}", id.0)))))) + })?; + h.charge_call(visited)?; + result } /// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index ee3bb6a1b8..24223785dd 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1224,6 +1224,35 @@ fn release_refuses_added_artwork_before_changing_the_document() { let _ = std::fs::remove_dir_all(base); } +/// Retracing and releasing discard the objects the trace made, so both refuse a tracing that holds +/// a locked one, before the document changes. +#[test] +fn retrace_and_release_refuse_locked_traced_artwork() { + let base = folder("locked-traced-artwork"); + for action in ["p.tracing.tracingOptions.threshold = 90;", "p.tracing.releaseTracing();"] { + let (mut s, image) = session(&base, false); + let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let group = NodeId(r["id"].as_u64().unwrap()); + let made = s.active().unwrap().doc.node(group).unwrap().children().unwrap()[1].id; + s.edit("Lock traced artwork", |d, _| { + d.node_mut(made).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!("var p = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"), + ); + assert_eq!(out, [json!(format!("Cannot edit page item {}", made.0))], "{action}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{action}"); + assert_eq!(undo_steps(&s), steps, "{action}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// The `TracingOptions` and `TracingObject` members that are not implemented are left out of /// `hasOwnProperty` and `reflect`, and still throw when read. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 22b1c65c7c..378206435f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3270,7 +3270,8 @@ through `$`: and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws `Cannot retrace a tracing containing added artwork`, with nothing changed, when the tracing holds an object its trace did not make, whether this run, an earlier run or a command added it, and `releaseTracing()` throws - `Cannot release a tracing containing added artwork` in the same case. `imageTrace.make` records the objects it made in + `Cannot release a tracing containing added artwork` in the same case. When no object was added, both throw + `Cannot edit page item `, with nothing changed, when an object the trace made is locked. `imageTrace.make` records the objects it made in the tracing's `trace` settings as `made`, ranges of ids `[[first, last], ...]`, and a copy of the tracing records their copies. A tracing saved without `made` is checked only for objects added in the same run. `threshold` takes a whole number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest From 8aa51b123ed28e8d526d0b00a588611921e597eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:16:37 -0800 Subject: [PATCH 40/41] JS: assert the qualified name's value in the E4X async test CI's test-lint step failed on with_e4x_async_before_a_double_colon_is_a_qualified_name: both of its assertions only checked is_ok. The test now runs x.async::b with async bound to a Namespace and asserts that it selects the namespaced child. --- crates/js/src/async_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 711f883633..6438392335 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -121,7 +121,9 @@ fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_it fn with_e4x_async_before_a_double_colon_is_a_qualified_name() { let options = Options { es2017: true, e4x: true, ..Options::default() }; assert!(parse("async::b", &options).is_ok()); - assert!(parse("var x = ; x.async::b", &options).is_ok()); + let mut r = Realm::with_options(options, Limits::default()); + let src = "var async = new Namespace('u'); var x = 78; String(x.async::b)"; + assert_eq!(r.run(src), Ok(JsValue::String("7".into()))); } #[test] From 540d7d9673f08aede73a2327ee098880c78a7b50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:44:52 -0800 Subject: [PATCH 41/41] PDF/EPS/.ai import: store imported images with fast PNG compression Opening a PDF, EPS or .ai file with images re-encodes each image, and each image's opacity mask, as a PNG. Since the switch to the shared image codec these PNGs were written with the codec's default compression (deflate level 6) instead of fast compression. A PDF and an .ai file each holding one image opened about 50 ms and 105 ms slower than in 0.24.1. PDF import and the EPS and .ai readers now each encode through one helper that asks for PngCompression::Fast, the setting the SVG filter raster already uses. The pixels are unchanged. Tests check the zlib header of every PNG an import stores (RFC 1950 FLEVEL): PDF RGB, gray and image-mask images and a CMYK image's soft mask; a PostScript RGB image and a masked CMYK image's mask; and .ai RGB and Separation images with their masks, at full size and reduced. --- crates/eps/src/import.rs | 6 +++ crates/eps/src/import/ai/read/art.rs | 10 ++--- crates/eps/src/import/ai/tests.rs | 29 ++++++++++++++ crates/eps/src/import/data/ops.rs | 4 +- crates/eps/src/import/preview.rs | 2 +- crates/eps/src/import/tests.rs | 13 +++++++ crates/eps/src/import/tests_images.rs | 20 +++++++++- crates/pdf/src/import/builder.rs | 2 +- crates/pdf/src/import/state.rs | 12 ++++-- crates/pdf/src/tests/import_fidelity.rs | 52 ++++++++++++++++++++++++- 10 files changed, 136 insertions(+), 14 deletions(-) diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6c85414463..db310e0f01 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -135,6 +135,12 @@ pub struct Imported { pub preview: bool, } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(crate) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + /// The DSC comments the reader uses. #[derive(Debug, Default, PartialEq)] struct Dsc { diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 95606c9ebb..e0a46fccb0 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -648,7 +648,7 @@ impl<'a> Reader<'a> { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&img) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; @@ -678,7 +678,7 @@ impl<'a> Reader<'a> { } let written = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()); + .and_then(|img| crate::import::png(&img)); let Some(png) = written else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); @@ -778,7 +778,7 @@ impl<'a> Reader<'a> { }; craft_image_codecs::Image::from_raw(ow, oh, layout, craft_image_codecs::SampleType::U8, pixels) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()) + .and_then(|img| crate::import::png(&img)) .map(|png| ImageBlob::new("image/png", png)) }; // One that can't be encoded is left to the page's art, as one past the hard limits. @@ -870,7 +870,7 @@ impl<'a> Reader<'a> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); @@ -1224,7 +1224,7 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { } let raw = craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; Some((png, width, height)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9ef4cbc840..fe425346d2 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3154,6 +3154,35 @@ fn a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask() { assert!(r.doc.images[&im.key].gray_source().is_some_and(|g| !g.alpha), "no alpha in the pixels"); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with an alpha channel, and a Separation image with its opacity +/// mask, at full size and reduced to fit the limits. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let pngs = |doc: &Document| { + let fast = |n: &Node| { + let NodeKind::Image(im) = &n.kind else { panic!("{:?}", n.kind) }; + let blob = &doc.images[&im.key]; + assert_eq!(blob.mime, "image/png"); + crate::import::tests::fastest_png(&blob.bytes) + }; + let a = art(doc); + let mut out = vec![fast(&a[0])]; + out.extend(a[0].extras().mask.as_ref().map(|m| fast(&m.art))); + out + }; + let rgb = image("[ 10 0 0 10 50 90 ]", (2, 1), ("DeviceRGB", 3, 1), &[255, 0, 0, 0, 255, 0, 255, 128], 10); + assert_eq!(pngs(&read(&rgb).unwrap().doc), [true], "the RGB image"); + let black = "1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation]"; + let ink = ink_image(black, 8, 1, 2, &[0, 255, 255, 64]); + assert_eq!(pngs(&read(&ink).unwrap().doc), [true, true], "the Separation image and its mask"); + let samples = [255u8; 16].iter().chain([0u8; 16].iter()).copied().collect::>(); + let ink = ink_image(black, 8, 1, 16, &samples); + let r = super::with_image_limits(4, 1 << 31, 512 << 20, || read(&ink).unwrap()); + assert!(r.warnings.iter().any(|w| w.contains("was reduced")), "{:?}", r.warnings); + assert_eq!(pngs(&r.doc), [true, true], "the reduced Separation image and its mask"); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index e9bf596eb3..c27dc3c3c6 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -1157,7 +1157,7 @@ impl Interp<'_> { else { return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&rgba, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&rgba) else { self.out.warn("an image that couldn't be read was left out"); return Ok(()); }; @@ -1184,7 +1184,7 @@ impl Interp<'_> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.out.doc.images.entry(key.clone()).or_insert(blob); diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index 36c0e5662c..87037fcd1a 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -46,7 +46,7 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option { } let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::png(&raw)?; let mut doc = Document::new(frame.width(), frame.height()); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 011cb86ce3..f920a1c364 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -208,6 +208,19 @@ fn arrays_and_dictionaries_holding_themselves_are_freed() { } } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +pub(super) fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + /// The objects of the document's layer. pub(super) fn objects(d: &Document) -> Vec> { d.layers[0].children().unwrap().clone() diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index e7fd734240..87a7560bfd 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ImageBlob, Node, NodeKind}; use super::import; -use super::tests::{all, eps, read}; +use super::tests::{all, eps, fastest_png, read}; use super::tests_generators::pixel; /// Each pixel of the first image, row by row. @@ -223,6 +223,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(first_image(&r).extras().mask.is_none()); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image, and the opacity mask of a masked CMYK image. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let r = read("30 20 scale 3 2 8 [3 0 0 -2 0 2] <00ff00405060> <0000ff708090> true 3 colorimage"); + let b = blob(&r, &first_image(&r)); + assert_eq!(b.mime, "image/png"); + assert!(fastest_png(&b.bytes), "the RGB image"); + let r = read( + "/DeviceCMYK setcolorspace 30 20 scale << /ImageType 4 /Width 2 /Height 1 /BitsPerComponent 8 /Decode [0 1 0 1 0 1 0 1] \ + /ImageMatrix [2 0 0 -1 0 1] /DataSource <0a141e28 00667f08> /MaskColor [10 20 30 40] >> image", + ); + let n = first_image(&r); + let mask = blob(&r, &n.extras().mask.as_ref().expect("an opacity mask").art); + assert_eq!(mask.mime, "image/png"); + assert!(fastest_png(&mask.bytes), "the opacity mask"); +} + /// A CMYK JPEG gives its samples as stored, for the Decode array to read: Adobe's inverted /// samples with `[1 0 1 0 1 0 1 0]`, the ink amounts themselves with `[0 1 0 1 0 1 0 1]`. #[test] diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0cfb8ea805..64da7fb8d5 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -1098,7 +1098,7 @@ impl<'p> Builder<'p> { a.data, ) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::state::png(&raw)?; let blob = ImageBlob::new("image/png", png); let k = blob.content_key(); self.images.insert(k.clone(), blob); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 629113680c..c85f36bd7f 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -378,19 +378,25 @@ pub(super) fn bounds(nodes: &[Arc]) -> Option { nodes.iter().try_fold(None, |acc, n| n.visual_bounds().map(|b| Some(acc.map_or(b, |a: Rect| a.union(b)))))? } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(super) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + pub(super) fn rgba_png(rgba: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn rgb_png(rgb: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn gray_png(gray: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec { diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 5fdafeb5fc..731f18ff06 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, ImageBlob, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; use vectorcraft_geom::{Rect, shapes}; use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; @@ -147,6 +147,56 @@ fn a_luminosity_soft_mask_of_an_image_keeps_the_images_colour() { assert_eq!(mask_image_pixels("Luminosity"), [[0, 0, 0, 255], [0, 0, 0, 0]]); } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with a soft mask, the soft mask of a CMYK image as its opacity +/// mask, a gray image and an image mask painted in a color. +#[test] +fn imported_images_are_stored_with_fast_compression() { + let g = first_extra(1); + let image = |space: &str, data: &str| { + stream( + &format!( + "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /{space} /BitsPerComponent 8 /Filter /ASCIIHexDecode /SMask {} 0 R", + g + 4 + ), + data, + ) + }; + let rgb = image("DeviceRGB", "FF000000FF00>"); + let cmyk = image("DeviceCMYK", "0A141E28 00667F08>"); + let gray = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "2080>"); + let stencil = stream("/Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode", "F0>"); + let smask = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "FF40>"); + let bytes = one_page( + "q 40 0 0 40 0 0 cm /Im0 Do Q q 40 0 0 40 50 0 cm /Im1 Do Q q 40 0 0 40 0 50 cm /Im2 Do Q 0 0 1 rg q 40 0 0 40 50 50 cm /Im3 Do Q", + &format!("/XObject << /Im0 {g} 0 R /Im1 {} 0 R /Im2 {} 0 R /Im3 {} 0 R >>", g + 1, g + 2, g + 3), + &[&rgb, &cmyk, &gray, &stencil, &smask], + ); + let d = open(&bytes); + let masks = all(&d).iter().filter(|n| n.extras().mask.is_some()).count(); + assert_eq!(masks, 1, "the CMYK image's soft mask as an opacity mask"); + let pngs: Vec<&ImageBlob> = d.images.values().filter(|b| b.mime == "image/png").collect(); + assert_eq!(pngs.len(), 4, "the RGB image, the CMYK image's mask, the gray image and the image mask: {:?}", d.images.keys()); + for b in pngs { + assert!(fastest_png(&b.bytes), "{:?}", &b.bytes[..b.bytes.len().min(48)]); + } +} + #[test] fn a_luminosity_soft_mask_becomes_an_opacity_mask() { let d = open(&masked("/S /Luminosity", "1 1 1 rg 0 0 50 100 re f"));