From fed96731e242d9df4286b258acb1fcd03ea07637 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:10:20 -0800 Subject: [PATCH 01/30] 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/30] 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/30] 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/30] 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/30] 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/30] 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/30] 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/30] 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/30] 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 81a2dea0a44ef212a2885a93396bb0b1fbaccce2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:27:11 -0800 Subject: [PATCH 10/30] 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 d6bb6429f4abf4a48df27d505e33741d05846db2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:11:19 -0800 Subject: [PATCH 11/30] 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 12/30] 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 13/30] 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 14/30] 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 15/30] 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 16/30] 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 17/30] 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 18/30] 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 19/30] 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 20/30] 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 21/30] 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 22/30] 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 23/30] 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 24/30] 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 25/30] 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 26/30] 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 27/30] 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 28/30] 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 29/30] 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 eb5e4c5eb7d0a4b5bbdea3e369373c0a23785192 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:32:22 -0800 Subject: [PATCH 30/30] 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