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`.