From 75cb9572678ceb7e142754e5fbd21db0f071b1eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 16:02:13 -0800 Subject: [PATCH 01/22] Scripts: Document.rasterize and Document.imageCapture with their option classes Document.rasterize(sourceArt, clipBounds?, options?) replaces one page item or a list of them with an embedded image in one undo step and gives the new RasterItem; the source objects go stale. Document.imageCapture( imageFile, clipBounds?, options?) writes a PNG of all the visible art, on the artboards or off them, or of the area clipBounds names. new RasterizeOptions() and new ImageCaptureOptions() start with the defaults the help pages give, and the enumerations AntiAliasingMethod and RasterizationColorModel hold their values. Every option goes to the command explicitly, so the document's raster effects settings do not change the result. object.rasterize takes ids, to rasterize those objects instead of the selection while keeping the selection less the replaced art, and clipBounds, which cuts the image to a rectangle that must reach the art itself. Its result adds imageId, the image inside the clip group when clippingMask makes one. VectorCraft's own rules: clipBounds is [left, top, right, bottom] in the script's coordinates and is never reordered; imageCapture writes a PNG and needs a .png name; transparency wins over backgroundBlack and over matte; padding takes 0 to 1,000 points and both resolutions 72 to 2400 ppi; an image over 64 megapixels or 32,768 pixels a side throws before anything is drawn. imageCapture writes only where the script's File objects may, and never over an open document's file or a file one of them links, wherever the linking image or placed document is stored. convertSpotColors, convertTextToOutlines and includeLayers set to true, and Document.windowCapture, throw an error that says they are not available yet. --- crates/engine/src/cmd/links.rs | 12 + crates/engine/src/cmd/menucmds.rs | 75 ++- crates/engine/src/script/dom.rs | 5 +- .../engine/src/script/dom/raster_capture.rs | 388 +++++++++++++ crates/engine/src/tests.rs | 1 + .../engine/src/tests/script_raster_capture.rs | 537 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 8 + docs/mcp.md | 34 ++ docs/target-app-parity.md | 1 + 9 files changed, 1053 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/script/dom/raster_capture.rs create mode 100644 crates/engine/src/tests/script_raster_capture.rs diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 29da4d0524..febe0946de 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -194,6 +194,18 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } +/// The link of every linked image and placed document of `d`, wherever it is stored, brush art +/// included, with the plate files of an image placed from a DCS file. +pub(crate) fn linked_files_with_plates(d: &Document) -> Vec<(LinkInfo, Vec)> { + groups(d, None) + .into_iter() + .map(|g| { + let plates = g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&g.link.path, &f.name)).collect(); + (g.link, plates) + }) + .collect() +} + /// The linked images and placed documents of `d` by file and content, wherever they are stored /// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object /// visited before it has (art being edited on a layer and its definition) counts once, by its diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index aa330e11ea..f339f7b96f 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, none inside another, each unlocked in unlocked layers and groups; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -894,7 +894,21 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p .collect(); // What the art draws, its geometry effects applied. let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); - let b = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?.inflate(pad, pad); + let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; + let mut b = drawn.inflate(pad, pad); + if let Some(v) = p.get("clipBounds").filter(|v| !v.is_null()) { + let [x0, y0, x1, y1] = super::finite_numbers::<4>(v).ok_or_else(|| bad(cmd, "clipBounds must be four finite numbers [x0, y0, x1, y1]"))?; + if x1 <= x0 || y1 <= y0 { + return Err(bad(cmd, "clipBounds must have x1 greater than x0 and y1 greater than y0")); + } + let clip_rect = Rect::new(x0, y0, x1, y1); + // The rectangle must reach the art itself, not only the padding around it. + let on_art = drawn.intersect(clip_rect); + if on_art.width() <= 0.0 || on_art.height() <= 0.0 { + return Err(bad(cmd, "clipBounds does not overlap the art")); + } + b = b.intersect(clip_rect); + } let scale = ppi / 72.0; // Snap to whole pixels. let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); @@ -934,9 +948,51 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p Ok(Rasterized { blob, alpha, width: img.width, height: img.height, xf, clip, warning }) } +/// The objects `ids` names for Rasterize, in paint order: each an object of the active document, +/// listed once, none inside another listed one, and neither it nor a layer or group it is in +/// locked. +fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { + let ids = super::checked_ids_param(s, p, "ids", cmd)?; + let d = &s.doc()?.doc; + let mut listed = HashSet::with_capacity(ids.len()); + for id in &ids { + if !listed.insert(*id) { + return Err(bad(cmd, format!("id {} is listed twice", id.0))); + } + } + for id in &ids { + // The layers and groups from the top down to the object itself. + let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; + if d.node(*id).is_some_and(|n| n.is_layer()) { + return Err(bad(cmd, format!("id {} is a layer, not an object", id.0))); + } + let parent = up.len().checked_sub(2).and_then(|i| d.node(up[i])); + if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { + return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); + } + if let Some(outer) = up.iter().find(|a| *a != id && listed.contains(*a)) { + return Err(bad(cmd, format!("id {} is inside id {}, which is listed too", id.0, outer.0))); + } + if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { + return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); + } + } + Ok(vectorcraft_doc::Selection { objects: ids, ..Default::default() }.in_paint_order(d)) +} + +/// The id of the image in `node`, the node Rasterize makes: the image itself, or the image in its +/// clip group. +fn image_in(node: &Node) -> NodeId { + match &node.kind { + NodeKind::Group { children, .. } => children.iter().find(|c| matches!(c.kind, NodeKind::Image(_))).map_or(node.id, |c| c.id), + _ => node.id, + } +} + fn rasterize(s: &mut Session, p: &Value) -> Result { const C: &str = "object.rasterize"; - let roots = selected_roots(s)?; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = if given { rasterize_sources(s, p, C)? } else { selected_roots(s)? }; let st = s.doc()?; let nodes: Vec = roots.iter().filter_map(|id| st.doc.node(*id).cloned()).collect(); let image = rasterize_art(&st.doc, nodes, p, C, true)?; @@ -944,16 +1000,21 @@ fn rasterize(s: &mut Session, p: &Value) -> Result { if roots.is_empty() { return Err(bad(C, "nothing selected")); } - let id = s.edit("Rasterize", |d, sel| { + let (id, image_id) = s.edit("Rasterize", |d, sel| { let threaded = super::threads::frames(d); let node = image.into_node(d); + let image_id = image_in(&node); let id = d.wrap(&roots, |_| node)?; // Rasterized frames of threaded text leave their threads with the text they show. super::threads::leave_threads(d, &threaded); - sel.set([id]); - Ok(id) + if given { + sel.prune(d); + } else { + sel.set([id]); + } + Ok((id, image_id)) })?; - let mut out = json!({ "id": id.0, "width": w, "height": h }); + let mut out = json!({ "id": id.0, "imageId": image_id.0, "width": w, "height": h }); if let Some(w) = warning { out["warning"] = json!(w); } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e6252bd774..478dbca2c5 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 raster_capture; mod save_open; /// The error for a member read or called with no document open. @@ -1813,7 +1814,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(raster_capture::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1876,6 +1877,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(raster_capture::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1941,6 +1943,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); classes.extend(save_open::classes(l)); + classes.extend(raster_capture::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/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs new file mode 100644 index 0000000000..a75f1a1c4a --- /dev/null +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -0,0 +1,388 @@ +//! Rasterizing art and capturing it as an image in the script object model: `Document.rasterize`, +//! `Document.imageCapture` and their option classes, as the help pages +//! , +//! , +//! and +//! describe. +//! +//! `rasterize` runs `object.rasterize` with the source art's ids, and `imageCapture` runs +//! `document.export` of an area of the page, inside the run's transaction. Every option is given to +//! the command, at the help page's default when the script leaves it out, so the document's raster +//! effects settings do not change the result. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as +//! `geometricBounds` gives them; the right edge must be right of the left one and the bottom edge +//! below the top one, and the numbers are never swapped. +//! - `rasterize` takes one page item or a list of at most [`super::MAX_LISTED`] of them, all of +//! this document, none listed twice, inside another listed one or a path of a compound path, and +//! none locked or in a locked layer or group. It keeps the selection, less the art it replaces, +//! and gives the new `RasterItem`: with `clippingMask`, the image inside its clip group. +//! `transparency` wins over `backgroundBlack`. `convertSpotColors`, `convertTextToOutlines` and +//! `includeLayers` true throw an error that says they are not available yet. +//! - `imageCapture` writes a PNG, and the file's name must end with `.png`. Without `clipBounds` it +//! captures the bounds of all the visible art, on the artboards or off them. With +//! `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with +//! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 +//! to 255. The file is written only where the script's `File` objects may write, and never over +//! an open document's file or a file one of them links. +//! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is +//! drawn; the resolution is never lowered to make it fit. +//! - `windowCapture` throws an error that says it is not available yet. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_geom::Rect; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; + +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, command, coordinate, current, frame, given, item_of, item_ref, later, method, + named, num, on_doc, text, this_doc, with_doc, +}; + +/// The lowest resolution the option classes take, in pixels per inch. +pub const MIN_RESOLUTION: f64 = 72.0; +/// The highest resolution the option classes take, in pixels per inch. +pub const MAX_RESOLUTION: f64 = 2400.0; +/// The most room `RasterizeOptions.padding` adds around the art, in points. +pub const MAX_PADDING: f64 = 1000.0; +/// The error of a source art object from another document. +pub const OTHER_DOCUMENT: &str = "The source art must be in this document"; + +/// The enumerations these members use, as `dom`'s are made. +pub(super) const ENUMS: &[(&str, &[&str])] = + &[("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]), ("RasterizationColorModel", &["BITMAP", "DEFAULTCOLORMODEL", "GRAYSCALE"])]; + +/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`). +fn member<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> { + let members = ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m); + let bad = || HostError::Type(format!("{what} must be a {enumeration} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?; + if members.contains(&m) { Ok(m) } else { Err(bad()) } +} + +/// A finite number from `lo` to `hi`. +fn number_in(d: &Data, what: &str, lo: f64, hi: f64) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => { + if (lo..=hi).contains(n) { + Ok(*n) + } else { + Err(HostError::Range(format!("{what} must be from {lo} to {hi}"))) + } + } + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// The fields of the options object `d` of `class`, or `None` when the script gave none. +fn options<'a>(d: &'a Data, class: &str) -> std::result::Result, HostError> { + match given(d) { + None | Some(Data::Null) => Ok(None), + Some(Data::Object(items)) if items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class)) => Ok(Some(items)), + Some(_) => Err(HostError::Type(format!("the options must be a {class} object"))), + } +} + +/// `clipBounds`, `[left, top, right, bottom]` in the run's script coordinates, as a rectangle in +/// document coordinates; `None` when the script gave none. +fn clip_bounds(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let a = match given(d) { + None | Some(Data::Null) => return Ok(None), + Some(Data::Array(a)) if a.len() == 4 => a, + Some(_) => return Err(HostError::Type("clipBounds must be an array of four numbers [left, top, right, bottom]".into())), + }; + let mut n = [0.0; 4]; + for (o, d) in n.iter_mut().zip(a) { + *o = coordinate(d, "clipBounds")?; + } + let f = with_doc(h, doc, |_, st| frame(st))?; + let c = h.dom.coords.get(); + let (p0, p1) = (f.to_document(c, [n[0], n[1]]), f.to_document(c, [n[2], n[3]])); + if p1.x <= p0.x || p1.y <= p0.y { + return Err(HostError::Range("clipBounds must have its right edge right of its left edge and its bottom edge below its top edge".into())); + } + Ok(Some(Rect::new(p0.x, p0.y, p1.x, p1.y))) +} + +/// Throws when an image of `region` at `ppi` would be more than 64 megapixels or longer than the +/// renderer draws on a side, before anything is drawn. +fn check_size(region: Rect, ppi: f64) -> std::result::Result<(), HostError> { + let scale = ppi / 72.0; + let (w, h) = ((region.width() * scale).round().max(1.0), (region.height() * scale).round().max(1.0)); + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if w * h > crate::cmd::menucmds::MAX_PIXELS || w > side || h > side { + return Err(HostError::Range(format!( + "the image would be {w} × {h} pixels; images are limited to 64 megapixels and {side} pixels a side: lower the resolution or the bounds" + ))); + } + Ok(()) +} + +// ---- Rasterize ---- + +/// `object.rasterize`'s params for the `RasterizeOptions` fields `items` (`None`: the defaults), +/// with every option given. +fn rasterize_params(items: Option<&[(String, Data)]>) -> std::result::Result, HostError> { + let (mut anti_alias, mut black, mut clear, mut clip, mut model, mut padding, mut ppi) = ("art", false, false, false, "document", 0.0, 300.0); + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("RasterizeOptions.{k}"); + match k.as_str() { + "antiAliasingMethod" => { + anti_alias = match member(v, "AntiAliasingMethod", &what)? { + "None" => "none", + "TYPEOPTIMIZED" => "type", + _ => "art", + } + } + "backgroundBlack" => black = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "clippingMask" => clip = boolean(v, &what)?, + "colorModel" => { + model = match member(v, "RasterizationColorModel", &what)? { + "BITMAP" => "bitmap", + "GRAYSCALE" => "grayscale", + _ => "document", + } + } + "padding" => padding = number_in(v, &what, 0.0, MAX_PADDING)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "convertSpotColors" | "convertTextToOutlines" | "includeLayers" if boolean(v, &what)? => { + return Err(HostError::Error(format!("{what} is not available yet"))); + } + _ => {} + } + } + let background = if clear { + "transparent" + } else if black { + "black" + } else { + "white" + }; + let mut p = Map::new(); + p.insert("ppi".into(), json!(ppi)); + p.insert("background".into(), json!(background)); + p.insert("antiAlias".into(), json!(anti_alias)); + p.insert("padding".into(), json!(padding)); + p.insert("colorModel".into(), json!(model)); + p.insert("clippingMask".into(), json!(clip)); + Ok(p) +} + +/// The ids of the source art `d` names for `rasterize` in the document `doc`: one page item, or a +/// list of them. The command checks that none is listed twice, inside another or locked. +fn sources(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match d { + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("rasterize takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + Data::Undefined | Data::Null => return Err(HostError::Type("rasterize needs the source art, a page item or a list of them".into())), + d => vec![d], + }; + if list.is_empty() { + return Err(HostError::Error("rasterize needs at least one page item".into())); + } + h.charge_call(16 * list.len() as u64)?; + let mut ids = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error(OTHER_DOCUMENT.into())); + } + ids.push(item.id.0); + } + Ok(ids) +} + +/// `document.rasterize(sourceArt, clipBounds?, options?)`: `object.rasterize` of the source art, +/// which the image replaces in one undo step. → the new `RasterItem`. +fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = sources(h, doc, arg(a, 1))?; + let clip = clip_bounds(h, doc, arg(a, 2))?; + let mut p = rasterize_params(options(arg(a, 3), "RasterizeOptions")?)?; + p.insert("ids".into(), json!(ids)); + if let Some(r) = clip { + p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); + } + let r = on_doc(h, doc.uid, true, |h| command(h, "object.rasterize", &Value::Object(p)))?; + let image = match &r { + Data::Object(o) => o.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("imageId", Data::Number(n)) => super::whole(*n), + _ => None, + }), + _ => None, + }; + let image = image.ok_or_else(|| HostError::Error("the image was not made".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(item_ref(h, st, crate::NodeId(image))) +} + +// ---- Image capture ---- + +/// A channel of `matteColor`: a finite number from 0 to 255. +fn channel(items: &[(String, Data)], key: &str) -> std::result::Result { + let d = items.iter().find(|(k, _)| k == key).map_or(&Data::Undefined, |(_, v)| v); + let n = number_in(d, &format!("ImageCaptureOptions.matteColor.{key}"), 0.0, 255.0)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = n.round() as u8; + Ok(byte) +} + +/// The capture's resolution and `document.export`'s `background` and `antiAlias` for the +/// `ImageCaptureOptions` fields `items` (`None`: the defaults). +fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f64, String, &'static str), HostError> { + let (mut anti_alias, mut matte, mut clear, mut ppi) = (false, false, false, 150.0); + let mut color = [255u8; 3]; + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("ImageCaptureOptions.{k}"); + match k.as_str() { + "antiAliasing" => anti_alias = boolean(v, &what)?, + "matte" => matte = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "matteColor" => { + let Data::Object(c) = v else { return Err(HostError::Type(format!("{what} must be an RGBColor"))) }; + color = [channel(c, "red")?, channel(c, "green")?, channel(c, "blue")?]; + } + _ => {} + } + } + let background = if clear { + "transparent".to_string() + } else if matte { + format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2]) + } else { + "white".to_string() + }; + Ok((ppi, background, if anti_alias { "art" } else { "none" })) +} + +/// The files a capture must not write over: the open documents' files and the files their linked +/// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns +/// and brushes included), with a DCS image's plate files, by their real paths. A link's stored path +/// and its relative path are each taken from its document's folder, as opening the document reads +/// them. +fn sources_on_disk(h: &Host) -> Vec { + let s = h.session.borrow(); + let mut paths: Vec = Vec::new(); + for st in s.documents() { + paths.extend(st.path.clone()); + let document = st.path.as_deref(); + for (link, plates) in crate::cmd::links::linked_files_with_plates(&st.doc) { + for stored in std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).chain(plates.iter().map(String::as_str)) { + if std::path::Path::new(stored).is_absolute() { + paths.push(stored.to_string()); + } + paths.extend(crate::cmd::fileio::document_path(stored, document).ok()); + } + } + } + paths.iter().filter_map(|p| std::fs::canonicalize(p).ok()).collect() +} + +/// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the +/// art inside `clipBounds`, or of all the visible art. +fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = vectorcraft_js::file_ref_path(arg(a, 1)).ok_or_else(|| HostError::Type("imageCapture needs a File".into()))?; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); + if !name.ends_with(".png") || name.len() <= ".png".len() { + return Err(HostError::Error("imageCapture writes a PNG file: give it a name that ends with .png".into())); + } + let clip = clip_bounds(h, doc, arg(a, 2))?; + let (ppi, background, anti_alias) = capture_settings(options(arg(a, 3), "ImageCaptureOptions")?)?; + let region = match clip { + Some(r) => r, + None => with_doc(h, doc, |_, st| crate::cmd::fileio::export_art_bounds(&st.doc, "png")) + .ok_or_else(|| HostError::Error("the document has no visible art to capture".into()))?, + }; + check_size(region, ppi)?; + let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; + let canonical = std::fs::canonicalize(&real).ok(); + if canonical.is_some_and(|c| sources_on_disk(h).contains(&c)) { + return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); + } + let p = json!({ + "path": crate::cmd::findfiles::plain(real).to_string_lossy(), + "format": "png", + "rect": [region.x0, region.y0, region.width(), region.height()], + "ppi": ppi, + "background": background, + "antiAlias": anti_alias, + "includeArtboardFill": false, + }); + h.disk.borrow_mut().exact = true; + let r = on_doc(h, doc.uid, false, |h| command(h, "document.export", &p)); + h.disk.borrow_mut().exact = false; + r?; + Ok(Data::Undefined) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + let mut members = named(vec![("rasterize", method(l, doc_rasterize)), ("imageCapture", method(l, doc_image_capture))]); + members.push(later(l, "Document", "windowCapture")); + members +} + +/// The fields a new options object starts with. +type Starts = fn() -> Vec<(&'static str, Data)>; + +fn rasterize_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasingMethod", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("backgroundBlack", Data::Bool(false)), + ("clippingMask", Data::Bool(false)), + ("colorModel", text("RasterizationColorModel.DEFAULTCOLORMODEL")), + ("convertSpotColors", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("includeLayers", Data::Bool(false)), + ("padding", num(0.0)), + ("resolution", num(300.0)), + ("transparency", Data::Bool(false)), + ] +} + +fn capture_starts() -> Vec<(&'static str, Data)> { + let white = Data::Object(vec![ + ("typename".to_string(), text("RGBColor")), + ("red".to_string(), num(255.0)), + ("green".to_string(), num(255.0)), + ("blue".to_string(), num(255.0)), + ]); + vec![ + ("antiAliasing", Data::Bool(false)), + ("matte", Data::Bool(false)), + ("matteColor", white), + ("resolution", num(150.0)), + ("transparency", Data::Bool(false)), + ] +} + +/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its +/// help page gives. +pub(super) fn classes(link: &Link) -> Vec { + let all: [(&'static str, Starts); 2] = [("RasterizeOptions", rasterize_starts), ("ImageCaptureOptions", capture_starts)]; + all.into_iter() + .map(|(name, starts)| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + let mut items = vec![("typename".to_string(), text(name))]; + items.extend(starts().into_iter().map(|(k, v)| (k.to_string(), v))); + Ok(Data::Object(items)) + }); + HostClass { name: name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + }) + .collect() +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b2db53b71f..d808439701 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_raster_capture; mod script_run; mod script_save_open; mod scripts; diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs new file mode 100644 index 0000000000..3385c4dd5c --- /dev/null +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -0,0 +1,537 @@ +//! Rasterizing and capturing art from a script: `Document.rasterize`, `Document.imageCapture`, +//! `RasterizeOptions`, `ImageCaptureOptions` and `object.rasterize` with `ids` and `clipBounds`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// Fills the objects `ids` with `color` and takes their strokes off. +fn paint(s: &mut Session, ids: &[NodeId], color: &str) { + let ids: Vec = ids.iter().map(|i| i.0).collect(); + s.execute("paint.setFill", &json!({"ids": ids, "color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": ids, "none": true})).unwrap(); +} + +/// A 400 × 300 pt document with two rectangles without strokes: `a` at (10, 20) 30 × 40 pt, `b` at +/// (100, 100) 50 × 50 pt. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + paint(&mut s, &[a, b], "#ff0000"); + s.execute("select.none", &json!({})).unwrap(); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The size of each embedded image of the active document, in pixels. +fn images(s: &Session) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(i) = &n.kind { + out.push((i.width, i.height)); + } + }); + out +} + +/// A script that selects `b` and rasterizes `a` (the first and second page items). +const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[0], b = d.pageItems[1]; b.name = 'b'; d.selection = [b];"; + +#[test] +fn script_rasterize_explicit_sources_preserves_selection() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); vc.log(d.selection.length); vc.log(d.selection[0].name === 'b');\ + try {{ a.name; }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);" + ), + ); + assert_eq!(out, [json!("RasterItem"), json!(1), json!(true), json!("Stale page item"), json!(2)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + assert_eq!(st.selection.objects, vec![b], "the selection stays as it was"); + assert_eq!(undo_steps(&s), undo + 1, "one undo step"); +} + +#[test] +fn script_rasterize_defaults_override_document_raster_settings() { + let (mut s, ..) = doc(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72, "background": "transparent"})).unwrap(); + log(&mut s, &format!("{RASTERIZE_A} d.rasterize(a);")); + // 30 × 40 pt at 300 ppi, snapped out to whole pixels (at 72 ppi it would be about 30 × 40). + let [(w, h)] = images(&s)[..] else { panic!("one image: {:?}", images(&s)) }; + assert!((125..=126).contains(&w) && (167..=168).contains(&h), "300 ppi, the help page's default, not the document's 72: {w} × {h}"); + let (mut s, ..) = doc(); + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 144; o.padding = 5; d.rasterize(a, undefined, o);")); + assert_eq!(images(&s), vec![(80, 100)], "40 × 50 pt with the padding, at 144 ppi"); +} + +#[test] +fn script_rasterize_options_have_the_help_page_defaults() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var o = new RasterizeOptions(); vc.log([o.typename, o.antiAliasingMethod, o.backgroundBlack, o.clippingMask, o.colorModel, \ + o.convertSpotColors, o.convertTextToOutlines, o.includeLayers, o.padding, o.resolution, o.transparency]);\ + var c = new ImageCaptureOptions(); vc.log([c.typename, c.antiAliasing, c.matte, c.matteColor.red, c.matteColor.green, \ + c.matteColor.blue, c.resolution, c.transparency]); vc.log([AntiAliasingMethod.TYPEOPTIMIZED, RasterizationColorModel.BITMAP]);", + ); + let rasterize = json!([ + "RasterizeOptions", + "AntiAliasingMethod.ARTOPTIMIZED", + false, + false, + "RasterizationColorModel.DEFAULTCOLORMODEL", + false, + false, + false, + 0, + 300, + false + ]); + assert_eq!(out[0], rasterize); + assert_eq!(out[1], json!(["ImageCaptureOptions", false, false, 255, 255, 255, 150, false])); + assert_eq!(out[2], json!(["AntiAliasingMethod.TYPEOPTIMIZED", "RasterizationColorModel.BITMAP"])); +} + +#[test] +fn script_rasterize_clip_mask_returns_image_child() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.clippingMask = true; var r = d.rasterize([a], null, o); vc.log([r.typename, r.parent.typename]);" + ), + ); + assert_eq!(out, [json!(["RasterItem", "GroupItem"])]); +} + +#[test] +fn script_rasterize_clip_bounds_cut_the_image() { + let (mut s, ..) = doc(); + // The left half of `a`: x 10 to 25, and its whole height (y 280 to 240, Y up). + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; d.rasterize(a, [10, 280, 25, 240], o);")); + assert_eq!(images(&s), vec![(15, 40)]); +} + +#[test] +fn script_rasterize_disposes_several_sources_in_one_step() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log(&mut s, "var d = app.activeDocument; var r = d.rasterize([d.pageItems[1], d.pageItems[0]]); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(1)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none() && st.doc.node(b).is_none()); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// Each bad call throws and leaves the document as it was, with no undo step. +fn refused(s: &mut Session, source: &str, message: &str) { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(s); + let e = failure(s, source); + assert!(e.contains(message), "{source}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc) || *before == *s.active().unwrap().doc, "{source} changed the document"); + assert_eq!(undo_steps(s), undo, "{source} added an undo step"); +} + +#[test] +fn script_rasterize_rejects_other_documents_art() { + let (mut s, ..) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 10.0, 10.0); + refused(&mut s, "app.documents[0].rasterize(app.documents[1].pageItems[0]);", "The source art must be in this document"); +} + +#[test] +fn script_rasterize_rejects_listed_twice() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[0]]);", "listed twice"); +} + +#[test] +fn script_rasterize_rejects_locked_art() { + let (mut s, ..) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].locked = true;"); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); +} + +#[test] +fn script_rasterize_rejects_art_inside_listed_art() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[1]]);", "which is listed too"); +} + +#[test] +fn script_rasterize_rejects_a_compound_path_member() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The page items are the compound path, then its two paths. + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[1]);", "part of a compound path"); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);"); + assert_eq!(out, [json!("RasterItem")], "the compound path itself is rasterized"); +} + +#[test] +fn script_rasterize_rejects_stale_and_missing_sources() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument, a = d.pageItems[0]; a.remove(); d.rasterize(a);", "Stale page item"); + refused(&mut s, "app.activeDocument.rasterize([]);", "at least one page item"); + refused(&mut s, "app.activeDocument.rasterize();", "needs the source art"); + refused(&mut s, "app.activeDocument.rasterize(5);", "not a page item"); + let many = "var d = app.activeDocument, l = []; for (var i = 0; i < 10001; i++) l.push(d.pageItems[0]); d.rasterize(l);"; + refused(&mut s, many, "at most 10000 objects"); +} + +#[test] +fn script_rasterize_rejects_bad_options() { + let (mut s, ..) = doc(); + let cases = [ + ("var o = new RasterizeOptions(); o.resolution = 71;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = 2401;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = NaN;", "finite number"), + ("var o = new RasterizeOptions(); o.resolution = Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.padding = 1001;", "from 0 to 1000"), + ("var o = new RasterizeOptions(); o.padding = -Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.antiAliasingMethod = 'smooth';", "AntiAliasingMethod value"), + ("var o = new RasterizeOptions(); o.colorModel = AntiAliasingMethod.None;", "RasterizationColorModel value"), + ("var o = new RasterizeOptions(); o.clippingMask = 1;", "true or false"), + ("var o = new RasterizeOptions(); o.convertTextToOutlines = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.includeLayers = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.convertSpotColors = true;", "not available yet"), + ("var o = new ImageCaptureOptions();", "RasterizeOptions object"), + ("var o = {resolution: 300};", "RasterizeOptions object"), + ]; + for (options, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; {options} d.rasterize(d.pageItems[0], undefined, o);"), message); + } +} + +#[test] +fn script_rasterize_rejects_bad_clip_bounds() { + let (mut s, ..) = doc(); + let cases = [ + ("[25, 280, 10, 240]", "right edge right of its left edge"), + ("[10, 240, 25, 280]", "bottom edge below its top edge"), + ("[10, 280, 25]", "four numbers"), + ("[10, 280, 25, NaN]", "finite number"), + ("[10, 280, 25, 1e300]", "outside the canvas"), + ("[300, 20, 350, 10]", "does not overlap the art"), + ("'all'", "four numbers"), + ]; + for (bounds, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[0], {bounds});"), message); + } + // `a` spans x 10 to 40: a rectangle at x 42 to 48 reaches only the 10 pt padding around it. + refused( + &mut s, + "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[0], [42, 280, 48, 240], o);", + "does not overlap the art", + ); +} + +#[test] +fn script_rasterize_rejects_an_image_past_the_size_limit() { + let (mut s, ..) = doc(); + let source = "var d = app.activeDocument, b = d.pageItems[1]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; + let e = failure(&mut s, source); + assert!(e.contains("too large"), "{e}"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); +} + +#[test] +fn object_rasterize_with_ids_keeps_the_selection_and_names_the_image() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let r = s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72, "clippingMask": true})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.selection.objects, vec![b]); + let (id, image) = (NodeId(r["id"].as_u64().unwrap()), NodeId(r["imageId"].as_u64().unwrap())); + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. })); + assert!(matches!(st.doc.node(image).unwrap().kind, NodeKind::Image(_))); + assert_eq!(st.doc.parent_of(image), Some(id)); + let r = s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + assert_eq!(r["id"], r["imageId"], "without a clip group the image is the new object"); + assert_eq!(s.active().unwrap().selection.objects, vec![NodeId(r["id"].as_u64().unwrap())], "the selection is rasterized as before"); +} + +// ---- imageCapture ---- + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-capture-{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() +} + +/// [`doc`] in a session whose scripts keep their data folders in `base`, and the data folder, where +/// scripts may write. +fn capture_doc(base: &Path) -> (Session, PathBuf) { + let (mut s, ..) = doc(); + s.attach_script_data(base.join("settings/Script Data")); + let dir = PathBuf::from(script(&mut s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()); + (s, dir) +} + +/// Runs `main/main.jsx` in `base` with the text `text`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + // Reading `Folder.userData` makes the data folder, where the script may write. + std::fs::write(&main, format!("Folder.userData; {text}").as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn script(s: &mut Session, base: &Path, text: &str) -> Vec { + run_file(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].as_array().cloned().unwrap_or_default() +} + +fn file_failure(s: &mut Session, base: &Path, text: &str) -> String { + run_file(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +/// The PNG at `path`, decoded by the `image` crate, as RGBA. +fn png(path: &Path) -> image::RgbaImage { + let bytes = std::fs::read(path).unwrap(); + assert!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG signature"); + image::load_from_memory_with_format(&bytes, image::ImageFormat::Png).unwrap().to_rgba8() +} + +#[test] +fn image_capture_whole_artwork_including_pasteboard() { + let base = folder("whole"); + let (mut s, dir) = capture_doc(&base); + // A third rectangle off the artboard, left of it: the art spans x -90 to 150 and y 20 to 150. + let c = rect(&mut s, -90.0, 30.0, 20.0, 20.0); + paint(&mut s, &[c], "#0000ff"); + // The capture's own 150 ppi applies, not the document's raster effects resolution. + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let undo = undo_steps(&s); + let out = script( + &mut s, + &base, + &format!("var r = app.activeDocument.imageCapture(new File({})); vc.log(r === undefined);", quoted(&dir.join("all.png"))), + ); + assert_eq!(out, [json!(true)]); + let img = png(&dir.join("all.png")); + assert_eq!((img.width(), img.height()), (500, 271), "240 × 130 pt at 150 ppi"); + assert_eq!(img.get_pixel(5, 30).0, [0, 0, 255, 255], "the art off the artboard is there"); + assert_eq!(img.get_pixel(499, 0).0, [255, 255, 255, 255], "white where there is no art"); + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_capture_exact_clip_bounds_and_matte() { + let base = folder("clip"); + let (mut s, dir) = capture_doc(&base); + // x 0 to 50 and y 300 to 250 (Y up): the top-left corner of the artboard, with `a` in it. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.matte = true; o.matteColor = {{red: 0, green: 128, blue: 0}}; d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.transparency = true; d.imageCapture(new File({}), [0, 300, 50, 250], o);", + f("white.png"), + f("matte.png"), + f("clear.png") + ); + script(&mut s, &base, &source); + for (name, blank) in [("white.png", [255, 255, 255, 255]), ("matte.png", [0, 128, 0, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.get_pixel(2, 2).0, blank, "{name}: the area without art"); + assert_eq!(img.get_pixel(20, 30).0, [255, 0, 0, 255], "{name}: the art"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_64mp_and_side_limit_before_render() { + let base = folder("huge"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("huge.png"); + // 4000 × 4000 pt at 2400 ppi is far past 64 megapixels; 40,000 × 1 pt at 72 ppi is past 32,768 a side. + let cases = [ + format!( + "var o = new ImageCaptureOptions(); o.resolution = 2400; app.activeDocument.imageCapture(new File({}), [0, 4000, 4000, 0], o);", + quoted(&target) + ), + format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 1, 40000, 0], o);", + quoted(&target) + ), + ]; + for case in &cases { + let e = file_failure(&mut s, &base, case); + assert!(e.contains("64 megapixels"), "{case}: {e}"); + } + assert!(!target.exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_bad_options_and_names() { + let base = folder("bad"); + let (mut s, dir) = capture_doc(&base); + let png = quoted(&dir.join("x.png")); + let cases = [ + ( + format!("var o = new ImageCaptureOptions(); o.resolution = 50; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "from 72 to 2400", + ), + ( + format!("var o = new ImageCaptureOptions(); o.resolution = Infinity; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "finite number", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: NaN, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "finite number", + ), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 300, Infinity, 250]);"), "finite number"), + ( + format!("var o = new ImageCaptureOptions(); o.matte = 'yes'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "true or false", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: 300, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "from 0 to 255", + ), + ( + format!("var o = new ImageCaptureOptions(); o.matteColor = 'red'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "RGBColor", + ), + (format!("app.activeDocument.imageCapture(new File({png}), undefined, new RasterizeOptions());"), "ImageCaptureOptions object"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("x.tif"))), "ends with .png"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join(".png"))), "ends with .png"), + ("app.activeDocument.imageCapture('x.png');".to_string(), "needs a File"), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 0, 0, 0]);"), "right edge right of its left edge"), + (format!("app.activeDocument.windowCapture(new File({}), [100, 100]);", quoted(&dir.join("w.tif"))), "not available yet"), + ]; + for (case, message) in &cases { + let e = file_failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(message), "{case}: {e}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.path().extension().is_some())).count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_denied_or_source_path_writes_nothing() { + let base = folder("denied"); + let (mut s, dir) = capture_doc(&base); + let outside = base.join("outside/x.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&outside))); + assert!(e.contains(DENIED), "{e}"); + assert!(!outside.exists()); + // An open document whose file is named .png in the folder the script may write: its source. + let source = dir.join("source.png"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&source))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + // An image linked by a path relative to the document's folder, not to the working directory. + let linked = dir.join("linked.png"); + std::fs::write(&linked, b"kept").unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "linked.png".into(), relative: Some("linked.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&linked))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&linked).unwrap(), b"kept"); + // An image linked only from a symbol's art, outside the layers. + let in_symbol = dir.join("in-symbol.png"); + std::fs::write(&in_symbol, b"kept").unwrap(); + s.edit("Symbol", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: in_symbol.to_string_lossy().into_owned(), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "symbol-pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + let art = vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))); + d.symbols.push(vectorcraft_doc::Symbol { name: "Mark".into(), art: std::sync::Arc::new(art), dynamic: false }); + Ok(()) + }) + .unwrap(); + let e = file_failure( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&in_symbol)), + ); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&in_symbol).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_written_before_a_failure_is_reported() { + let base = folder("report"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("kept.png"); + let r = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({})); throw new Error('later');", quoted(&target))); + let e = r.unwrap_err().to_string(); + assert!(e.contains("later") && e.contains("kept.png"), "the failure names the file it wrote: {e}"); + assert!(target.is_file()); + 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 a0794be35c..b95a1076e5 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -145,6 +145,14 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + ("", "AntiAliasingMethod ImageCaptureOptions RasterizationColorModel RasterizeOptions"), + ("Document.prototype.", "rasterize windowCapture windowCapture="), + ("ImageCaptureOptions.", "prototype"), + ("ImageCaptureOptions.prototype.", "constructor"), + ("RasterizeOptions.", "prototype"), + ("RasterizeOptions.prototype.", "constructor"), + ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), + ("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types diff --git a/docs/mcp.md b/docs/mcp.md index b379fb7973..24cda05fea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2729,6 +2729,34 @@ 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.rasterize(sourceArt, clipBounds?, options?)` runs `object.rasterize` with the source art's `ids` and gives + the new `RasterItem`; the source art is replaced in one undo step and its objects throw `Stale page item` after. + `Document.imageCapture(imageFile, clipBounds?, options?)` runs `document.export` of a PNG of the art inside + `clipBounds`, or of all the visible art when it is left out, and gives `undefined` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `new RasterizeOptions()` starts with + `antiAliasingMethod` `ARTOPTIMIZED`, `backgroundBlack`, `clippingMask`, `convertSpotColors`, + `convertTextToOutlines`, `includeLayers` and `transparency` false, `colorModel` `DEFAULTCOLORMODEL`, `padding` 0 + and `resolution` 300 (https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/); `new + ImageCaptureOptions()` starts with `antiAliasing`, `matte` and `transparency` false, `matteColor` white and + `resolution` 150 (https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/). Both resolutions take 72 to + 2400 pixels per inch. Every option goes to the command at that value when the script leaves it out, so the + document's raster effects settings do not change the result. The enumerations `AntiAliasingMethod` and + `RasterizationColorModel` (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/) hold strings such + as `"AntiAliasingMethod.TYPEOPTIMIZED"`. + VectorCraft's own rules: `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as + `geometricBounds` gives them, and bounds whose right edge is not right of the left one, or whose bottom edge is not + below the top one, throw an error. `rasterize` takes one page item or a list of at most 10,000; an object of another + document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in + a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With + `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and + `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an error that says + they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With + `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white + without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` + opened for writing is checked, and a path that is an open document's file or a file one of them links throws an + error. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or + written, and the resolution is never lowered to make it fit. `Document.windowCapture` throws an error that says it + is 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 @@ -9707,6 +9735,12 @@ without it, and their results carry the `warning` that Flatten Transparency give of threaded text that it rasterizes out of its thread with the text it shows, as `type.createOutlines` does (see Threading text from the in and out ports), and the other frames keep the text they hold. `object.rasterize` refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. +With `ids`, `object.rasterize` rasterizes those objects instead of the selection and leaves the selection as it was, +without the objects it replaced. An id listed twice, an object inside another listed one, a layer, a path of a +compound path or a part of another object that is not a group, and an object that is locked or in a locked layer or +group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's +`imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. ```json {"name":"run_command","arguments":{"command":"document.rasterEffectsSettings","params":{"resolution":"high","background":"white","addAround":36}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 123604eaec..0d3e80376b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1027,6 +1027,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.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.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 41c375fa579de106534d35fa764dd386442c3bb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:30:55 -0800 Subject: [PATCH 02/22] Scripts: imageCapture refuses a missing linked file's path Document.imageCapture compared only paths that exist, so a capture to the path of a linked image whose file is missing created the file the document then loads from that link. Each path is now compared as its folder's real path and its name, so a missing file counts too. A name that differs only in letter case is the same file in a folder whose names ignore case: the folder's own entries are looked up with their ASCII letter case swapped, and on macOS the nearest folder above on the same volume. When neither tells, the capture is refused. --- .../engine/src/script/dom/raster_capture.rs | 104 ++++++++++++++++-- .../engine/src/tests/script_raster_capture.rs | 67 +++++++++++ docs/mcp.md | 11 +- 3 files changed, 170 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index a75f1a1c4a..811d0c48c4 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -269,10 +269,10 @@ fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f6 /// The files a capture must not write over: the open documents' files and the files their linked /// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns -/// and brushes included), with a DCS image's plate files, by their real paths. A link's stored path -/// and its relative path are each taken from its document's folder, as opening the document reads -/// them. -fn sources_on_disk(h: &Host) -> Vec { +/// and brushes included), with a DCS image's plate files, also when a file is missing, in the form +/// [`placed`] gives. A link's stored path and its relative path are each taken from its +/// document's folder, as opening the document reads them. +fn sources_on_disk(h: &Host) -> Vec { let s = h.session.borrow(); let mut paths: Vec = Vec::new(); for st in s.documents() { @@ -287,7 +287,97 @@ fn sources_on_disk(h: &Host) -> Vec { } } } - paths.iter().filter_map(|p| std::fs::canonicalize(p).ok()).collect() + paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect() +} + +/// A file as its folder's real path and its name. +type Placed = (std::path::PathBuf, std::ffi::OsString); + +/// `p` as its folder's real path and its file name: from its real path with links followed, or, +/// for a file that is not there, from its folder's real path. `None` when neither the file nor its +/// folder is there. +fn placed(p: &std::path::Path) -> Option { + let real = std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?)))?; + Some((real.parent()?.to_path_buf(), real.file_name()?.to_os_string())) +} + +/// Whether two [`placed`] files are one file: the same folder, and the same name, or names that +/// differ only in letter case in a folder whose volume ignores case. +fn same_file(a: &Placed, b: &Placed) -> bool { + same_folder(&a.0, &b.0) && (a.1 == b.1 || (a.1.to_string_lossy().to_lowercase() == b.1.to_string_lossy().to_lowercase() && ignores_case(&a.0))) +} + +/// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and +/// file number, so a path spelled in another letter case on a volume that ignores case still +/// matches. On Windows a real path carries the letter case stored on disk. +fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { + if a == b { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { + return x.dev() == y.dev() && x.ino() == y.ino(); + } + } + false +} + +/// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a +/// symbolic link or another file. +fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool { + if !std::fs::symlink_metadata(other).is_ok_and(|m| !m.file_type().is_symlink()) { + return false; + } + match (std::fs::canonicalize(entry), std::fs::canonicalize(other)) { + (Ok(a), Ok(b)) => same_folder(&a, &b), + _ => false, + } +} + +/// `name` with the letter case of every ASCII letter swapped, and other characters as they are. +fn swapped_case(name: &str) -> String { + name.chars().map(|c| if c.is_ascii_lowercase() { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() }).collect() +} + +/// Whether file names in the real folder `folder` ignore letter case. Names keep case when two of +/// the folder's first 256 entries differ only in the case of ASCII letters. Otherwise the first of +/// them whose name has an ASCII letter and that is not a symbolic link is looked up with the case +/// of those letters swapped: names ignore case when that finds the same entry. With no such entry +/// on macOS, where a whole volume either ignores or keeps case, the nearest folder at or above +/// `folder` whose name has an ASCII letter, with its parent on the same volume, is looked up the +/// same way in its parent. When neither tells, names are taken to ignore case. +fn ignores_case(folder: &std::path::Path) -> bool { + let entries: Vec = std::fs::read_dir(folder).into_iter().flatten().flatten().take(256).collect(); + let mut folded = std::collections::HashSet::new(); + let names: std::collections::HashSet = entries.iter().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + if !names.iter().all(|n| folded.insert(n.to_ascii_lowercase())) { + return false; + } + for entry in &entries { + let name = entry.file_name().to_string_lossy().into_owned(); + let swapped = swapped_case(&name); + if swapped != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(swapped)); + } + } + #[cfg(target_os = "macos")] + for dir in folder.ancestors() { + use std::os::unix::fs::MetadataExt; + let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { break }; + let device = |p: &std::path::Path| std::fs::metadata(p).map(|m| m.dev()).ok(); + let here = device(folder); + if here.is_none() || device(dir) != here || device(parent) != here { + break; + } + let name = name.to_string_lossy(); + let swapped = swapped_case(&name); + if swapped != name { + return finds_same(dir, &parent.join(swapped)); + } + } + true } /// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the @@ -308,8 +398,8 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { }; check_size(region, ppi)?; let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; - let canonical = std::fs::canonicalize(&real).ok(); - if canonical.is_some_and(|c| sources_on_disk(h).contains(&c)) { + let target = placed(&real); + if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s))) { return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); } let p = json!({ diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 3385c4dd5c..e48c7a2d46 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -524,6 +524,73 @@ fn capture_denied_or_source_path_writes_nothing() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn capture_to_a_missing_links_path_writes_nothing() { + let base = folder("missing-link"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // An image linked by a path next to the document whose file is not there. + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "gone.png".into(), relative: Some("gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let gone = dir.join("gone.png"); + assert!(!gone.exists()); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&gone))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!gone.exists(), "nothing written"); + // The same name in other letter case is the linked file only where the volume ignores case. + std::fs::write(dir.join("probe.txt"), b"x").unwrap(); + let volume_ignores_case = dir.join("PROBE.TXT").exists(); + let upper = dir.join("GONE.png"); + let text = format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&upper)); + if volume_ignores_case { + assert!(file_failure(&mut s, &base, &text).contains("cannot write over an open document")); + assert!(!gone.exists(), "nothing written"); + } else { + script(&mut s, &base, &text); + assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); + // Two names for one file that differ only in case show that the folder keeps case. + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(sub.join("probe.txt"), b"x").unwrap(); + std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "sub-gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let sub_upper = sub.join("GONE.png"); + script(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&sub_upper))); + assert!(sub_upper.exists() && !sub.join("gone.png").exists()); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_written_before_a_failure_is_reported() { let base = folder("report"); diff --git a/docs/mcp.md b/docs/mcp.md index 24cda05fea..b58ff4129b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,14 +2749,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and - `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an error that says - they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With + `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an + error that says they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` opened for writing is checked, and a path that is an open document's file or a file one of them links throws an - error. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or - written, and the resolution is never lowered to make it fit. `Document.windowCapture` throws an error that says it - is not available yet. + error, also when that file is missing. A name that differs from it only in letter case throws the same error in a + folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or + 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to + make it fit. `Document.windowCapture` throws an error that says it is 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 6a19ae164b18368ff74f751ad80325af21e4a1ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:34:45 -0800 Subject: [PATCH 03/22] Scripts: script.check counts imageCapture as a file write The checker lists Document.imageCapture with saveAs and exportFile as a document method that writes the file it is given, and the host name check gives it an OUTSIDE row. RasterizeOptions and ImageCaptureOptions move to the bare classes, as the save and export option classes did. A capture whose clipBounds miss all the art writes a blank image of that area, and a new test covers it; docs/mcp.md says so beside the rasterize rule, which throws an error for such bounds. --- .../engine/src/tests/script_raster_capture.rs | 25 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 12 ++++----- crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/tests.rs | 15 +++++++++++ docs/mcp.md | 3 ++- 5 files changed, 48 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index e48c7a2d46..762ef76bef 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -382,6 +382,31 @@ fn image_capture_exact_clip_bounds_and_matte() { let _ = std::fs::remove_dir_all(base); } +/// Bounds that miss every object still give an image of that area, blank or transparent. +#[test] +fn image_capture_of_bounds_without_art_is_blank() { + let base = folder("empty"); + let (mut s, dir) = capture_doc(&base); + // x 300 to 350 and y 100 to 50 (Y up): below and right of both rectangles. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [300, 100, 350, 50], o);\ + o.transparency = true; d.imageCapture(new File({}), [300, 100, 350, 50], o);", + f("blank.png"), + f("clear.png") + ); + let undo = undo_steps(&s); + script(&mut s, &base, &source); + for (name, blank) in [("blank.png", [255, 255, 255, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert!(img.pixels().all(|p| p.0 == blank), "{name}: every pixel is {blank:?}"); + } + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_rejects_64mp_and_side_limit_before_render() { let base = folder("huge"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b95a1076e5..52721f7c33 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,6 +39,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -145,21 +146,18 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), - ("", "AntiAliasingMethod ImageCaptureOptions RasterizationColorModel RasterizeOptions"), + // The enumerations of rasterizing and the document's rasterize and window capture methods. + ("", "AntiAliasingMethod RasterizationColorModel"), ("Document.prototype.", "rasterize windowCapture windowCapture="), - ("ImageCaptureOptions.", "prototype"), - ("ImageCaptureOptions.prototype.", "constructor"), - ("RasterizeOptions.", "prototype"), - ("RasterizeOptions.prototype.", "constructor"), ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), ("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// and the save and export option classes. +/// and the save, export, rasterize and image capture option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ - ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions ImageCaptureOptions RasterizeOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index a73dd557d6..c87e1347d6 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -75,7 +75,7 @@ pub(crate) const REFLECT: &str = "reflect"; pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ -pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "imageCapture", "saveAs"]; // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index e985fa3d0f..0f7fa38c7e 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -543,6 +543,21 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `imageCapture` writes the file it is given, with or without bounds and options, and +/// called by its name in brackets; `rasterize` stays inside the document. +#[test] +fn image_capture_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument.imageCapture(f);\n", + "var d = app.activeDocument; d.imageCapture(f, [0, 0, 10, 10], new ImageCaptureOptions());\n", + "d['imageCapture'](f);\n", + "d.rasterize(d.pageItems[0]);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 4][..])]); +} + /// `saveAs` and `exportFile` called with their names as string literals in brackets write the file /// too; reading the method without calling it does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4904f683f1..4510330cba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,7 +2749,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot as `"AntiAliasingMethod.TYPEOPTIMIZED"`. VectorCraft's own rules: `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as `geometricBounds` gives them, and bounds whose right edge is not right of the left one, or whose bottom edge is not - below the top one, throw an error. `rasterize` takes one page item or a list of at most 10,000; an object of another + below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` + writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and From cb6b9e3577318971ef681ad1dd4dac3f97628a21 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:33:44 -0800 Subject: [PATCH 04/22] Rasterize: ids leave out an object inside another listed one object.rasterize with ids now does what the same objects selected do: an object listed with a group or layer that holds it is left out and the group is rasterized, as edit::roots_of leaves it out of a selection. Document.rasterize still throws an error for such a list before it runs the command. --- crates/engine/src/cmd/menucmds.rs | 16 +++++++++------- crates/engine/src/script/dom/raster_capture.rs | 13 ++++++++++++- docs/mcp.md | 6 +++--- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index f339f7b96f..c5bc2be07f 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, none inside another, each unlocked in unlocked layers and groups; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -949,8 +949,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p } /// The objects `ids` names for Rasterize, in paint order: each an object of the active document, -/// listed once, none inside another listed one, and neither it nor a layer or group it is in -/// locked. +/// listed once, and neither it nor a layer or group it is in locked. An object inside another +/// listed one is left out, as `edit::roots_of` leaves it out of a selection. fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { let ids = super::checked_ids_param(s, p, "ids", cmd)?; let d = &s.doc()?.doc; @@ -960,24 +960,26 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { return Err(bad(cmd, format!("id {} is listed twice", id.0))); } } + let mut roots = Vec::with_capacity(ids.len()); for id in &ids { // The layers and groups from the top down to the object itself. let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; if d.node(*id).is_some_and(|n| n.is_layer()) { return Err(bad(cmd, format!("id {} is a layer, not an object", id.0))); } + if up.iter().any(|a| a != id && listed.contains(a)) { + continue; + } let parent = up.len().checked_sub(2).and_then(|i| d.node(up[i])); if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); } - if let Some(outer) = up.iter().find(|a| *a != id && listed.contains(*a)) { - return Err(bad(cmd, format!("id {} is inside id {}, which is listed too", id.0, outer.0))); - } if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); } + roots.push(*id); } - Ok(vectorcraft_doc::Selection { objects: ids, ..Default::default() }.in_paint_order(d)) + Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) } /// The id of the image in `node`, the node Rasterize makes: the image itself, or the image in its diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 811d0c48c4..1ad9fcb395 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -176,7 +176,8 @@ fn rasterize_params(items: Option<&[(String, Data)]>) -> std::result::Result std::result::Result, HostError> { let list: Vec<&Data> = match d { Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("rasterize takes at most {MAX_LISTED} objects"))), @@ -196,6 +197,16 @@ fn sources(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostEr } ids.push(item.id.0); } + let listed: std::collections::HashSet = ids.iter().copied().collect(); + let inside = with_doc(h, doc, |_, st| { + ids.iter().find_map(|id| { + let up = st.doc.ancestry(crate::NodeId(*id))?; + up.iter().any(|a| a.0 != *id && listed.contains(&a.0)).then_some(()) + }) + }); + if inside.is_some() { + return Err(HostError::Error("a source page item is inside another one, which is listed too".into())); + } Ok(ids) } diff --git a/docs/mcp.md b/docs/mcp.md index 4510330cba..3ab6ead40d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9754,9 +9754,9 @@ of threaded text that it rasterizes out of its thread with the text it shows, as Threading text from the in and out ports), and the other frames keep the text they hold. `object.rasterize` refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. With `ids`, `object.rasterize` rasterizes those objects instead of the selection and leaves the selection as it was, -without the objects it replaced. An id listed twice, an object inside another listed one, a layer, a path of a -compound path or a part of another object that is not a group, and an object that is locked or in a locked layer or -group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id +listed twice, a layer, a path of a compound path or a part of another object that is not a group, and an object that +is locked or in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's `imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. From 1f71bda80f66f37344ca4c5dec48e21a19e4d0cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:05:09 -0800 Subject: [PATCH 05/22] Scripts: imageCapture protects every place a link is read from - imageCapture refuses a path that any open document's link is read from: the stored path from the document's folder, the relative path from the file the document was read from (a template opened as an untitled document included), the name in those folders, and a DCS image's plate files beside each of those places. Documents the interface opened while the run was paused count too. - new IllustratorSaveOptions() starts with compatibility Compatibility.ILLUSTRATOR19. - PageItem.controlBounds throws that it is not available yet instead of giving the visible bounds. - move and duplicate with PLACEAFTER and a clipping group's clipping path as the relative object throw an error. - The settings of one run's DocumentPreset objects hold at most 4 MB together. - A run keeps the page-item lists of up to 8 documents, so reads that alternate between documents do not walk them again. --- crates/engine/src/cmd/links.rs | 46 +++++---- crates/engine/src/script/dom.rs | 54 ++++++++--- .../engine/src/script/dom/raster_capture.rs | 20 ++-- crates/engine/src/script/dom/save_open.rs | 7 +- crates/engine/src/script/mod.rs | 7 ++ crates/engine/src/tests/script_dom.rs | 61 +++++++++++- .../engine/src/tests/script_raster_capture.rs | 95 +++++++++++++++++++ crates/engine/src/tests/script_run.rs | 4 +- crates/engine/src/tests/script_save_open.rs | 4 +- docs/mcp.md | 16 ++-- 10 files changed, 258 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index febe0946de..4d6c2c8b39 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -194,16 +194,24 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } -/// The link of every linked image and placed document of `d`, wherever it is stored, brush art -/// included, with the plate files of an image placed from a DCS file. -pub(crate) fn linked_files_with_plates(d: &Document) -> Vec<(LinkInfo, Vec)> { - groups(d, None) - .into_iter() - .map(|g| { - let plates = g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&g.link.path, &f.name)).collect(); - (g.link, plates) - }) - .collect() +/// Every place a linked image or placed document of `d` (a document looking from `base`) is read +/// from, wherever it is stored, brush art included, whether or not a file is there: each place +/// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, +/// as its plate-change check finds them. A link's absolute stored and relative paths are listed +/// as they are too. +pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { + let mut out = vec![]; + for g in groups(d, None) { + let link = &g.link; + let mut mains: Vec = + std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).filter(|p| Path::new(p).is_absolute()).map(str::to_string).collect(); + mains.extend(places(link, base)); + for main in mains { + out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); + out.push(main); + } + } + out } /// The linked images and placed documents of `d` by file and content, wherever they are stored @@ -397,6 +405,17 @@ fn found_at(path: String) -> Option { /// by name in the document's folder, then in that of [`LinkBase::relative`]. Only paths /// [`fileio::document_path`] follows from the document's own file are looked at. fn locate(link: &LinkInfo, base: LinkBase) -> Option { + let mut f = places(link, base).find_map(found_at)?; + f.relative = base.relative.map(|from| { + let from = absolute_path(from); + Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) + }); + Some(f) +} + +/// The places [`locate`] looks for the file of `link` at, in its order, whether or not a file is +/// there. +fn places<'a>(link: &'a LinkInfo, base: LinkBase<'a>) -> impl Iterator + 'a { let (relative, other) = (link.relative.as_deref(), base.doc != base.relative); let stored = [ (Some(link.path.as_str()), base.doc), @@ -405,12 +424,7 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { (Some(link.name()), base.doc), (other.then_some(link.name()), base.relative), ]; - let mut f = stored.into_iter().filter_map(|(p, from)| follow_from(p?, from, base.doc, fileio::document_path)).find_map(found_at)?; - f.relative = base.relative.map(|from| { - let from = absolute_path(from); - Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) - }); - Some(f) + stored.into_iter().filter_map(move |(p, from)| follow_from(p?, from, base.doc, fileio::document_path)) } /// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 478dbca2c5..d651d82867 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -87,17 +87,21 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; -/// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// What the object model keeps for one run: its coordinate system, the last list of page items of +/// each of up to [`MAX_ITEM_LISTS`] documents, kept while that document is unchanged, whether a +/// call's own savepoint ([`atomically`]) is open, and the settings of each `DocumentPreset` the run +/// made. #[derive(Default)] pub(super) struct State { coords: Cell, - items: RefCell>, + /// The documents' lists, the one listed most recently at the end. + items: RefCell>, saving: Cell, /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, presets: RefCell>>, + /// What the settings in `presets` hold together ([`MAX_PRESET_BYTES`]). + preset_bytes: Cell, } impl State { @@ -130,6 +134,9 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); +/// The most documents whose page-item lists a run keeps at once. +const MAX_ITEM_LISTS: usize = 8; + type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. @@ -339,10 +346,7 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { /// The ids of a document's page items in paint order ([`State`] keeps the last list). fn page_items(h: &Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.items.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - { + if let Some((_, _, ids)) = h.dom.items.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)) { return ids.clone(); } fn walk(nodes: &[Arc], out: &mut Vec) { @@ -361,7 +365,12 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { let mut ids = Vec::new(); walk(&st.doc.layers, &mut ids); let ids = Rc::new(ids); - *h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + let mut lists = h.dom.items.borrow_mut(); + lists.retain(|(uid, ..)| *uid != st.uid); + if lists.len() >= MAX_ITEM_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), ids.clone())); ids } @@ -950,20 +959,26 @@ fn new_preset(h: &Host) -> Answer { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ + let fields = vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ]); + ]; + h.dom.preset_bytes.set(h.dom.preset_bytes.get().saturating_add(fields.iter().map(|(_, v)| data_size(v)).sum::())); + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; +/// The most bytes the settings of one run's `DocumentPreset` objects hold together, as +/// [`data_size`] counts them. +const MAX_PRESET_BYTES: u64 = 4 << 20; + /// The settings a `DocumentPreset` has, each a property a script reads and assigns. const PRESET_FIELDS: &[&str] = &[ "artboardLayout", @@ -1016,7 +1031,16 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; - match fields.iter_mut().find(|(k, _)| k == key) { + let slot = fields.iter_mut().find(|(k, _)| k == key); + // The settings of the run's presets hold at most MAX_PRESET_BYTES together, and the value a + // setting replaces no longer counts. + let old = slot.as_ref().map_or(0, |(_, v)| data_size(v)); + let kept = h.dom.preset_bytes.get().saturating_sub(old).saturating_add(data_size(&value)); + if kept > MAX_PRESET_BYTES { + return Err(HostError::Range(format!("the DocumentPresets of a script can hold at most {} MB of settings", MAX_PRESET_BYTES >> 20))); + } + h.dom.preset_bytes.set(kept); + match slot { Some((_, v)) => *v = value, None => fields.push((key.to_string(), value)), } @@ -1628,6 +1652,10 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s } Placement::Above | Placement::Below => { let parent = d.parent_of(target).ok_or_else(|| HostError::Error("an object cannot go beside a top-level layer".into()))?; + let mask = d.node(parent).is_some_and(crate::doc::Node::clips) && d.position(target).is_some_and(|(_, i, _)| i == 0); + if how == Placement::Below && mask { + return Err(HostError::Error("an object cannot go below a clipping group's clipping path".into())); + } (parent, Some(target)) } }; @@ -1908,7 +1936,6 @@ 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)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), @@ -1920,6 +1947,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), [ "artworkKnockout", "blendingMode", + "controlBounds", "isIsolated", "layer", "pixelAligned", diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 1ad9fcb395..8883fb1714 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -281,22 +281,18 @@ fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f6 /// The files a capture must not write over: the open documents' files and the files their linked /// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns /// and brushes included), with a DCS image's plate files, also when a file is missing, in the form -/// [`placed`] gives. A link's stored path and its relative path are each taken from its -/// document's folder, as opening the document reads them. +/// [`placed`] gives. A link's places are the ones opening the document looks at: its stored path +/// from the document's folder and its relative path from the folder of the file the document was +/// read from (a template opened as an untitled document has no file of its own), with a DCS +/// image's plate files beside each. The documents the interface has open while the run's slice +/// runs, such as one opened while the run was paused, count too. fn sources_on_disk(h: &Host) -> Vec { let s = h.session.borrow(); + let interface = h.interface_docs.borrow(); let mut paths: Vec = Vec::new(); - for st in s.documents() { + for st in s.documents().iter().chain(interface.iter()) { paths.extend(st.path.clone()); - let document = st.path.as_deref(); - for (link, plates) in crate::cmd::links::linked_files_with_plates(&st.doc) { - for stored in std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).chain(plates.iter().map(String::as_str)) { - if std::path::Path::new(stored).is_absolute() { - paths.push(stored.to_string()); - } - paths.extend(crate::cmd::fileio::document_path(stored, document).ok()); - } - } + paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st))); } paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect() } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..725330e3af 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -196,7 +196,12 @@ const AI_KEPT: &[(&str, Default)] = &[ ]; fn ai_starts() -> Vec<(&'static str, Data)> { - vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))] + vec![ + ("compatibility", text("Compatibility.ILLUSTRATOR19")), + ("compressed", Data::Bool(true)), + ("pdfCompatible", Data::Bool(true)), + ("embedICCProfile", Data::Bool(false)), + ] } fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index affacab584..2225a89a3c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -802,6 +802,9 @@ struct Host { args: RefCell<(Data, u64)>, /// The run's state of the script object model (`app`). dom: dom::State, + /// While a slice runs: the documents the interface has open ([`World::docs`] of the run's + /// job), which a capture must not write over either. Empty between slices. + interface_docs: RefCell>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -2065,6 +2068,7 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::default(), + interface_docs: RefCell::new(Vec::new()), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2464,6 +2468,8 @@ fn failure_frame(report: &Value) -> (String, String) { fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { let depth = std::mem::replace(&mut s.depth, 0); job.world.swap(s); + // The interface's documents are the host's to read during the slice, and the job's again after. + std::mem::swap(&mut job.world.docs, &mut *job.host.interface_docs.borrow_mut()); // The run's front document draws and converts through its own profiles, and the interface's // again after the slice. s.sync_front_profiles(); @@ -2487,6 +2493,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result Vec { s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect() }; + assert_eq!(children(&s)[0], b, "the clipping path is the group's first child"); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for source in [ + "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + "var p = app.activeDocument.pageItems; p.getByName('loose').duplicate(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("cannot go below a clipping group's clipping path"), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "a refused move changes nothing"); + assert_eq!(undo_steps(&s), steps); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEBEFORE);"); + assert_eq!(children(&s), [b, c, a]); +} + #[test] fn a_copy_that_cannot_be_placed_is_deleted() { let mut s = Session::new(); @@ -670,9 +698,12 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].rotate(5);", + "app.activeDocument.pageItems[0].controlBounds;", + ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); @@ -824,6 +855,24 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); } +/// The presets of one run hold at most 4 MB of settings together; a setting that replaces another +/// gives back what the old value held. +#[test] +fn document_preset_settings_are_limited_in_bytes() { + let mut s = Session::new(); + let out = log( + &mut s, + "var big = new Array(1572865).join('a'), p = new DocumentPreset(), q = new DocumentPreset();\ + p.title = big; p.units = big; p.title = big; q.title = 'x'; vc.log(p.title.length);\ + try { q.colorMode = big; } catch (e) { vc.log([e.name, e.message]); }\ + vc.log(q.colorMode === undefined); p.title = 'short'; q.colorMode = big; vc.log(q.colorMode.length);", + ); + assert_eq!(out[0], json!(1_572_864)); + assert_eq!(out[1], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); + assert_eq!(out[2], json!(true), "a refused setting is not stored"); + assert_eq!(out[3], json!(1_572_864), "replacing a setting frees what it held"); +} + #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); @@ -1026,8 +1075,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'));"); + // Script string literals, so a quote or a backslash in the temporary folder's path stays text. + 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_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 762ef76bef..610882b419 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -616,6 +616,101 @@ fn capture_to_a_missing_links_path_writes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Places a linked image of the key `key` with `link` on the active document's default layer. +fn place_linked(s: &mut Session, key: &str, link: vectorcraft_doc::LinkInfo) { + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: key.into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); +} + +/// An untitled document opened from a template finds a link by its relative path from the +/// template's folder, so a capture there is refused, also when the file is missing. +#[test] +fn capture_to_a_templates_relative_link_writes_nothing() { + let base = folder("template-link"); + let (mut s, dir) = capture_doc(&base); + let st = s.active_mut().unwrap(); + st.path = None; + st.links_from = Some(dir.join("t.vctemplate").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale, relative: Some("pic.png".into()), ..Default::default() }); + let target = dir.join("pic.png"); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!target.exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +/// A DCS image whose stored path is stale reads its plate files beside the main file its relative +/// path finds, so a capture over one of those is refused. +#[test] +fn capture_over_a_plate_beside_a_found_dcs_file_writes_nothing() { + use vectorcraft_doc::separated::{InkPlate, PlateFile, Separated}; + let base = folder("dcs-plate"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + std::fs::write(dir.join("main.eps"), b"main").unwrap(); + let plate = dir.join("cyan.png"); + std::fs::write(&plate, b"kept").unwrap(); + let separated = Separated::new(1, 1, vec![InkPlate { name: "Cyan".into(), cmyk: [1.0, 0.0, 0.0, 0.0], data: vec![255] }]).unwrap(); + let files = [PlateFile { name: "cyan.png".into(), size: 4, modified: 0 }]; + let blob = vectorcraft_doc::ImageBlob::separated_tiff(&separated, None, &files).unwrap(); + s.edit("Blob", |d, _| { + d.images.insert("dcs".into(), blob); + Ok(()) + }) + .unwrap(); + let stale = base.join("outside/gone/main.eps").to_string_lossy().into_owned(); + place_linked(&mut s, "dcs", vectorcraft_doc::LinkInfo { path: stale, relative: Some("main.eps".into()), ..Default::default() }); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&plate))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&plate).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// A document the interface opens while the run is paused is open too: a capture over its file is +/// refused. +#[test] +fn capture_over_a_document_opened_while_paused_writes_nothing() { + let base = folder("paused-open"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("opened.png"); + let main = base.join("main/main.jsx"); + let text = format!( + "Folder.userData; for (var i = 0; i < 2000000; i++) {{}}\ + try {{ app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]); vc.log('written'); }} catch (e) {{ vc.log(e.message); }}", + quoted(&target) + ); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + let svg = br#""#; + crate::cmd::fileio::open_bytes(&mut s, "opened.svg", svg, Some(target.to_string_lossy().into_owned())).unwrap(); + std::fs::write(&target, b"kept").unwrap(); + let r = loop { + if let Some(r) = s.script_pump() { + break r.unwrap(); + } + }; + s.script_frames = false; + let out = r["log"].as_array().cloned().unwrap_or_default(); + assert!(out.len() == 1 && out[0].as_str().is_some_and(|m| m.contains("cannot write over an open document")), "{out:?}"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_written_before_a_failure_is_reported() { let base = folder("report"); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 02176c38c9..fcd364e744 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -181,7 +181,9 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + // Names the app's own reference errors give a hint for: a script's own text keeps none. + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: activeDocument is not defined';", "thrown", "ReferenceError: activeDocument is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..d8d6a82a50 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -63,7 +63,7 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { "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\ d.saveAs(new File(dir + '/a.svg'));\n\ - var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\ + var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability, new IllustratorSaveOptions().compatibility]);\n\ o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.someOtherName = 3;\n\ o.colorCompression = 'CompressionQuality.None';\n\ d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\ @@ -77,7 +77,7 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { var u = [app.userInteractionLevel]; app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; u.push(app.userInteractionLevel); vc.log(u);" ), ); - assert_eq!(out[0], json!(["PDFSaveOptions", "PDFCompatibility.ACROBAT5", true])); + assert_eq!(out[0], json!(["PDFSaveOptions", "PDFCompatibility.ACROBAT5", true, "Compatibility.ILLUSTRATOR19"])); assert_eq!(out[1], json!("b.pdf"), "saveAs gives the document the new file"); assert_eq!(out[2], json!("b.pdf"), "exportFile leaves the document's file as it is"); assert_eq!(out[3], json!(["Document", 2, true, "a.svg"])); diff --git a/docs/mcp.md b/docs/mcp.md index 3ab6ead40d..f8595cacc4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2639,7 +2639,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and + starts with the defaults that page gives. The settings of the `DocumentPreset` objects one run makes hold at most + 4 MB together, and an assignment past that throws a `RangeError`. A preset's `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 @@ -2655,14 +2656,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds 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?)`, + 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `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 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. `PLACEAFTER` with a clipping group's clipping path as the relative object throws an error and + changes nothing. 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. `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 @@ -2691,7 +2692,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.controlBounds`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. @@ -2759,7 +2760,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` opened for writing is checked, and a path that is an open document's file or a file one of them links throws an - error, also when that file is missing. A name that differs from it only in letter case throws the same error in a + error, also when that file is missing. The linked files are every place opening the document looks for a link's + file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS + image's plate files beside each, and the documents count whether they were open when the run started or were + opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to make it fit. `Document.windowCapture` throws an error that says it is not available yet. From 61b7c8dbe1dbbf3bf1e7bc902287a2e1b085af94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:13:29 -0800 Subject: [PATCH 06/22] Scripts: new DocumentPreset and imageCapture keep their limits for every link - new DocumentPreset() counts its default settings toward the 4 MB the presets of a run hold together, and throws a RangeError instead of passing it, as a setter does. - imageCapture refuses a file at the relative path of every linked image, also when two images share a path and content but keep different relative paths; before, only the first one's was protected. --- crates/engine/src/cmd/links.rs | 35 +++++++++++++------ crates/engine/src/script/dom.rs | 7 +++- crates/engine/src/tests/script_dom.rs | 17 +++++++++ .../engine/src/tests/script_raster_capture.rs | 20 +++++++++++ 4 files changed, 68 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 4d6c2c8b39..ff420c436e 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -165,6 +165,9 @@ struct Group { document: Option, /// An image placed from a DCS file: the plate files of their own its plates were read from. plate_files: Vec, + /// The stored relative paths of the group's objects other than `link`'s, each once: objects + /// with the same path and content can each keep a relative path of its own. + other_relatives: Vec, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -198,17 +201,22 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { /// from, wherever it is stored, brush art included, whether or not a file is there: each place /// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, /// as its plate-change check finds them. A link's absolute stored and relative paths are listed -/// as they are too. +/// as they are too, for the relative path of every object in a group. pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { let mut out = vec![]; for g in groups(d, None) { - let link = &g.link; - let mut mains: Vec = - std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).filter(|p| Path::new(p).is_absolute()).map(str::to_string).collect(); - mains.extend(places(link, base)); - for main in mains { - out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); - out.push(main); + let others = g.other_relatives.iter().map(|r| LinkInfo { relative: Some(r.clone()), ..g.link.clone() }); + for link in std::iter::once(g.link.clone()).chain(others) { + let mut mains: Vec = std::iter::once(link.path.as_str()) + .chain(link.relative.as_deref()) + .filter(|p| Path::new(p).is_absolute()) + .map(str::to_string) + .collect(); + mains.extend(places(&link, base)); + for main in mains { + out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); + out.push(main); + } } } out @@ -231,10 +239,17 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), Some(_) => vec![], }; - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files }); + out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files, other_relatives: vec![] }); out.len() - 1 }); - if let (Some(id), Some(g)) = (id, out.get_mut(i)) { + let Some(g) = out.get_mut(i) else { return }; + if let Some(r) = &link.relative + && g.link.relative.as_ref() != Some(r) + && !g.other_relatives.contains(r) + { + g.other_relatives.push(r.clone()); + } + if let Some(id) = id { g.ids.push(id); } }; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d651d82867..871cd94370 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -967,7 +967,12 @@ fn new_preset(h: &Host) -> Answer { item("numArtboards", num(1.0)), item("width", num(612.0)), ]; - h.dom.preset_bytes.set(h.dom.preset_bytes.get().saturating_add(fields.iter().map(|(_, v)| data_size(v)).sum::())); + // The defaults count toward MAX_PRESET_BYTES as the setter counts a value. + let kept = h.dom.preset_bytes.get().saturating_add(fields.iter().map(|(_, v)| data_size(v)).sum::()); + if kept > MAX_PRESET_BYTES { + return Err(HostError::Range(format!("the DocumentPresets of a script can hold at most {} MB of settings", MAX_PRESET_BYTES >> 20))); + } + h.dom.preset_bytes.set(kept); presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c64aee6ec2..bc8f71199a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -873,6 +873,23 @@ fn document_preset_settings_are_limited_in_bytes() { assert_eq!(out[3], json!(1_572_864), "replacing a setting frees what it held"); } +/// A new `DocumentPreset`'s default settings count toward the 4 MB, so one that would pass the +/// limit is refused and leaves the count as it was. +#[test] +fn a_new_document_preset_is_refused_past_the_byte_limit() { + let mut s = Session::new(); + // The six defaults hold 74 bytes; the two strings leave 10 bytes of the 4 MB free. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.title = new Array(2097153).join('a'); p.units = new Array(2097065).join('b');\ + try { new DocumentPreset(); vc.log('made'); } catch (e) { vc.log([e.name, e.message]); }\ + p.colorMode = 1; vc.log(p.colorMode); p.title = 'x'; vc.log(new DocumentPreset().width);", + ); + assert_eq!(out[0], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); + assert_eq!(out[1], json!(1), "a refused preset adds nothing to the count"); + assert_eq!(out[2], json!(612), "a preset below the limit is still made"); +} + #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 610882b419..863b5d1db6 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -653,6 +653,26 @@ fn capture_to_a_templates_relative_link_writes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Two images that share a stale path and a content but keep different relative paths are each +/// looked for at their own relative path, so a capture over either one's file is refused. +#[test] +fn capture_over_either_relative_path_of_one_linked_content_writes_nothing() { + let base = folder("two-relatives"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + for relative in ["a.png", "b.png"] { + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale.clone(), relative: Some(relative.into()), ..Default::default() }); + } + for name in ["a.png", "b.png"] { + let target = dir.join(name); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{name}: {e}"); + assert!(!target.exists(), "{name}: nothing written"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A DCS image whose stored path is stale reads its plate files beside the main file its relative /// path finds, so a capture over one of those is refused. #[test] From 90400601189f9c204d0c1c2150f1b84f211d2e56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:38:52 -0800 Subject: [PATCH 07/22] Links: a group checks its other relative paths in a set Grouping linked objects compared each object's relative path with every other relative path already in its group, so many objects of one file with paths of their own took quadratic time. The group keeps a set beside the list, which keeps the stored order. --- crates/engine/src/cmd/links.rs | 52 ++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index ff420c436e..fad22b6367 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -168,6 +168,8 @@ struct Group { /// The stored relative paths of the group's objects other than `link`'s, each once: objects /// with the same path and content can each keep a relative path of its own. other_relatives: Vec, + /// `other_relatives` as a set, looked up for every object added to the group. + relatives_seen: std::collections::HashSet, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -239,14 +241,23 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), Some(_) => vec![], }; - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files, other_relatives: vec![] }); + out.push(Group { + link: link.clone(), + key: key.to_string(), + ids: vec![], + document, + plate_files, + other_relatives: vec![], + relatives_seen: Default::default(), + }); out.len() - 1 }); let Some(g) = out.get_mut(i) else { return }; if let Some(r) = &link.relative && g.link.relative.as_ref() != Some(r) - && !g.other_relatives.contains(r) + && !g.relatives_seen.contains(r) { + g.relatives_seen.insert(r.clone()); g.other_relatives.push(r.clone()); } if let Some(id) = id { @@ -3222,6 +3233,43 @@ mod tests { assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + /// Many objects of one file and content that each keep a relative path of their own make one + /// group, which lists every other relative path once, in the order the objects are stored. + #[test] + fn a_group_lists_each_other_relative_path_once_in_stored_order() { + let mut d = Document::new(612.0, 792.0); + let layer = d.default_layer(); + let relatives: Vec = (0..2_000).map(|i| format!("art/{}/pic.png", i % 1_000)).collect(); + for r in &relatives { + let link = LinkInfo { relative: Some(r.clone()), ..LinkInfo::new("/art/pic.png") }; + let im = ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + let id = d.alloc_id(); + d.insert(layer, 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + } + let groups = groups(&d, None); + assert_eq!(groups.len(), 1); + let g = &groups[0]; + assert_eq!(g.ids.len(), 2_000); + // Objects inserted at index 0 are stored last to first. + let first = g.link.relative.clone().unwrap(); + let mut expected: Vec = vec![]; + for r in relatives.iter().rev() { + if *r != first && !expected.contains(r) { + expected.push(r.clone()); + } + } + assert_eq!(expected.len(), 999); + assert_eq!(g.other_relatives, expected); + } + #[test] fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { for (name, stem) in [ From 8f9e3007106e71998fa19352f22e14c8a809fb8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 18:07:01 -0800 Subject: [PATCH 08/22] Tests: the host name table lists the PageItem.controlBounds setter PageItem.controlBounds now throws that it is not available yet, through the same getter and setter as the other members that are not available, so the table of names the host adds lists controlBounds= as well. --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 52721f7c33..d56fd43e02 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -112,7 +112,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + controlBounds controlBounds= duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ From 4180df830d982adfbb0ec1059b7a08c56907e450 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:08:47 -0800 Subject: [PATCH 09/22] Tests: the script tests follow main's page item order and preset checks - The rasterize tests read `a` and `b` as the second and first page items, since the list starts with the topmost object. - The DocumentPreset byte-limit tests fill the 4 MB with 4,096-byte titles across many presets, since a title holds at most 4,096 bytes and the other settings take only their own kind of value. - The plugin test's ScriptGate gives the `held` field. --- crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_dom.rs | 26 ++++++++++++------- .../engine/src/tests/script_raster_capture.rs | 11 ++++---- 3 files changed, 23 insertions(+), 15 deletions(-) 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 1fc9de10d7..35164c3958 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1117,17 +1117,20 @@ fn document_preset_applies_only_its_given_fields() { #[test] fn document_preset_settings_are_limited_in_bytes() { let mut s = Session::new(); + // A title holds at most 4,096 bytes, so 1,005 presets with such a title and their six defaults + // hold 4,192,860 bytes, and the next preset's defaults bring that to 4,192,934 of 4,194,304. let out = log( &mut s, - "var big = new Array(1572865).join('a'), p = new DocumentPreset(), q = new DocumentPreset();\ - p.title = big; p.units = big; p.title = big; q.title = 'x'; vc.log(p.title.length);\ - try { q.colorMode = big; } catch (e) { vc.log([e.name, e.message]); }\ - vc.log(q.colorMode === undefined); p.title = 'short'; q.colorMode = big; vc.log(q.colorMode.length);", + "var big = new Array(4097).join('a'), ps = [];\ + for (var i = 0; i < 1005; i++) { var p = new DocumentPreset(); p.title = big; ps.push(p); }\ + var q = new DocumentPreset(); ps[0].title = big; vc.log(ps[0].title.length);\ + try { q.title = big; } catch (e) { vc.log([e.name, e.message]); }\ + vc.log(q.title === undefined); ps[0].title = 'short'; q.title = big; vc.log(q.title.length);", ); - assert_eq!(out[0], json!(1_572_864)); + assert_eq!(out[0], json!(4096), "a setting assigned again replaces what it held"); assert_eq!(out[1], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); assert_eq!(out[2], json!(true), "a refused setting is not stored"); - assert_eq!(out[3], json!(1_572_864), "replacing a setting frees what it held"); + assert_eq!(out[3], json!(4096), "replacing a setting frees what it held"); } /// A new `DocumentPreset`'s default settings count toward the 4 MB, so one that would pass the @@ -1135,15 +1138,18 @@ fn document_preset_settings_are_limited_in_bytes() { #[test] fn a_new_document_preset_is_refused_past_the_byte_limit() { let mut s = Session::new(); - // The six defaults hold 74 bytes; the two strings leave 10 bytes of the 4 MB free. + // The six defaults hold 74 bytes and a 4,096-byte title 4,098, so 1,005 presets with such a + // title and one more with a 1,358-byte title leave 10 bytes of the 4 MB free. let out = log( &mut s, - "var p = new DocumentPreset(); p.title = new Array(2097153).join('a'); p.units = new Array(2097065).join('b');\ + "var big = new Array(4097).join('a');\ + for (var i = 0; i < 1005; i++) { var f = new DocumentPreset(); f.title = big; }\ + var p = new DocumentPreset(); p.title = new Array(1359).join('b');\ try { new DocumentPreset(); vc.log('made'); } catch (e) { vc.log([e.name, e.message]); }\ - p.colorMode = 1; vc.log(p.colorMode); p.title = 'x'; vc.log(new DocumentPreset().width);", + p.documentBleedLink = true; vc.log(p.documentBleedLink); p.title = 'x'; vc.log(new DocumentPreset().width);", ); assert_eq!(out[0], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); - assert_eq!(out[1], json!(1), "a refused preset adds nothing to the count"); + assert_eq!(out[1], json!(true), "a refused preset adds nothing to the count"); assert_eq!(out[2], json!(612), "a preset below the limit is still made"); } diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 863b5d1db6..1dbbfe7b75 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -58,8 +58,9 @@ fn images(s: &Session) -> Vec<(u32, u32)> { out } -/// A script that selects `b` and rasterizes `a` (the first and second page items). -const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[0], b = d.pageItems[1]; b.name = 'b'; d.selection = [b];"; +/// A script that selects `b` and rasterizes `a` (the second and first page items: the list starts +/// with the topmost object). +const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[1], b = d.pageItems[0]; b.name = 'b'; d.selection = [b];"; #[test] fn script_rasterize_explicit_sources_preserves_selection() { @@ -249,12 +250,12 @@ fn script_rasterize_rejects_bad_clip_bounds() { ("'all'", "four numbers"), ]; for (bounds, message) in cases { - refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[0], {bounds});"), message); + refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[1], {bounds});"), message); } // `a` spans x 10 to 40: a rectangle at x 42 to 48 reaches only the 10 pt padding around it. refused( &mut s, - "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[0], [42, 280, 48, 240], o);", + "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[1], [42, 280, 48, 240], o);", "does not overlap the art", ); } @@ -262,7 +263,7 @@ fn script_rasterize_rejects_bad_clip_bounds() { #[test] fn script_rasterize_rejects_an_image_past_the_size_limit() { let (mut s, ..) = doc(); - let source = "var d = app.activeDocument, b = d.pageItems[1]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; + let source = "var d = app.activeDocument, b = d.pageItems[0]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; let e = failure(&mut s, source); assert!(e.contains("too large"), "{e}"); assert_eq!(images(&s), Vec::<(u32, u32)>::new()); From 5dbd4357c182f392dcb3717f02ea6e437319bc93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:21:54 -0800 Subject: [PATCH 10/22] Scripts: rasterize clips to fractional clip bounds and refuses clipping paths Rasterize with clipBounds keeps the pixel grid outward and clips the art to the exact rectangle, so a partial edge pixel keeps only its in-bounds coverage. A clipping path given by id is refused, with a message for clip groups and for clipped layers. app.open sends the file's read warnings to the console. A multi-file export refuses a destination that is a folder before writing any file. The DocumentPreset byte tests use the run's heap limit, which replaced the fixed 4 MB limit; the 4 MB sentence leaves docs/mcp.md. The controlBounds row matches main, where it has no setter. The two new script file messages stay English only, as AGENTS.md asks. --- crates/engine/src/cmd/fileio/export_names.rs | 3 + crates/engine/src/cmd/menucmds.rs | 28 +++++- crates/engine/src/script/dom/save_open.rs | 11 +++ crates/engine/src/tests/script_dom.rs | 98 +++++++++++-------- .../engine/src/tests/script_raster_capture.rs | 60 ++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- 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 | 8 +- 32 files changed, 160 insertions(+), 100 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..6c49622553 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -88,6 +88,9 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do if files.len() > 1 { for (p, _) in &files { super::may_write(p)?; + if std::path::Path::new(p.as_str()).is_dir() { + return Err(EngineError::Other(format!("{p}: is a folder, not a file"))); + } } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index a32d7dd3be..c441c73c6e 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -899,6 +899,7 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; let mut b = drawn.inflate(pad, pad); + let mut clip_bounds = None; if let Some(v) = p.get("clipBounds").filter(|v| !v.is_null()) { let [x0, y0, x1, y1] = super::finite_numbers::<4>(v).ok_or_else(|| bad(cmd, "clipBounds must be four finite numbers [x0, y0, x1, y1]"))?; if x1 <= x0 || y1 <= y0 { @@ -910,11 +911,13 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p if on_art.width() <= 0.0 || on_art.height() <= 0.0 { return Err(bad(cmd, "clipBounds does not overlap the art")); } + clip_bounds = Some(clip_rect); b = b.intersect(clip_rect); } let scale = ppi / 72.0; - // Snap to whole pixels. - let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); + // The image covers the bounds in whole pixels. + let px = |len: f64| (len * scale).ceil().max(1.0); + let region = Rect::new(b.x0, b.y0, b.x0 + px(b.width()) / scale, b.y0 + px(b.height()) / scale); // Create Clipping Mask: the image is clipped to the art's outline with its geometry effects // applied, as on the canvas. let clip = look @@ -932,7 +935,15 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .flatten() .map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)); - let tmp = isolated_doc(doc, nodes); + let mut tmp = isolated_doc(doc, nodes); + if let Some(rect) = clip_bounds { + let children = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()).map(std::mem::take).unwrap_or_default(); + let art = Node::group(tmp.alloc_id(), children); + let art = super::rasterfx::clip_group(&mut tmp, vectorcraft_geom::shapes::rectangle(rect), vectorcraft_geom::FillRule::NonZero, art); + if let Some(children) = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()) { + children.push(Arc::new(art)); + } + } let opts = raster.render_options(RasterFormat::Png); let (img, warning) = render_pixels(&tmp, region, scale, &opts, look.color_model)?; let png = @@ -977,6 +988,15 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); } + // A clipping path's image would clip its siblings to a rectangle. + if parent.is_some_and(Node::clips) && d.position(*id).is_some_and(|(_, i, _)| i == 0) { + let message = if parent.is_some_and(Node::is_layer) { + "is a layer's clipping path and cannot be rasterized on its own" + } else { + "is a clipping path; give its clip group's id" + }; + return Err(bad(cmd, format!("id {} {message}", id.0))); + } if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b8491cd284..618d1d4e91 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -705,6 +705,17 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { }), _ => None, }; + // Each warning from reading the file (content left out, an image that could not be read) goes + // to the console, as `addDocument` sends its profile's. + if let Data::Object(items) = &r { + for (k, v) in items { + if let ("warnings", Data::Array(ws)) = (k.as_str(), v) { + for w in ws.iter().filter_map(|w| if let Data::String(w) = w { Some(w) } else { None }) { + super::super::each_line(&format!("open: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + } + } + } let s = h.session.borrow(); let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; Ok(doc_ref(h, st.uid)) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ea8cf2a4ea..b80020077e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1476,47 +1476,6 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); } -/// The presets of one run hold at most 4 MB of settings together; a setting that replaces another -/// gives back what the old value held. -#[test] -fn document_preset_settings_are_limited_in_bytes() { - let mut s = Session::new(); - // A title holds at most 4,096 bytes, so 1,005 presets with such a title and their six defaults - // hold 4,192,860 bytes, and the next preset's defaults bring that to 4,192,934 of 4,194,304. - let out = log( - &mut s, - "var big = new Array(4097).join('a'), ps = [];\ - for (var i = 0; i < 1005; i++) { var p = new DocumentPreset(); p.title = big; ps.push(p); }\ - var q = new DocumentPreset(); ps[0].title = big; vc.log(ps[0].title.length);\ - try { q.title = big; } catch (e) { vc.log([e.name, e.message]); }\ - vc.log(q.title === undefined); ps[0].title = 'short'; q.title = big; vc.log(q.title.length);", - ); - assert_eq!(out[0], json!(4096), "a setting assigned again replaces what it held"); - assert_eq!(out[1], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); - assert_eq!(out[2], json!(true), "a refused setting is not stored"); - assert_eq!(out[3], json!(4096), "replacing a setting frees what it held"); -} - -/// A new `DocumentPreset`'s default settings count toward the 4 MB, so one that would pass the -/// limit is refused and leaves the count as it was. -#[test] -fn a_new_document_preset_is_refused_past_the_byte_limit() { - let mut s = Session::new(); - // The six defaults hold 74 bytes and a 4,096-byte title 4,098, so 1,005 presets with such a - // title and one more with a 1,358-byte title leave 10 bytes of the 4 MB free. - let out = log( - &mut s, - "var big = new Array(4097).join('a');\ - for (var i = 0; i < 1005; i++) { var f = new DocumentPreset(); f.title = big; }\ - var p = new DocumentPreset(); p.title = new Array(1359).join('b');\ - try { new DocumentPreset(); vc.log('made'); } catch (e) { vc.log([e.name, e.message]); }\ - p.documentBleedLink = true; vc.log(p.documentBleedLink); p.title = 'x'; vc.log(new DocumentPreset().width);", - ); - assert_eq!(out[0], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); - assert_eq!(out[1], json!(true), "a refused preset adds nothing to the count"); - assert_eq!(out[2], json!(612), "a preset below the limit is still made"); -} - #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); @@ -1565,6 +1524,63 @@ fn add_document_takes_only_a_document_preset() { assert_eq!(out, vec![json!(500)]); } +#[test] +fn document_preset_settings_are_limited_in_bytes() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var presets = [];\ + for (var k = 0; k < 1000; k++) { var p = new DocumentPreset(); p.title = 'old'; presets.push(p); }\ + var message = '';\ + try { for (var k = 0; k < presets.length; k++) presets[k].title = title; }\ + catch (e) { message = e.name + ': ' + e.message; }\ + vc.log(message); vc.log(k > 0 && k < presets.length); vc.log(presets[k].title);\ + presets[0].title = 'x'; presets[k].title = title;\ + vc.log(presets[0].title); vc.log(presets[k].title === title);", + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!( + out, + vec![ + json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)), + json!(true), + json!("old"), + json!("x"), + json!(true), + ] + ); +} + +#[test] +fn a_new_document_preset_is_refused_past_the_byte_limit() { + use crate::script::TEST_ENGINE_HEAP; + let preset_bytes = 6 * std::mem::size_of::() + "DocumentArtboardLayout.GridByRow".len(); + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + &format!( + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var first = new DocumentPreset(); first.title = title;\ + try {{ for (var k = 0; k < 2000; k++) {{ var p = new DocumentPreset(); p.title = title; }} }} catch (e) {{}}\ + var message = '';\ + try {{ for (var k = 0; k < 10000; k++) new DocumentPreset(); }}\ + catch (e) {{ message = e.name + ': ' + e.message; }}\ + vc.log(message); vc.log(k < 10000);\ + first.title = title.substring({preset_bytes});\ + vc.log((new DocumentPreset()).width);\ + var again = ''; try {{ new DocumentPreset(); }} catch (e) {{ again = e.name + ': ' + e.message; }}\ + vc.log(again);" + ), + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + let message = json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)); + assert_eq!(out, vec![message.clone(), json!(true), json!(612), message]); +} + #[test] fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 1dbbfe7b75..0e70175844 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -141,6 +141,66 @@ fn script_rasterize_clip_bounds_cut_the_image() { assert_eq!(images(&s), vec![(15, 40)]); } +/// A clip rectangle that ends partway through a pixel keeps partial coverage in the image's last +/// column and row. +#[test] +fn script_rasterize_fractional_clip_bounds_stay_inside_the_rectangle() { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; o.transparency = true; d.rasterize(a, [10, 280, 25.5, 240.5], o);" + ), + ); + assert_eq!(images(&s), vec![(16, 40)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + assert_eq!(pixels.get_pixel(14, 20)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(15, 20)[3]), "the last column keeps only its in-bounds coverage"); + assert_eq!(pixels.get_pixel(7, 38)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(7, 39)[3]), "the last row keeps only its in-bounds coverage"); +} + +/// A clip rectangle from a fractional origin that spans whole pixels keeps every one of them, +/// though the subtraction of its edges is not exact. +#[test] +fn script_rasterize_clip_bounds_from_a_fractional_origin_keep_whole_pixels() { + for (right, width, partial) in [(10.7, 3, false), (10.75, 4, true)] { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [10.4, 280, {right}, 240], o);" + ), + ); + assert_eq!(images(&s), vec![(width, 400)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let alpha = pixels.get_pixel(width - 1, 200)[3]; + if partial { + assert!((1..255).contains(&alpha), "the last column keeps only its in-bounds coverage"); + } else { + assert_eq!(alpha, 255, "the whole boundary pixel stays opaque"); + } + } +} + +#[test] +fn script_rasterize_rejects_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The clipping path is `b`, the topmost of the two. + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [b.0]})).unwrap_err().to_string(); + assert!(e.contains("is a clipping path"), "{e}"); + assert_eq!(undo_steps(&s), undo, "a refused clipping path adds no undo step"); + s.execute("object.rasterize", &json!({"ids": [a.0]})).unwrap(); +} + #[test] fn script_rasterize_disposes_several_sources_in_one_step() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index e76a217f2a..3c910cda0b 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -127,7 +127,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds controlBounds= duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0c091dcc91..c451ec9811 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6647,8 +6647,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 4309654e8d..d2a89194fa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5429,8 +5429,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 d356fd7ab2..70c167b084 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 3cab0128fe..e2ce6c9202 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5006,8 +5006,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 5bc9c90d1a..51b04c5526 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2838,8 +2838,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 1d177afc44..053e35e721 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5116,8 +5116,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 db1a87dbed..05c77549a0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5359,8 +5359,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 29a520a0a9..8f843cc11f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5073,8 +5073,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 323635ebc9..3bc5aaf219 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7850,8 +7850,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 eb7b957794..fedcfcf62b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5951,8 +5951,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 e43c36b300..3c434256fa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8913,8 +8913,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 cd54480a25..13d0656137 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5144,8 +5144,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 32eabfa175..97606b7e76 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5980,8 +5980,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 cbfae1b8d5..a8d2240536 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8653,8 +8653,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 839151841b..96e84b418e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5909,8 +5909,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 90facd6389..fada1fc205 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 3cc4572864..01d3571047 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5246,8 +5246,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 5e9c84ef5e..e3dd5ffeda 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6291,8 +6291,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 59d5006547..a2235998eb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5141,8 +5141,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 1a6a11ca81..41bda9072e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5014,8 +5014,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 7a624802e4..0ee286faa1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4842,8 +4842,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 39c04fe34e..e9dd432e72 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5128,8 +5128,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 8d10194145..8e9d5cac87 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5641,8 +5641,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 52440db23c..a7e94e826f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5636,8 +5636,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 a12a6a61cc..3a86a5b728 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2977,8 +2977,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 e427f114c3..0066455f24 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2868,8 +2868,7 @@ other files through `$`: `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. The settings of the `DocumentPreset` objects one run makes hold at most - 4 MB together, and an assignment past that throws a `RangeError`. Assigning one of its settings checks the value's kind: a value of the + starts with the defaults that page gives. Assigning one of its settings checks the value's kind: a value of the setting's enumeration, a finite number, a `title` string, `true` or `false` for `documentBleedLink`, or an array of four finite numbers for `documentBleedOffsetRect`. Any setting takes `undefined`, which unsets it. A value of another kind throws a `TypeError`, a `title` longer than 4096 bytes throws a `RangeError`, and the setting keeps @@ -11082,8 +11081,9 @@ Threading text from the in and out ports), and the other frames keep the text th refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. With `ids`, `object.rasterize` rasterizes those objects instead of the selection and leaves the selection as it was, without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id -listed twice, a layer, a path of a compound path or a part of another object that is not a group, and an object that -is locked or in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's +clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or +in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's `imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. From 88d9a6e601ab1e4e57318ab161ef804b9e80efd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 23:02:05 -0800 Subject: [PATCH 11/22] Scripts: script file writes and rasterize report their warnings Document.rasterize, imageCapture, saveAs and exportFile send command warnings to the Script Console, as app.open does. app.open no longer inherits the linked-file permissions of documents open at the start of the run. Rasterize by id refuses art on a locked artboard, and clip bounds within floating-point error of whole pixels use that pixel count. Capture sources leave out link paths the document cannot follow. --- crates/engine/src/cmd/links.rs | 5 +- crates/engine/src/cmd/menucmds.rs | 16 +++++- crates/engine/src/cmd/scripts.rs | 2 +- .../engine/src/script/dom/raster_capture.rs | 3 +- crates/engine/src/script/dom/save_open.rs | 35 +++++++----- crates/engine/src/script/mod.rs | 3 +- crates/engine/src/tests/link_paths.rs | 14 +++++ .../engine/src/tests/script_raster_capture.rs | 51 ++++++++++++++++- crates/engine/src/tests/script_save_open.rs | 55 +++++++++++++++++++ docs/mcp.md | 21 +++++-- 10 files changed, 176 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 78641c711b..9bec029957 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -212,7 +212,8 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { /// from, wherever it is stored, brush art included, whether or not a file is there: each place /// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, /// as its plate-change check finds them. A link's absolute stored and relative paths are listed -/// as they are too, for the relative path of every object in a group. +/// too, for the relative path of every object in a group. Document-path restrictions apply before +/// any filesystem probe. pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { let mut out = vec![]; for g in groups(d, None) { @@ -221,7 +222,7 @@ pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { let mut mains: Vec = std::iter::once(link.path.as_str()) .chain(link.relative.as_deref()) .filter(|p| Path::new(p).is_absolute()) - .map(str::to_string) + .filter_map(|p| fileio::document_path(p, base.doc).ok()) .collect(); mains.extend(places(&link, base)); for main in mains { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index c441c73c6e..e216a5531a 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -916,8 +916,14 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p } let scale = ppi / 72.0; // The image covers the bounds in whole pixels. - let px = |len: f64| (len * scale).ceil().max(1.0); - let region = Rect::new(b.x0, b.y0, b.x0 + px(b.width()) / scale, b.y0 + px(b.height()) / scale); + let px = |lo: f64, hi: f64| { + let pixels = (hi - lo) * scale; + let nearest = pixels.round(); + let error = 8.0 * f64::EPSILON * (lo.abs() + hi.abs()) * scale; + let pixels = if (pixels - nearest).abs() <= error { nearest } else { pixels }; + pixels.ceil().max(1.0) + }; + let region = Rect::new(b.x0, b.y0, b.x0 + px(b.x0, b.x1) / scale, b.y0 + px(b.y0, b.y1) / scale); // Create Clipping Mask: the image is clipped to the art's outline with its geometry effects // applied, as on the canvas. let clip = look @@ -975,6 +981,7 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { } } let mut roots = Vec::with_capacity(ids.len()); + let locks = d.locked_artboards(); for id in &ids { // The layers and groups from the top down to the object itself. let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; @@ -1000,6 +1007,9 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); } + if locks.holds_id(*id) { + return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); + } roots.push(*id); } Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index d895c3969f..4b1dfa0f31 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 9a3daccfbe..54682c1848 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -222,6 +222,7 @@ fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); } let r = on_doc(h, doc.uid, true, |h| command(h, "object.rasterize", &Value::Object(p)))?; + super::save_open::command_warnings(h, "rasterize", &r); let image = match &r { Data::Object(o) => o.iter().find_map(|(k, v)| match (k.as_str(), v) { ("imageId", Data::Number(n)) => super::whole(*n), @@ -421,7 +422,7 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { h.disk.borrow_mut().exact = true; let r = on_doc(h, doc.uid, false, |h| command(h, "document.export", &p)); h.disk.borrow_mut().exact = false; - r?; + super::save_open::command_warnings(h, "imageCapture", &r?); Ok(Data::Undefined) } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 618d1d4e91..9842150b5d 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -571,6 +571,23 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { r } +pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) { + if let Data::Object(items) = result { + for (key, value) in items { + let warnings: &[Data] = match (key.as_str(), value) { + ("warning", Data::String(_)) => std::slice::from_ref(value), + ("warnings", Data::Array(warnings)) => warnings, + _ => continue, + }; + for warning in warnings { + if let Data::String(warning) = warning { + super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + } + } + } +} + /// The path to give a command for the real path `real`. fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() @@ -602,7 +619,8 @@ 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 r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + command_warnings(h, "saveAs", &r); Ok(Data::Undefined) } @@ -656,7 +674,8 @@ 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 r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + command_warnings(h, "exportFile", &r); Ok(Data::Undefined) } @@ -705,17 +724,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { }), _ => None, }; - // Each warning from reading the file (content left out, an image that could not be read) goes - // to the console, as `addDocument` sends its profile's. - if let Data::Object(items) = &r { - for (k, v) in items { - if let ("warnings", Data::Array(ws)) = (k.as_str(), v) { - for w in ws.iter().filter_map(|w| if let Data::String(w) = w { Some(w) } else { None }) { - super::super::each_line(&format!("open: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); - } - } - } - } + command_warnings(h, "open", &r); let s = h.session.borrow(); let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; Ok(doc_ref(h, st.uid)) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ab50b47586..1f6cfa0b84 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1296,7 +1296,8 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value // the open documents; it also reads the files the documents open when the run began link to, as the // person left them. A document a script's command opened gives it no file. let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); - let gate = host.disk.borrow().gate(documents, host.linked()); + let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { host.linked() }; + let gate = host.disk.borrow().gate(documents, linked); let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // What the command opened, changed or gave another file is not as the person left it. diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index e39cf66896..b0a4303f23 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -100,6 +100,20 @@ fn places_named_from_a_share_are_not_followed_after_a_save_elsewhere() { assert_eq!(follow_from(link, on_share, Some(r"C:\b\poster.vectorcraft"), resolve), None); } +#[test] +fn capture_sources_exclude_paths_the_document_cannot_follow() { + let dir = Folder::new("capture-paths"); + let mut paths = far(&dir); + paths.push(dir.file("local.png")); + let path = save_linked(&dir, &paths); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let st = s.active().unwrap(); + let places = crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st)); + assert_eq!(far_reads(&places), Vec::<&String>::new(), "{places:?}"); + assert!(places.contains(&dir.file("local.png")), "local links remain capture sources: {places:?}"); +} + /// The final path Windows gives a folder of the drive `Z:` mapped to `\\server\share`. The /// share's root folder has no trailing separator (`\\?\UNC\server\share`). fn on_share(folder: &str) -> Option { diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 0e70175844..075d49baf5 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -166,12 +166,12 @@ fn script_rasterize_fractional_clip_bounds_stay_inside_the_rectangle() { /// though the subtraction of its edges is not exact. #[test] fn script_rasterize_clip_bounds_from_a_fractional_origin_keep_whole_pixels() { - for (right, width, partial) in [(10.7, 3, false), (10.75, 4, true)] { + for (left, right, width, partial) in [(10.4, 10.7, 3, false), (10.1, 10.4, 3, false), (10.4, 10.75, 4, true)] { let (mut s, ..) = doc(); log( &mut s, &format!( - "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [10.4, 280, {right}, 240], o);" + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [{left}, 280, {right}, 240], o);" ), ); assert_eq!(images(&s), vec![(width, 400)]); @@ -243,6 +243,53 @@ fn script_rasterize_rejects_locked_art() { refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); } +#[test] +fn rasterize_rejects_explicit_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap_err().to_string(); + assert!(e.contains("locked artboard"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked artboard"); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap(); +} + +#[test] +fn script_rasterize_logs_a_missing_image_warning() { + let (mut s, ..) = doc(); + let id = super::menucmds::place_undecodable_png(&mut s); + let out = run(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);").unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!( + lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("rasterize: ") && s.contains("couldn't be decoded")), + "{out}" + ); + assert_eq!(out["log"], json!(["RasterItem"])); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn image_capture_logs_a_missing_image_warning() { + let base = folder("warning"); + let (mut s, dir) = capture_doc(&base); + let id = super::menucmds::place_undecodable_png(&mut s); + let before = s.active().unwrap().doc.clone(); + let out = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("capture.png")))).unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!( + lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("imageCapture: ") && s.contains("couldn't be decoded")), + "{out}" + ); + assert!(dir.join("capture.png").is_file()); + assert!(s.active().unwrap().doc.node(id).is_some()); + assert_eq!(*s.active().unwrap().doc, *before); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_rasterize_rejects_art_inside_listed_art() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index d8d6a82a50..d08a6f316c 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,61 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn scripted_file_writes_log_command_warnings() { + for (method, extension, call) in [("saveAs", "pdf", "d.saveAs(file)"), ("exportFile", "png", "d.exportFile(file, ExportType.PNG24)")] { + let base = folder(&format!("warning-{method}")); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + super::menucmds::place_undecodable_png(&mut s); + let path = dir.join(format!("output.{extension}")); + let out = run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument, file = new File({}); {call};", quoted(&path))).unwrap(); + assert!(path.is_file(), "{method}"); + let prefix = format!("{method}: "); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!( + lines.iter().filter_map(Value::as_str).any(|s| s.starts_with(&prefix) && s.contains("couldn't be decoded")), + "{method}: {out}" + ); + let _ = std::fs::remove_dir_all(base); + } +} + +#[test] +fn open_does_not_inherit_an_existing_documents_link_permission() { + let base = folder("inherited-link"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let linked = base.join("outside/linked.png"); + std::fs::write(&linked, super::links::png(2, 2, [255, 0, 0])).unwrap(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("file.place", &json!({"path": linked.to_string_lossy(), "link": true})).unwrap(); + let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); + let page = dir.join("page.svg"); + std::fs::write( + &page, + format!(""), + ) + .unwrap(); + let capture = dir.join("existing.png"); + logged( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({})); app.open(new File({}));", quoted(&capture), quoted(&page)), + ); + let pixels = image::open(&capture).unwrap().to_rgb8(); + assert!(pixels.pixels().any(|p| p.0 == [255, 0, 0]), "existing art can still read its linked image"); + let mut images = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + images.push((im.width, im.height, im.link.as_ref().is_some_and(|l| l.hash.is_some()))); + } + }); + assert_eq!(images, [(64, 64, false)], "the new document cannot read the inherited link"); + 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() { diff --git a/docs/mcp.md b/docs/mcp.md index 0066455f24..bce70dfbbf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3148,8 +3148,11 @@ other files through `$`: document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs` and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the - files a command reads or writes besides the one named, such as an SVG's linked files, are - read and written only where the script's folders allow. `userInteractionLevel` does not change what a command + files `app.open` reads besides the one named, such as an SVG's linked files, are read only where the script's + folders allow, including links inherited from documents that were already open. Rendering existing documents + can still read their inherited linked files. Ancillary writes require the script's write grants. + `saveAs` and `exportFile` send command warnings to the Script Console with the method name. + `userInteractionLevel` does not change what a command does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the @@ -3177,7 +3180,10 @@ other files through `$`: below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in - a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With + a locked layer or group or on a locked artboard throw an error, and nothing changes. + Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional + dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. + `rasterize` keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an error that says they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With @@ -3186,7 +3192,8 @@ other files through `$`: opened for writing is checked, and a path that is an open document's file or a file one of them links throws an error, also when that file is missing. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS - image's plate files beside each, and the documents count whether they were open when the run started or were + image's plate files beside each. Paths rejected by the document's path restrictions are excluded before filesystem + probes. The documents count whether they were open when the run started or were opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to @@ -11083,8 +11090,10 @@ With `ids`, `object.rasterize` rasterizes those objects instead of the selection without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or -in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) -keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's +in a locked layer or group or on a locked artboard are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. +Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions +round up. The result's `imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. ```json From 06eb0f252affed9df848712ff016eb9fd77e25e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:35:27 -0800 Subject: [PATCH 12/22] Scripts: saveAs takes its format from the script's file name Document.saveAs without options picks the format from the name the script gave, before a symbolic link is resolved, and a name without a known extension keeps the document's format. A save that writes several files refuses a destination that is a folder before it writes any of them. imageCapture leaves out source paths outside the automation read roots before it probes them. The host and scriptcheck name test lists saveAs as a method, which it is now. --- crates/engine/src/cmd/fileio/save.rs | 14 ++++-- crates/engine/src/cmd/scripts.rs | 2 +- .../engine/src/script/dom/raster_capture.rs | 29 ++++++++++- crates/engine/src/script/dom/save_open.rs | 9 +++- crates/engine/src/tests/script_save_open.rs | 48 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- docs/mcp.md | 7 ++- 7 files changed, 99 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f31f01a7aa..3c9c11cb85 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1074,10 +1074,14 @@ impl SaveJob { // 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. #[cfg(not(target_arch = "wasm32"))] - if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) - { - write(p, bytes)?; + if files.len() > 1 { + for (p, bytes) in &files { + if super::may_write(p).is_err() { + write(p, bytes)?; + } else if std::path::Path::new(p).is_dir() { + return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file"))); + } + } } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1383,7 +1387,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written or is a directory, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 1a945e68ba..f9d9c7c33c 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 54682c1848..dfa77fc1f2 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -26,6 +26,7 @@ //! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 //! to 255. The file is written only where the script's `File` objects may write, and never over //! an open document's file or a file one of them links. +//! Source paths outside the automation read roots are excluded before filesystem probes. //! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is //! drawn; the resolution is never lowered to make it fit. //! - `windowCapture` throws an error that says it is not available yet. @@ -295,7 +296,12 @@ fn sources_on_disk(h: &Host) -> Vec { paths.extend(st.path.clone()); paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st))); } - paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect() + paths.iter().filter_map(|p| source_place(p)).collect() +} + +fn source_place(path: &str) -> Option { + crate::file_access::check_read(path).ok()?; + placed(std::path::Path::new(path)) } /// A file as its folder's real path and its name. @@ -495,3 +501,24 @@ pub(super) fn classes(link: &Link) -> Vec { }) .collect() } + +#[cfg(test)] +mod source_tests { + use super::*; + + #[test] + fn capture_sources_exclude_files_outside_automation_roots() { + let dir = vectorcraft_testkit::TempDir::new("capture-source-roots"); + let allowed = dir.join("allowed"); + std::fs::create_dir(&allowed).unwrap(); + let inside = allowed.join("doc.vectorcraft"); + let outside = dir.join("linked.png"); + std::fs::write(&inside, b"document").unwrap(); + std::fs::write(&outside, b"linked").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&allowed], &[&allowed]).unwrap(); + crate::file_access::confine(roots.as_ref(), || { + assert!(source_place(&inside.to_string_lossy()).is_some()); + assert!(source_place(&outside.to_string_lossy()).is_none()); + }); + } +} diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 9842150b5d..ff3905c32d 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -17,8 +17,9 @@ //! commands may use. //! //! VectorCraft's own rules, which the help pages do not state: -//! - `saveAs` without options saves in the format the path's extension names; it writes the file -//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and +//! - `saveAs` without options selects the format from the script's file name before resolving +//! symbolic links. A name without a recognized extension uses the document's current format. +//! Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and //! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds. //! `exportFile` adds the format's extension unless the name already ends //! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes @@ -617,6 +618,10 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { p.insert("options".into(), Value::Object(q)); } } + if !p.contains_key("format") { + let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id); + p.insert("format".into(), json!(format)); + } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 87c935fca9..beb9d3cc87 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -10,6 +10,54 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[cfg(unix)] +#[test] +fn save_as_uses_the_scripts_extension_before_following_a_link() { + let base = folder("save-link-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let target = dir.join("target.vectorcraft"); + let alias = dir.join("alias.svg"); + std::fs::write(&target, b"keep").unwrap(); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias))); + assert!(std::fs::read_to_string(&target).unwrap().contains(" PathBuf { let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f0bf02daa9..2d7e9dc97c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -112,7 +112,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ - pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \ + pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs 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 6c914eb6c0..e10094250a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3272,7 +3272,8 @@ through `$`: `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/); - without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and + without options the name supplied by the script picks the format before symbolic links are resolved. + A name without a recognized extension uses the document's current format. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and `exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to @@ -3337,7 +3338,7 @@ through `$`: opened for writing is checked, and a path that is an open document's file or a file one of them links throws an error, also when that file is missing. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS - image's plate files beside each. Paths rejected by the document's path restrictions are excluded before filesystem + image's plate files beside each. Paths rejected by the document's path restrictions or the automation read roots are excluded before filesystem probes. The documents count whether they were open when the run started or were opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or @@ -12094,6 +12095,8 @@ or in `options` (`file.formatOptions {format}` lists them with their values): - `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to `-.` beside the file: that artboard and the art touching it. The result's `files` lists every file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files. + The save checks every destination before writing. If any destination is a directory or access is refused, + it leaves every file unwritten. The same check applies to EPS saves that write multiple files. - `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a brush's art shows embedded keeps its pixels either way. A `version` older than the current one saves the placed From b3dede0a252e7a8f1f123829fd43b633fdd95fc8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 01:04:03 -0800 Subject: [PATCH 13/22] Scripts: rasterize refuses art holding locked objects Rasterize by id refuses a group that holds a locked object, as it refuses a locked object itself. A save that writes several files refuses an existing read-only destination before it writes any of them. --- crates/engine/src/cmd/fileio/save.rs | 11 +++++-- .../engine/src/cmd/fileio/tests_readonly.rs | 31 +++++++++++++++++++ crates/engine/src/cmd/menucmds.rs | 14 ++++++--- .../engine/src/tests/script_raster_capture.rs | 24 ++++++++++++++ docs/mcp.md | 5 +-- 5 files changed, 75 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 3c9c11cb85..5e9b0f374b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1078,8 +1078,13 @@ impl SaveJob { for (p, bytes) in &files { if super::may_write(p).is_err() { write(p, bytes)?; - } else if std::path::Path::new(p).is_dir() { - return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file"))); + } else if let Ok(meta) = std::fs::metadata(p) { + if meta.is_dir() { + return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file"))); + } + if meta.is_file() && meta.permissions().readonly() { + return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))); + } } } } @@ -1387,7 +1392,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written or is a directory, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when access to one of a save's files is refused, or it is a directory or an existing read-only file, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs index ae9762efc3..bee4258f8b 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -28,6 +28,37 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() { } } +#[test] +fn readonly_sidecar_leaves_every_save_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("save-readonly-sidecar"); + for format in ["vectorcraft", "eps"] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let path = dir.join(format!("Poster.{format}")).to_string_lossy().into_owned(); + let params = if format == "eps" { json!({"path": path, "useArtboards": true}) } else { json!({"path": path, "separateArtboards": true}) }; + let saved = session.execute("file.saveAs", ¶ms).unwrap(); + let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect(); + assert!(files.len() > 1); + let before: Vec<_> = files.iter().map(std::fs::read).collect::>().unwrap(); + session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let sidecar = files.last().unwrap(); + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = session.execute("file.saveAs", ¶ms); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for (file, bytes) in files.iter().zip(before) { + assert_eq!(std::fs::read(file).unwrap(), bytes, "{file}"); + } + assert_eq!(*session.doc().unwrap().doc, *doc); + assert!(session.doc().unwrap().is_dirty()); + } +} + #[test] fn readonly_failed_save_keeps_document_and_options() { let mut session = Session::new(); diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index e216a5531a..0556fe7e20 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -969,8 +969,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p } /// The objects `ids` names for Rasterize, in paint order: each an object of the active document, -/// listed once, and neither it nor a layer or group it is in locked. An object inside another -/// listed one is left out, as `edit::roots_of` leaves it out of a selection. +/// listed once, with no locks on it, its descendants, or a layer or group it is in. An object +/// inside another listed one is left out, as `edit::roots_of` leaves it out of a selection. fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { let ids = super::checked_ids_param(s, p, "ids", cmd)?; let d = &s.doc()?.doc; @@ -1004,8 +1004,12 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { }; return Err(bad(cmd, format!("id {} {message}", id.0))); } - if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { - return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); + let mut locked = false; + if let Some(node) = d.node(*id) { + node.walk(&mut |n| locked |= n.locked); + } + if locked || up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { + return Err(bad(cmd, format!("id {} is locked, in a locked layer or group, or contains locked art", id.0))); } if locks.holds_id(*id) { return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 2e17a65248..bd4fe83f92 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -243,6 +243,30 @@ fn script_rasterize_rejects_locked_art() { refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); } +#[test] +fn script_rasterize_rejects_groups_with_locked_descendants() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [inner, c.0]})).unwrap(); + let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "locked": true})).unwrap(); + for id in [inner, outer] { + let before = s.active().unwrap().doc.clone(); + let selection = s.active().unwrap().selection.objects.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(s.active().unwrap().selection.objects, selection); + assert_eq!(undo_steps(&s), undo); + } + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); + s.execute("object.setProps", &json!({"id": a.0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap(); +} + #[test] fn rasterize_rejects_explicit_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index e10094250a..24c406d511 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3326,7 +3326,8 @@ through `$`: below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in - a locked layer or group or on a locked artboard throw an error, and nothing changes. + a locked layer or group or on a locked artboard throw an error, and nothing changes. An object containing + locked descendants also throws an error. Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With @@ -12095,7 +12096,7 @@ or in `options` (`file.formatOptions {format}` lists them with their values): - `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to `-.` beside the file: that artboard and the art touching it. The result's `files` lists every file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files. - The save checks every destination before writing. If any destination is a directory or access is refused, + The save checks every destination before writing. If any destination is a directory, an existing read-only file, or access is refused, it leaves every file unwritten. The same check applies to EPS saves that write multiple files. - `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a From ef62c429ea6756d52d1e2d85637c43a0c22c1e8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:41:00 -0800 Subject: [PATCH 14/22] Scripts: one clipping-path guard for move and duplicate The merge of main brought main's check that refuses placing an object below a clipping path, with the message "an object cannot go below a clipping mask" and an exception for moving the clipping path below itself. The branch's own earlier check ran first with a different message, so main's nothing_is_placed_below_a_clipping_path test failed on the message, and the self-move exception could not run. The branch's check is removed and its test now expects main's message. --- crates/engine/src/script/dom.rs | 4 ---- crates/engine/src/tests/script_dom.rs | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4a7ffb71cc..ad60249cce 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2708,10 +2708,6 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s } Placement::Above | Placement::Below => { let parent = d.parent_of(target).ok_or_else(|| HostError::Error("an object cannot go beside a top-level layer".into()))?; - let mask = d.node(parent).is_some_and(crate::doc::Node::clips) && d.position(target).is_some_and(|(_, i, _)| i == 0); - if how == Placement::Below && mask { - return Err(HostError::Error("an object cannot go below a clipping group's clipping path".into())); - } (parent, Some(target)) } }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bf7caa1578..936d21263c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -826,7 +826,7 @@ fn nothing_goes_below_a_clipping_path() { "var p = app.activeDocument.pageItems; p.getByName('loose').duplicate(p.getByName('mask'), ElementPlacement.PLACEAFTER);", ] { let e = failure(&mut s, source); - assert!(e.contains("cannot go below a clipping group's clipping path"), "{source}: {e}"); + assert!(e.contains("an object cannot go below a clipping mask"), "{source}: {e}"); } assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "a refused move changes nothing"); assert_eq!(undo_steps(&s), steps); From b91beb68fd92bb39d757f7162e9e928e572d2f34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:56:42 -0800 Subject: [PATCH 15/22] Scripts: refuse read-only export files, hidden rasterize sources and capture over write-only documents - A multi-file export checks every destination before writing and refuses an existing read-only file, as save does, so no file is written. - object.rasterize and Document.rasterize refuse an id that is hidden or in a hidden layer or group, as they refuse locked ones. - imageCapture compares open documents and linked files that only a write root covers, so it no longer replaces such a document's file. - The blank-capture test also checks the pixel count, as test-lint asks. --- crates/engine/src/cmd/fileio/export_names.rs | 6 +++- .../engine/src/cmd/fileio/tests_readonly.rs | 27 +++++++++++++++ crates/engine/src/cmd/menucmds.rs | 5 ++- .../engine/src/script/dom/raster_capture.rs | 33 ++++++++++++++----- .../engine/src/tests/script_raster_capture.rs | 20 +++++++++++ docs/mcp.md | 15 +++++---- 6 files changed, 89 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 6c49622553..b38da6bb84 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -88,9 +88,13 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do if files.len() > 1 { for (p, _) in &files { super::may_write(p)?; - if std::path::Path::new(p.as_str()).is_dir() { + let Ok(meta) = std::fs::metadata(p) else { continue }; + if meta.is_dir() { return Err(EngineError::Other(format!("{p}: is a folder, not a file"))); } + if meta.is_file() && meta.permissions().readonly() { + return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))); + } } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs index bee4258f8b..a60e9841b2 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -59,6 +59,33 @@ fn readonly_sidecar_leaves_every_save_destination_unchanged() { } } +#[test] +fn readonly_export_file_leaves_every_export_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("export-readonly-sidecar"); + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let enc = super::Encoded { files: vec![(None, b"new main".to_vec()), (Some(1), b"new board".to_vec())], ..Default::default() }; + let path = dir.join("Poster.svg").to_string_lossy().into_owned(); + let files: Vec = enc.named(&doc, &path).into_iter().map(|(p, _)| p).collect(); + assert_eq!(files.len(), 2); + for file in &files { + std::fs::write(file, b"old").unwrap(); + } + let sidecar = &files[1]; + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = super::write_encoded(Some(&path), "Poster.svg", &doc, &enc, json!({})); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for file in &files { + assert_eq!(std::fs::read(file).unwrap(), b"old", "{file}"); + } +} + #[test] fn readonly_failed_save_keeps_document_and_options() { let mut session = Session::new(); diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 0556fe7e20..4eba8c7235 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -1014,6 +1014,9 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { if locks.holds_id(*id) { return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); } + if up.iter().any(|a| d.node(*a).is_some_and(|n| !n.visible)) { + return Err(bad(cmd, format!("id {} is hidden or in a hidden layer or group", id.0))); + } roots.push(*id); } Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index dfa77fc1f2..1eb66216a1 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -299,8 +299,13 @@ fn sources_on_disk(h: &Host) -> Vec { paths.iter().filter_map(|p| source_place(p)).collect() } +/// An open document or linked file inside the automation read or write roots: one that only a write +/// root covers is compared too, since a capture may write there. A path outside both is left out +/// before it is looked up, as no capture can write it; the refusal names only the requested path. fn source_place(path: &str) -> Option { - crate::file_access::check_read(path).ok()?; + if crate::file_access::check_read(path).is_err() && crate::file_access::check_write_unrecorded(path).is_err() { + return None; + } placed(std::path::Path::new(path)) } @@ -507,18 +512,28 @@ mod source_tests { use super::*; #[test] - fn capture_sources_exclude_files_outside_automation_roots() { + fn capture_sources_keep_files_outside_automation_read_roots() { let dir = vectorcraft_testkit::TempDir::new("capture-source-roots"); - let allowed = dir.join("allowed"); - std::fs::create_dir(&allowed).unwrap(); - let inside = allowed.join("doc.vectorcraft"); - let outside = dir.join("linked.png"); + let readable = dir.join("readable"); + let writable = dir.join("writable"); + std::fs::create_dir(&readable).unwrap(); + std::fs::create_dir(&writable).unwrap(); + let inside = readable.join("doc.vectorcraft"); + // An open document that only a write root covers: a capture to its path must still be + // refused. + let outside = writable.join("other.vectorcraft"); + // Outside every root: no capture can write it, so it is not looked up. + let elsewhere = dir.join("linked.png"); std::fs::write(&inside, b"document").unwrap(); - std::fs::write(&outside, b"linked").unwrap(); - let roots = crate::file_access::AutomationRoots::new(&[&allowed], &[&allowed]).unwrap(); + std::fs::write(&outside, b"document").unwrap(); + std::fs::write(&elsewhere, b"linked").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&readable], &[&writable]).unwrap(); crate::file_access::confine(roots.as_ref(), || { assert!(source_place(&inside.to_string_lossy()).is_some()); - assert!(source_place(&outside.to_string_lossy()).is_none()); + assert!(source_place(&elsewhere.to_string_lossy()).is_none()); + let source = source_place(&outside.to_string_lossy()).expect("a source outside the read roots is still compared"); + let target = placed(&outside).unwrap(); + assert!(same_file(&target, &source)); }); } } diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index bd4fe83f92..057c022dea 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -267,6 +267,25 @@ fn script_rasterize_rejects_groups_with_locked_descendants() { s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap(); } +#[test] +fn rasterize_rejects_explicit_hidden_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"id": group, "visible": false})).unwrap(); + for id in [a.0, b.0] { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("hidden"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + } + s.execute("object.setProps", &json!({"id": a.0, "visible": true})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72})).unwrap(); +} + #[test] fn rasterize_rejects_explicit_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); @@ -527,6 +546,7 @@ fn image_capture_of_bounds_without_art_is_blank() { for (name, blank) in [("blank.png", [255, 255, 255, 255]), ("clear.png", [0, 0, 0, 0])] { let img = png(&dir.join(name)); assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.pixels().len(), 2500, "{name}"); assert!(img.pixels().all(|p| p.0 == blank), "{name}: every pixel is {blank:?}"); } assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); diff --git a/docs/mcp.md b/docs/mcp.md index ad8d7dea5b..e0356af3d1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3273,7 +3273,8 @@ through `$`: format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and - when the script's folders refuse one of those files, none of them is written; a write that fails once the + when the script's folders refuse one of those files, or one is a folder or an existing read-only file, none of + them is written; a write that fails once the first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and @@ -3671,8 +3672,8 @@ through `$`: below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in - a locked layer or group or on a locked artboard throw an error, and nothing changes. An object containing - locked descendants also throws an error. + a locked layer or group or on a locked artboard, and one that is hidden or in a hidden layer or group throw an + error, and nothing changes. An object containing locked descendants also throws an error. Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With @@ -3684,8 +3685,9 @@ through `$`: opened for writing is checked, and a path that is an open document's file or a file one of them links throws an error, also when that file is missing. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS - image's plate files beside each. Paths rejected by the document's path restrictions or the automation read roots are excluded before filesystem - probes. The documents count whether they were open when the run started or were + image's plate files beside each. Paths rejected by the document's path restrictions, and paths outside both the + automation read and write roots, are left out of the comparison. Open documents and linked files that only + a write root covers are still compared, and the error names only the requested path. The documents count whether they were open when the run started or were opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to @@ -11667,7 +11669,8 @@ With `ids`, `object.rasterize` rasterizes those objects instead of the selection without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or -in a locked layer or group or on a locked artboard are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +in a locked layer or group or on a locked artboard, and an object that is hidden or in a hidden layer or group, are +refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. The result's From cb98b72a58ba37758dc4896a2b7950e87e477df9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:10:57 -0800 Subject: [PATCH 16/22] Scripts: fix a run's linked files at its first step A run whose first step is an exact document.open still reads the open documents' linked files then, so a link retargeted while the run is paused gives a later command no read access to the new target. The open itself still gets no linked-file access. --- crates/engine/src/script/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 250fbfe744..db7cddce49 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1349,7 +1349,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value // the open documents; it also reads the files the documents open when the run began link to, as the // person left them. A document a script's command opened gives it no file. let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); - let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { host.linked() }; + // The linked files are fixed at the run's first step, also when that step is an exact open that gets none. + let linked = host.linked(); + let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { linked }; let gate = host.disk.borrow().gate(documents, linked); let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); From 8714ec7731d6b700cc52a76a234038470831e4b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:10:56 -0800 Subject: [PATCH 17/22] Scripts: rasterize refuses sources clipped differently, capture checks file identity - object.rasterize with ids refuses objects whose nearest clip group or clipped layer differs, before rendering: the image goes where the last object is, so mixed sources would be clipped by another object's path. - Document.rasterize reads the image id from the command's result inside the run's savepoint, so an id above 2^53 binds the new RasterItem and a missing id undoes the edit. - Document.imageCapture refuses a destination that is another name of an open document's file or a linked file (same device and inode, or same volume and file index), and on Unix any file with other hard links, which an in-place write would change under every name. - Docs: gaps.md and target-app-parity.md list what rasterizing and capturing still lack; mcp.md states the clipping rule, the hard-link rule and that a later OS write failure can leave some files written. --- crates/engine/src/cmd/menucmds.rs | 17 +++- .../engine/src/script/dom/raster_capture.rs | 67 ++++++++++++---- .../engine/src/tests/script_raster_capture.rs | 78 +++++++++++++++++++ docs/gaps.md | 6 +- docs/mcp.md | 14 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 161 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 4eba8c7235..7af1bae33d 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the nearest clip group or clipped layer around each object must be the same one, or none for all; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -1019,6 +1019,21 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { } roots.push(*id); } + // The image goes where the last object is, so every object must share its clipping context: + // the nearest clip group or clipped layer around it, or none. + let clipper = |id: NodeId| d.ancestry(id).and_then(|up| up.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(Node::clips))); + if let Some(first) = roots.first() { + let context = clipper(*first); + if let Some(other) = roots.iter().find(|id| clipper(**id) != context) { + return Err(bad( + cmd, + format!( + "id {} is clipped differently from id {}: the nearest clip group or clipped layer around each object must be the same one, or none for all", + other.0, first.0 + ), + )); + } + } Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) } diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 1eb66216a1..3a2100a148 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -25,8 +25,10 @@ //! `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with //! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 //! to 255. The file is written only where the script's `File` objects may write, and never over -//! an open document's file or a file one of them links. -//! Source paths outside the automation read roots are excluded before filesystem probes. +//! an open document's file or a file one of them links, under any of its names (a hard link +//! included); on Unix it is never written over a file that has other hard links. Source paths +//! outside both the automation read and write roots are excluded before +//! filesystem probes. //! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is //! drawn; the resolution is never lowered to make it fit. //! - `windowCapture` throws an error that says it is not available yet. @@ -38,8 +40,8 @@ use vectorcraft_geom::Rect; use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{ - Answer, Described, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, class, command, coordinate, current, frame, given, item_of, item_ref, - later, method, named, num, on_doc, returns, text, this_doc, with_doc, + Answer, Described, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, class, command, command_value, coordinate, current, frame, given, + item_of, item_ref, later, method, named, num, on_doc, returns, text, this_doc, with_doc, }; /// The lowest resolution the option classes take, in pixels per inch. @@ -222,16 +224,14 @@ fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { if let Some(r) = clip { p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); } - let r = on_doc(h, doc.uid, true, |h| command(h, "object.rasterize", &Value::Object(p)))?; + // The image's id is read from the command's own result inside the run's savepoint, so an id + // that a script number cannot hold exactly still names the image, and a missing one undoes the edit. + let (r, image) = on_doc(h, doc.uid, true, |h| { + let (r, value) = command_value(h, "object.rasterize", &Value::Object(p))?; + let image = value.get("imageId").and_then(Value::as_u64).ok_or_else(|| HostError::Error("the image was not made".into()))?; + Ok((r, image)) + })?; super::save_open::command_warnings(h, "rasterize", &r); - let image = match &r { - Data::Object(o) => o.iter().find_map(|(k, v)| match (k.as_str(), v) { - ("imageId", Data::Number(n)) => super::whole(*n), - _ => None, - }), - _ => None, - }; - let image = image.ok_or_else(|| HostError::Error("the image was not made".into()))?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; Ok(item_ref(h, st, crate::NodeId(image))) @@ -343,6 +343,42 @@ fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { false } +/// Whether two existing paths name one file on disk, such as two hard links to it: the same device +/// and file number on Unix, or the same volume and file index on Windows. `false` when either is +/// missing. +fn same_identity(a: &std::path::Path, b: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + matches!((std::fs::metadata(a), std::fs::metadata(b)), (Ok(x), Ok(y)) if (x.dev(), x.ino()) == (y.dev(), y.ino())) + } + #[cfg(windows)] + { + same_file::is_same_file(a, b).unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (a, b); + false + } +} + +/// Whether the existing file at `p` has more than one name on Unix: writing into it in place, when +/// its folder refuses a replacement, would change the file under its other names too. Always +/// `false` off Unix, where [`same_identity`] compares the protected files instead. +fn has_other_links(p: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.nlink() > 1) + } + #[cfg(not(unix))] + { + let _ = p; + false + } +} + /// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a /// symbolic link or another file. fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool { @@ -418,9 +454,12 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { check_size(region, ppi)?; let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; let target = placed(&real); - if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s))) { + if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); } + if has_other_links(&real) { + return Err(HostError::Error(format!("imageCapture cannot write over a file that has other hard links: {path}"))); + } let p = json!({ "path": crate::cmd::findfiles::plain(real).to_string_lossy(), "format": "png", diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 057c022dea..6f1c6357f5 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -201,6 +201,46 @@ fn script_rasterize_rejects_a_clipping_path() { s.execute("object.rasterize", &json!({"ids": [a.0]})).unwrap(); } +/// The new `RasterItem` is bound to the image's exact id, also for an id above 2^53, which a +/// script number does not hold exactly. +#[test] +fn script_rasterize_binds_an_image_id_above_two_to_the_53() { + let (mut s, a, _) = doc(); + 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, &format!("{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); r.name = 'img';")); + assert_eq!(out, [json!("RasterItem")]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + let mut named = Vec::new(); + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + named.push((n.id, n.name.clone())); + } + }); + assert_eq!(named.len(), 1, "{named:?}"); + assert!(named[0].0.0 > 1u64 << 53, "{named:?}"); + assert_eq!(named[0].1.as_deref(), Some("img"), "the item names the image itself"); +} + +/// The image takes the place of the last object, so objects in different clipping contexts are +/// refused before anything changes. +#[test] +fn script_rasterize_rejects_sources_clipped_differently() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 20.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [c.0, a.0]})).unwrap_err().to_string(); + assert!(e.contains("is clipped differently"), "{e}"); + assert!(*before == *s.active().unwrap().doc, "a refused call leaves the document as it was"); + assert_eq!(undo_steps(&s), undo); + assert!(s.active().unwrap().doc.node(c).is_some(), "the unclipped object stays"); +} + #[test] fn script_rasterize_disposes_several_sources_in_one_step() { let (mut s, a, b) = doc(); @@ -627,6 +667,44 @@ fn capture_rejects_bad_options_and_names() { let _ = std::fs::remove_dir_all(base); } +/// A second hard link to an open document's file names the same file, so a capture to it is refused. +#[test] +fn capture_refuses_a_hard_link_to_an_open_document() { + let base = folder("hard-link"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + let alias = dir.join("alias.png"); + if std::fs::hard_link(&source, &alias).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&alias).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a capture never writes over a file with other hard links, which an in-place write would +/// change under every name. +#[cfg(unix)] +#[test] +fn capture_refuses_a_file_with_other_hard_links() { + let base = folder("other-links"); + let (mut s, dir) = capture_doc(&base); + let other = dir.join("other.bin"); + std::fs::write(&other, b"kept").unwrap(); + let alias = dir.join("alias.png"); + std::fs::hard_link(&other, &alias).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("other hard links"), "{e}"); + assert_eq!(std::fs::read(&other).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_denied_or_source_path_writes_nothing() { let base = folder("denied"); diff --git a/docs/gaps.md b/docs/gaps.md index 1ba18317d8..6054399bc1 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -868,8 +868,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi document's `fullName`, `path` and `saved`, and close it with `Document.close`. Scripts also have each document's linked and embedded images (`placedItems` and `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. + `TracingObject` and `TracingOptions`; the tracing options VectorCraft has no setting for are still missing. + `Document.rasterize` and `Document.imageCapture` are there; `RasterizeOptions.convertSpotColors`, + `convertTextToOutlines` and `includeLayers` set to true, and `Document.windowCapture`, still throw an error that + says they are not available yet. 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 diff --git a/docs/mcp.md b/docs/mcp.md index bf6bdf5099..68e27ec1f7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3924,7 +3924,8 @@ through `$`: writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in a locked layer or group or on a locked artboard, and one that is hidden or in a hidden layer or group throw an - error, and nothing changes. An object containing locked descendants also throws an error. + error, and nothing changes. An object containing locked descendants also throws an error, as do objects whose + nearest clip group or clipped layer is not the same one (or none for all). Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With @@ -3934,7 +3935,8 @@ through `$`: `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` opened for writing is checked, and a path that is an open document's file or a file one of them links throws an - error, also when that file is missing. The linked files are every place opening the document looks for a link's + error, also when that file is missing or when the path is another hard link to it. On Unix a path to a file that + has other hard links also throws an error. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS image's plate files beside each. Paths rejected by the document's path restrictions, and paths outside both the automation read and write roots, are left out of the comparison. Open documents and linked files that only @@ -11942,7 +11944,8 @@ without the objects it replaced. An object inside another listed one is left out listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or in a locked layer or group or on a locked artboard, and an object that is hidden or in a hidden layer or group, are -refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +refused, and nothing changes. The nearest clip group or clipped layer around each object must be the same one, or +none for all of them; objects clipped differently are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. The result's @@ -12772,8 +12775,9 @@ or in `options` (`file.formatOptions {format}` lists them with their values): - `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to `-.` beside the file: that artboard and the art touching it. The result's `files` lists every file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files. - The save checks every destination before writing. If any destination is a directory, an existing read-only file, or access is refused, - it leaves every file unwritten. The same check applies to EPS saves that write multiple files. + The save checks every destination before writing. If any destination is a directory, an existing read-only file, or + one the file-access policy refuses, it leaves every file unwritten. The same check applies to EPS saves that write + multiple files. A write that the operating system refuses later can still leave some of the files written. - `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a brush's art shows embedded keeps its pixels either way. A `version` older than the current one saves the placed diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 948c4d9ecb..f35feb211d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1118,7 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.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`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`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: `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: `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. `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. 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: 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 14e8959bc0e31df27bae7ee4ef0a16b9d870f2c5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:19:16 -0800 Subject: [PATCH 18/22] Scripts: tighten rasterize clip bounds and imageCapture destination checks - object.rasterize and Document.rasterize refuse clipBounds that reach none of the selected objects' own bounds, including a rectangle in the gap between two of them, instead of replacing the art with a background-only image. - imageCapture checks its destination again on every write the export makes and as the file is committed, so a destination that becomes a link to an open document or a linked file while the art renders is refused. - imageCapture refuses a destination whose real path is not valid UTF-8 instead of writing under a name with its bytes replaced. - A missing linked file's name in the other Unicode normalization form counts as the linked file in folders that ignore the form (macOS, and casefolded folders on Linux). - The hard-link tests skip on volumes without hard links. - docs/mcp.md: imageCapture rounds clip dimensions to the nearest pixel; rasterize rounds fractional dimensions up. --- Cargo.lock | 1 + crates/engine/Cargo.toml | 3 + crates/engine/src/cmd/menucmds.rs | 13 +- crates/engine/src/file_access.rs | 42 ++++++- crates/engine/src/script/dom.rs | 2 + .../engine/src/script/dom/raster_capture.rs | 83 +++++++++++-- .../engine/src/tests/script_raster_capture.rs | 115 +++++++++++++++++- docs/mcp.md | 4 +- 8 files changed, 239 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..50d594fab9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8741,6 +8741,7 @@ dependencies = [ "skrifa 0.47.0", "thiserror 2.0.21", "tiff", + "unicode-normalization", "vectorcraft-affinity", "vectorcraft-apischema", "vectorcraft-brush", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 945e6c92be..0fe4f7d10e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -71,6 +71,9 @@ serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } +# Whether two file names differ only in their Unicode normalization form, in a folder that ignores +# it (`script::dom::raster_capture`). Already in Cargo.lock, so this adds no new crate. +unicode-normalization = "0.1.26" # Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a # file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile, diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 7af1bae33d..661fe741e7 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -896,7 +896,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .collect(); // What the art draws, its geometry effects applied. - let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); + let each: Vec = nodes.iter().filter_map(|n| vectorcraft_render::drawn_bounds(doc, n)).collect(); + let b = each.iter().fold(None, |acc, r| vectorcraft_geom::union_opt(acc, Some(*r))); let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; let mut b = drawn.inflate(pad, pad); let mut clip_bounds = None; @@ -906,9 +907,13 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p return Err(bad(cmd, "clipBounds must have x1 greater than x0 and y1 greater than y0")); } let clip_rect = Rect::new(x0, y0, x1, y1); - // The rectangle must reach the art itself, not only the padding around it. - let on_art = drawn.intersect(clip_rect); - if on_art.width() <= 0.0 || on_art.height() <= 0.0 { + // The rectangle must reach the art itself, not only the padding around it or the gap + // between two of the selected objects. + let reaches = |r: &Rect| { + let on = r.intersect(clip_rect); + on.width() > 0.0 && on.height() > 0.0 + }; + if !each.iter().any(reaches) { return Err(bad(cmd, "clipBounds does not overlap the art")); } clip_bounds = Some(clip_rect); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 55c06cc130..afc8c52e73 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -510,11 +510,43 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// A check every write on this thread must pass as well, given the path as written or, at the +/// moment a checked write commits on Unix, the opened folder's real path with the file's name +/// ([`with_write_guard`]). +pub(crate) type WriteGuard = std::rc::Rc Result<(), String>>; + +thread_local! { + static WRITE_GUARD: RefCell> = const { RefCell::new(None) }; +} + +/// Puts the write guard it replaced back when dropped (also when `f` panics). +struct RestoreWriteGuard(Option); + +impl Drop for RestoreWriteGuard { + fn drop(&mut self) { + let previous = self.0.take(); + WRITE_GUARD.with(|g| *g.borrow_mut() = previous); + } +} + +/// Runs `f` with `guard` checked on every write it makes on this thread, again at the moment each +/// checked write commits, so a destination that is changed after an earlier check is checked as it +/// is then. +pub(crate) fn with_write_guard(guard: WriteGuard, f: impl FnOnce() -> T) -> T { + let _restore = RestoreWriteGuard(WRITE_GUARD.with(|g| g.replace(Some(guard)))); + f() +} + +fn check_write_guard(path: &Path) -> Result<(), String> { + WRITE_GUARD.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g(path)) +} + /// [`check_write`] without adding `path` to the files a script run reports as written, for a /// check made before anything is written. pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write) + check_gate(path, Access::Write)?; + check_write_guard(Path::new(path)) } /// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been @@ -523,12 +555,14 @@ pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { #[cfg(unix)] pub(crate) fn check_write_real(real: &Path) -> Result<(), String> { current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?; - GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write)) + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))?; + check_write_guard(real) } -/// Whether a write here is checked: roots are in force, or a script's command runs. +/// Whether a write here is checked: roots are in force, a script's command runs, or a write guard +/// is in force ([`with_write_guard`]). pub(crate) fn writes_checked() -> bool { - current().is_some() || in_script_command() + current().is_some() || in_script_command() || WRITE_GUARD.with(|g| g.borrow().is_some()) } /// A file's modification time and length; `None` when there is no file at `path`. diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 607a20362e..b08a961396 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -108,6 +108,8 @@ mod paths; pub mod preferences; mod print; mod raster_capture; +#[cfg(test)] +pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT; mod save_open; mod tags; mod text; diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 3a2100a148..36fec48381 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -321,9 +321,65 @@ fn placed(p: &std::path::Path) -> Option { } /// Whether two [`placed`] files are one file: the same folder, and the same name, or names that -/// differ only in letter case in a folder whose volume ignores case. +/// differ only in letter case in a folder whose volume ignores case, or only in their Unicode +/// normalization form in a folder whose volume ignores that. fn same_file(a: &Placed, b: &Placed) -> bool { - same_folder(&a.0, &b.0) && (a.1 == b.1 || (a.1.to_string_lossy().to_lowercase() == b.1.to_string_lossy().to_lowercase() && ignores_case(&a.0))) + if !same_folder(&a.0, &b.0) { + return false; + } + if a.1 == b.1 { + return true; + } + let (x, y) = (a.1.to_string_lossy(), b.1.to_string_lossy()); + let form = |s: &str| unicode_normalization::UnicodeNormalization::nfc(s).collect::(); + if form(&x) == form(&y) { + return ignores_normalization(&a.0); + } + let (lx, ly) = (x.to_lowercase(), y.to_lowercase()); + if form(&lx) != form(&ly) || !ignores_case(&a.0) { + return false; + } + lx == ly || ignores_normalization(&a.0) +} + +/// Whether file names in the real folder `folder` ignore their Unicode normalization form: the +/// first of the folder's first 256 entries whose name changes between the composed (NFC) and +/// decomposed (NFD) forms, and that is not a symbolic link, is looked up in the other form, and +/// names ignore the form when that finds the same entry. With no such entry, names ignore the form +/// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that +/// ignores letter case (ext4 and f2fs casefolding also ignore the form), and keep it elsewhere. +fn ignores_normalization(folder: &std::path::Path) -> bool { + use unicode_normalization::UnicodeNormalization; + for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { + let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue }; + let (c, d): (String, String) = (name.nfc().collect(), name.nfd().collect()); + let other = if name == c { d } else { c }; + if other != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(other)); + } + } + cfg!(target_os = "macos") || (cfg!(target_os = "linux") && ignores_case(folder)) +} + +/// The check `imageCapture` makes on the file it writes, `p`, given as written or as the real path +/// of its folder with its name: it is none of the `sources` ([`sources_on_disk`]), not one of them +/// under another name, and has no other hard links. +fn capture_target_check(p: &std::path::Path, sources: &[Placed], shown: &str) -> Result<(), String> { + let real = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if placed(&real).is_some_and(|t| sources.iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { + return Err(format!("imageCapture cannot write over an open document or a file it links: {shown}")); + } + if has_other_links(&real) { + return Err(format!("imageCapture cannot write over a file that has other hard links: {shown}")); + } + Ok(()) +} + +#[cfg(test)] +thread_local! { + /// Run once in `imageCapture` after its checks and before its export, for tests that change the + /// destination in between. + pub(crate) static BEFORE_CAPTURE_EXPORT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and @@ -453,15 +509,18 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { }; check_size(region, ppi)?; let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; - let target = placed(&real); - if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { - return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); - } - if has_other_links(&real) { - return Err(HostError::Error(format!("imageCapture cannot write over a file that has other hard links: {path}"))); - } + let sources = sources_on_disk(h); + let shown = path.to_string(); + // Checked here, and again as the export commits its file, so a destination changed into a link + // to a protected file while the art renders is refused too. + let guard = move |p: &std::path::Path| capture_target_check(p, &sources, &shown); + guard(&real).map_err(HostError::Error)?; + let plain = crate::cmd::findfiles::plain(real); + let Some(plain) = plain.to_str() else { + return Err(HostError::Error(format!("imageCapture cannot write to a path that is not valid UTF-8: {path}"))); + }; let p = json!({ - "path": crate::cmd::findfiles::plain(real).to_string_lossy(), + "path": plain, "format": "png", "rect": [region.x0, region.y0, region.width(), region.height()], "ppi": ppi, @@ -469,8 +528,10 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { "antiAlias": anti_alias, "includeArtboardFill": false, }); + #[cfg(test)] + BEFORE_CAPTURE_EXPORT.with(|f| f.borrow_mut().take().map(|f| f())); h.disk.borrow_mut().exact = true; - let r = on_doc(h, doc.uid, false, |h| command(h, "document.export", &p)); + let r = crate::file_access::with_write_guard(std::rc::Rc::new(guard), || on_doc(h, doc.uid, false, |h| command(h, "document.export", &p))); h.disk.borrow_mut().exact = false; super::save_open::command_warnings(h, "imageCapture", &r?); Ok(Data::Undefined) diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 6f1c6357f5..ac12a3e22f 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -444,6 +444,20 @@ fn script_rasterize_rejects_bad_clip_bounds() { ); } +#[test] +fn object_rasterize_refuses_clip_bounds_between_the_sources() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + // The rectangle lies inside the box around `a` and `b` but reaches neither of them. + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [55, 45, 65, 55]})).unwrap_err().to_string(); + assert!(e.contains("does not overlap the art"), "{e}"); + assert_eq!(undo_steps(&s), undo, "no edit"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); + // A rectangle that reaches only `a` is still accepted. + s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [30, 30, 65, 55]})).unwrap(); + assert_eq!(images(&s).len(), 1); +} + #[test] fn script_rasterize_rejects_an_image_past_the_size_limit() { let (mut s, ..) = doc(); @@ -567,6 +581,22 @@ fn image_capture_exact_clip_bounds_and_matte() { let _ = std::fs::remove_dir_all(base); } +/// `imageCapture` rounds fractional clip dimensions to the nearest whole pixel, as +/// `document.export` does, where `rasterize` rounds them up. +#[test] +fn image_capture_rounds_fractional_clip_dimensions_to_the_nearest_pixel() { + let base = folder("nearest"); + let (mut s, dir) = capture_doc(&base); + let source = format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 300, 10.25, 289.75], o);", + quoted(&dir.join("n.png")) + ); + script(&mut s, &base, &source); + let img = png(&dir.join("n.png")); + assert_eq!((img.width(), img.height()), (10, 10), "10.25 pt at 72 ppi"); + let _ = std::fs::remove_dir_all(base); +} + /// Bounds that miss every object still give an image of that area, blank or transparent. #[test] fn image_capture_of_bounds_without_art_is_blank() { @@ -698,13 +728,88 @@ fn capture_refuses_a_file_with_other_hard_links() { let other = dir.join("other.bin"); std::fs::write(&other, b"kept").unwrap(); let alias = dir.join("alias.png"); - std::fs::hard_link(&other, &alias).unwrap(); + if std::fs::hard_link(&other, &alias).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); assert!(e.contains("other hard links"), "{e}"); assert_eq!(std::fs::read(&other).unwrap(), b"kept"); let _ = std::fs::remove_dir_all(base); } +/// A destination that becomes a second name of an open document's file after the capture's checks, +/// while the art renders, is refused as the export commits its file. +#[test] +fn capture_refuses_a_destination_linked_to_an_open_document_during_the_export() { + let base = folder("rebind"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let target = dir.join("late.png"); + let probe = dir.join("probe-link"); + if std::fs::hard_link(&source, &probe).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + std::fs::remove_file(&probe).unwrap(); + let (from, to) = (source.clone(), target.clone()); + crate::script::dom::BEFORE_CAPTURE_EXPORT.with(|f| *f.borrow_mut() = Some(Box::new(move || std::fs::hard_link(&from, &to).unwrap()))); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept", "the late link is left as it was"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a destination whose real path is not valid UTF-8 is refused before anything is written, +/// rather than written under a name with its bytes replaced. +#[cfg(unix)] +#[test] +fn capture_refuses_a_destination_that_is_not_utf8() { + use std::os::unix::ffi::OsStrExt; + let base = folder("non-utf8"); + let (mut s, dir) = capture_doc(&base); + let odd = dir.join(std::ffi::OsStr::from_bytes(b"odd\xff")); + if std::fs::create_dir(&odd).is_err() { + // The volume refuses names that are not UTF-8. + let _ = std::fs::remove_dir_all(base); + return; + } + // A link with a UTF-8 name that leads into the folder whose name is not. + let link = dir.join("plain"); + std::os::unix::fs::symlink(&odd, &link).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&link.join("x.png")))); + assert!(e.contains("not valid UTF-8"), "{e}"); + assert_eq!(std::fs::read_dir(&odd).unwrap().count(), 0, "nothing written"); + assert!(!dir.join("odd\u{fffd}").exists(), "nothing written under the replaced name"); + let _ = std::fs::remove_dir_all(base); +} + +/// On macOS, whose volumes look names up in either Unicode normalization form, a missing linked +/// file's name in the other form is the linked file. +#[cfg(target_os = "macos")] +#[test] +fn capture_to_a_missing_links_name_in_the_other_normalization_form_writes_nothing() { + let base = folder("missing-nfd"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // The link's name is composed (NFC); the capture names it decomposed (NFD). + place_linked( + &mut s, + "cafe", + vectorcraft_doc::LinkInfo { path: "caf\u{e9}.png".into(), relative: Some("caf\u{e9}.png".into()), ..Default::default() }, + ); + let nfd = dir.join("cafe\u{301}.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&nfd))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!nfd.exists() && !dir.join("caf\u{e9}.png").exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_denied_or_source_path_writes_nothing() { let base = folder("denied"); @@ -812,11 +917,15 @@ fn capture_to_a_missing_links_path_writes_nothing() { } else { script(&mut s, &base, &text); assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); - // Two names for one file that differ only in case show that the folder keeps case. + // Two names for one file that differ only in case show that the folder keeps case. A + // volume without hard links skips this part. let sub = dir.join("sub"); std::fs::create_dir(&sub).unwrap(); std::fs::write(sub.join("probe.txt"), b"x").unwrap(); - std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); + if std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).is_err() { + let _ = std::fs::remove_dir_all(base); + return; + } s.edit("Place", |d, _| { let id = d.alloc_id(); let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); diff --git a/docs/mcp.md b/docs/mcp.md index e57e827b60..04d3ee75f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3946,8 +3946,8 @@ through `$`: a locked layer or group or on a locked artboard, and one that is hidden or in a hidden layer or group throw an error, and nothing changes. An object containing locked descendants also throws an error, as do objects whose nearest clip group or clipped layer is not the same one (or none for all). - Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional - dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. + In `rasterize`, clip dimensions within floating-point error of a whole pixel use that whole pixel count, and other + fractional dimensions round up. `imageCapture` rounds each dimension to the nearest whole pixel. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an From 96ba49f5bd79d0999d1d90dbccf341f4e85ebcb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:09:11 -0800 Subject: [PATCH 19/22] Files: check a write again before it is put in place off Unix Off Unix, write_atomic_checked asked `allowed` once, before the file was written, so a destination that stopped being allowed while the file was filled still received it. The check now runs again after the fill, right before the rename, and again before the content is copied over a file whose folder refuses the rename. A refusal removes the staging file and leaves the target as it was. The hard-link fixtures in the capture tests unwrap the link again, as the other hard-link tests in the engine do (script_io.rs, plugins.rs). --- .../engine/src/tests/script_raster_capture.rs | 14 +-- crates/format/src/atomic.rs | 90 +++++++++++++++++-- 2 files changed, 85 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index ac12a3e22f..9e0d53c696 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -728,11 +728,7 @@ fn capture_refuses_a_file_with_other_hard_links() { let other = dir.join("other.bin"); std::fs::write(&other, b"kept").unwrap(); let alias = dir.join("alias.png"); - if std::fs::hard_link(&other, &alias).is_err() { - // The volume has no hard links. - let _ = std::fs::remove_dir_all(base); - return; - } + std::fs::hard_link(&other, &alias).unwrap(); let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); assert!(e.contains("other hard links"), "{e}"); assert_eq!(std::fs::read(&other).unwrap(), b"kept"); @@ -917,15 +913,11 @@ fn capture_to_a_missing_links_path_writes_nothing() { } else { script(&mut s, &base, &text); assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); - // Two names for one file that differ only in case show that the folder keeps case. A - // volume without hard links skips this part. + // Two names for one file that differ only in case show that the folder keeps case. let sub = dir.join("sub"); std::fs::create_dir(&sub).unwrap(); std::fs::write(sub.join("probe.txt"), b"x").unwrap(); - if std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).is_err() { - let _ = std::fs::remove_dir_all(base); - return; - } + std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); s.edit("Place", |d, _| { let id = d.alloc_id(); let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index dd0cd4cc6c..30c55f3cc0 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -265,15 +265,19 @@ pub fn write_atomic_checked( } } -/// See the Unix version. +/// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is +/// filled, right before it is put in place; a refusal then removes the temporary file and leaves +/// `path` unchanged. #[cfg(not(unix))] pub fn write_atomic_checked( path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>, - allowed: impl FnOnce(&Path) -> io::Result<()>, + allowed: impl Fn(&Path) -> io::Result<()>, ) -> io::Result<()> { allowed(path)?; - write_atomic_with(path, fill) + let replacing = path.exists(); + let create = |tmp: &Path| if replacing { create_private(tmp) } else { create_new(tmp) }; + write_atomic_staged(path, fill, create, || allowed(path), |tmp, target| std::fs::rename(tmp, target)) } /// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links @@ -404,6 +408,18 @@ fn write_atomic_stepping( fill: impl FnOnce(&mut File) -> io::Result<()>, create: impl FnOnce(&Path) -> io::Result, rename: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> io::Result<()> { + write_atomic_staged(path, fill, create, || Ok(()), rename) +} + +/// [`write_atomic_stepping`], with `check` run after the temporary file is filled and right before +/// it is put in place. An error from `check` removes the temporary file and leaves `path` unchanged. +fn write_atomic_staged( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + create: impl FnOnce(&Path) -> io::Result, + check: impl Fn() -> io::Result<()>, + rename: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> io::Result<()> { let target = resolve_link(path)?; let beside = temp_path(&target)?; @@ -420,7 +436,7 @@ fn write_atomic_stepping( }; let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); - if let Err(e) = filled { + if let Err(e) = filled.and_then(|()| check()) { // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); return Err(e); @@ -435,7 +451,7 @@ fn write_atomic_stepping( e } }; - write_over(&tmp, &target, refused) + write_over(&tmp, &target, refused, &check) } /// The content of `tmp`, which is whole and flushed, copied into `target` itself, and `tmp` @@ -443,8 +459,8 @@ fn write_atomic_stepping( /// writing it is untouched: `tmp` is removed and `refused` returned. When what it holds can't be /// copied aside first ([`keep_old`]) it is untouched too: `tmp` stays and the error names it. When /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the -/// error says where they are. -fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { +/// error says where they are. `check` runs again right before `target` is overwritten. +fn write_over(tmp: &Path, target: &Path, refused: io::Error, check: &dyn Fn() -> io::Result<()>) -> io::Result<()> { let old = tmp.with_extension("old"); let over = Over { tmp: &|| tmp.to_path_buf(), @@ -461,7 +477,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { #[cfg(unix)] create_target: &|| create_new(target), synced: &|| sync_written_parent(target), - still_allowed: &|| Ok(()), + still_allowed: check, }; write_over_in(&over, refused) } @@ -1753,6 +1769,64 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A check that refuses after the file is filled keeps the old file, removes the temporary file + /// and tries no rename, whether the folder takes the temporary file or not. + #[test] + fn a_check_refused_after_the_fill_keeps_the_file() { + let d = dir("staged-check"); + let path = d.join("staged-check.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let renamed = std::cell::Cell::new(false); + let rename = |_: &Path, _: &Path| { + renamed.set(true); + Ok(()) + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), |_| denied(), || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(!renamed.get() && leftovers(&d, "staged-check.vectorcraft").is_empty()); + // A folder that refuses the rename: the check runs again before the file is written over. + let calls = std::cell::Cell::new(0); + let check = || { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("moved away")) } else { Ok(()) } + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, check, |_, _| denied()); + assert!(r.is_err_and(|e| e.to_string().contains("moved away"))); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "staged-check.vectorcraft").is_empty()); + let staged = format!(".staged-check.vectorcraft.{}-", std::process::id()); + let in_system = std::fs::read_dir(std::env::temp_dir()).unwrap().filter_map(Result::ok); + assert!(!in_system.into_iter().any(|e| e.file_name().to_string_lossy().starts_with(&staged)), "the system's folder keeps no staging file"); + let _ = std::fs::remove_dir_all(&d); + } + + /// Off Unix the check runs again after the file is filled: a refusal at that point keeps the + /// old file and leaves no temporary file. + #[cfg(not(unix))] + #[test] + fn a_checked_write_checks_again_before_the_file_is_put_in_place() { + let d = dir("checked-twice"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let calls = std::cell::Cell::new(0); + let r = write_atomic_checked( + &path, + |f| f.write_all(b"new"), + |_| { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("no longer allowed")) } else { Ok(()) } + }, + ); + assert_eq!(r.unwrap_err().to_string(), "no longer allowed"); + assert_eq!(calls.get(), 2); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "doc.vectorcraft").is_empty()); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn write_new_never_replaces_what_is_there() { let d = dir("new"); From 4e90d6c21114cdf1b422b1ca5e5d6fc23044a3fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 00:09:32 -0800 Subject: [PATCH 20/22] Scripts: same_folder builds without a needless bool on Windows On Windows the Unix block in same_folder is compiled out, which left `if a == b { return true; } false` and failed clippy's needless_bool lint with -D warnings in the Windows CI run. The early return now sits inside the Unix block and the other platforms compare the paths. Behavior is unchanged on every platform. --- crates/engine/src/script/dom/raster_capture.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 36fec48381..38c8eb5437 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -386,17 +386,21 @@ thread_local! { /// file number, so a path spelled in another letter case on a volume that ignores case still /// matches. On Windows a real path carries the letter case stored on disk. fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { - if a == b { - return true; - } #[cfg(unix)] { use std::os::unix::fs::MetadataExt; + if a == b { + return true; + } if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { return x.dev() == y.dev() && x.ino() == y.ino(); } + false + } + #[cfg(not(unix))] + { + a == b } - false } /// Whether two existing paths name one file on disk, such as two hard links to it: the same device From ade0e47f4808303d70bb5ca4b08cb928bf7ab191 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:35:18 -0800 Subject: [PATCH 21/22] Scripts: refused writes create no file; Linux reads the casefold flag A refused rename that falls back to copying into the target no longer creates a missing target before the final authorization check. The target is created only after that check, on every platform, so a refusal at the final check leaves the path absent. An existing target is still opened with O_CREAT, so Linux's fs.protected_regular applies. imageCapture no longer treats an empty Linux folder as ignoring the Unicode normalization form. It reads the folder's casefold inode flag (FS_IOC_GETFLAGS) instead, so a missing linked cafe\u{301}.png no longer matches cafe\u{e9}.png in an ordinary folder, and a casefolded folder still matches both spellings. --- .../engine/src/script/dom/raster_capture.rs | 55 ++++++++++++++++++- crates/format/src/atomic.rs | 46 +++++++++++----- 2 files changed, 86 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 38c8eb5437..b7385a6b94 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -347,7 +347,8 @@ fn same_file(a: &Placed, b: &Placed) -> bool { /// decomposed (NFD) forms, and that is not a symbolic link, is looked up in the other form, and /// names ignore the form when that finds the same entry. With no such entry, names ignore the form /// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that -/// ignores letter case (ext4 and f2fs casefolding also ignore the form), and keep it elsewhere. +/// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the +/// form. Elsewhere, and on Linux when the flag can't be read, names keep the form. fn ignores_normalization(folder: &std::path::Path) -> bool { use unicode_normalization::UnicodeNormalization; for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { @@ -358,7 +359,31 @@ fn ignores_normalization(folder: &std::path::Path) -> bool { return finds_same(&entry.path(), &folder.join(other)); } } - cfg!(target_os = "macos") || (cfg!(target_os = "linux") && ignores_case(folder)) + #[cfg(target_os = "linux")] + { + casefolded(folder) + } + #[cfg(not(target_os = "linux"))] + { + cfg!(target_os = "macos") + } +} + +/// `FS_CASEFOLD_FL` from Linux's `include/uapi/linux/fs.h`: the folder looks names up casefolded. +#[cfg(target_os = "linux")] +const FS_CASEFOLD_FL: u32 = 0x4000_0000; + +/// Whether the Linux folder `folder` carries the casefold inode flag, read with +/// `FS_IOC_GETFLAGS`. `false` when the folder can't be opened or its flags can't be read. +#[cfg(target_os = "linux")] +fn casefolded(folder: &std::path::Path) -> bool { + std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_some_and(|f| has_casefold(f.bits())) +} + +/// Whether the inode flags `bits` include `FS_CASEFOLD_FL`. +#[cfg(target_os = "linux")] +fn has_casefold(bits: u32) -> bool { + bits & FS_CASEFOLD_FL != 0 } /// The check `imageCapture` makes on the file it writes, `p`, given as written or as the real path @@ -640,4 +665,30 @@ mod source_tests { assert!(same_file(&target, &source)); }); } + + /// In an empty Linux folder, names that differ only in their normalization form are one file + /// only when the folder is casefolded. On a folder without the flag they are distinct, and + /// nothing is written into the folder to find out. + #[cfg(target_os = "linux")] + #[test] + fn names_in_another_normalization_form_match_only_in_a_casefolded_empty_folder() { + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-distinct"); + let folder = std::fs::canonicalize(&*dir).unwrap(); + let (linked, capture): (Placed, Placed) = ((folder.clone(), "cafe\u{301}.png".into()), (folder.clone(), "caf\u{e9}.png".into())); + assert_eq!(same_file(&capture, &linked), casefolded(&folder)); + assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 0); + } + + /// A casefolded folder, which looks a name up in either normalization form, is recognized by + /// its inode flag, and a folder that can't be read is not taken for one. + #[cfg(target_os = "linux")] + #[test] + fn a_casefolded_folder_is_recognized_by_its_inode_flag() { + assert!(has_casefold(FS_CASEFOLD_FL)); + assert!(has_casefold(FS_CASEFOLD_FL | 0x10)); + assert!(!has_casefold(0x10)); + assert!(!has_casefold(0)); + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-missing"); + assert!(!casefolded(&dir.join("missing"))); + } } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 30c55f3cc0..83901874fd 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -473,8 +473,17 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error, check: &dyn Fn() -> remove_tmp: &|| { let _ = std::fs::remove_file(tmp); }, - open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, - #[cfg(unix)] + // A missing target is created by `create_target`, after the last check. An existing one is + // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. + open_target: &|write| { + if !write { + return File::open(target); + } + if matches!(std::fs::symlink_metadata(target), Err(e) if e.kind() == io::ErrorKind::NotFound) { + return Err(io::ErrorKind::NotFound.into()); + } + OpenOptions::new().write(true).create(true).truncate(false).open(target) + }, create_target: &|| create_new(target), synced: &|| sync_written_parent(target), still_allowed: check, @@ -497,10 +506,9 @@ struct Over<'a> { /// Best effort. remove_tmp: &'a dyn Fn(), /// Opens the target without truncating it for writing when `true`, or for reading when `false`. - /// Checked Unix writes defer creation of a missing target to `create_target`. + /// It never creates a missing target: `create_target` does that, after the final check. open_target: &'a dyn Fn(bool) -> io::Result, /// Creates a missing target after the final check and fails if its name is taken. - #[cfg(unix)] create_target: &'a dyn Fn() -> io::Result, /// The target's folder flushed, after the target is written. synced: &'a dyn Fn() -> io::Result<()>, @@ -510,7 +518,7 @@ struct Over<'a> { /// [`write_over`] through `over`. fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { - // Checked Unix writes create a missing target only after the final check. + // A missing target is created only after the final check. if let Err(e) = (over.still_allowed)() { (over.remove_tmp)(); return Err(e); @@ -518,7 +526,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { let opened = (over.open_tmp)().and_then(|from| { let to = match (over.open_target)(true) { Ok(to) => Some(to), - #[cfg(unix)] Err(e) if e.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e), }; @@ -563,7 +570,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { } let mut to = match to { Some(to) => to, - #[cfg(unix)] None => match (over.create_target)() { Ok(to) => to, // A file put at the name meanwhile is left alone, and reported as there. @@ -576,11 +582,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { return Err(refused); } }, - #[cfg(not(unix))] - None => { - (over.remove_tmp)(); - return Err(refused); - } }; let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); @@ -1116,6 +1117,26 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A refused rename onto a missing file that is no longer allowed at the final check does not + /// create the file. + #[test] + fn a_refused_rename_does_not_create_a_missing_file_once_no_longer_allowed() { + let d = dir("no-rename-missing-disallowed"); + let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let check = || { + checks.set(checks.get() + 1); + if checks.get() == 1 { Ok(()) } else { Err(io::Error::other("moved outside")) } + }; + let e = write_over(&tmp, &path, denied::<()>().unwrap_err(), &check).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!path.exists(), "the refused write created {}", path.display()); + assert!(!tmp.exists()); + let _ = std::fs::remove_dir_all(d); + } + /// A refused rename whose folder is no longer allowed by the time the file would be overwritten /// leaves the file as it was, and neither copy stays behind. #[test] @@ -1137,7 +1158,6 @@ mod tests { let _ = std::fs::remove_file(&tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, - #[cfg(unix)] create_target: &|| create_new(&path), synced: &|| Ok(()), still_allowed: &|| { From 4a1ac38ac3bf05160bf2deb41695fc90e8d80405 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:59:58 -0800 Subject: [PATCH 22/22] Scripts: a Linux folder whose casefold flag can't be read is taken as casefolded When the folder can't be opened or `FS_IOC_GETFLAGS` fails, `casefolded` returned false, so `imageCapture` treated names that differ only in their normalization form as two files and could write over a source document. It now returns false only when the flags are read and the flag is clear. --- crates/engine/src/script/dom/raster_capture.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index b7385a6b94..f067b430d4 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -348,7 +348,7 @@ fn same_file(a: &Placed, b: &Placed) -> bool { /// names ignore the form when that finds the same entry. With no such entry, names ignore the form /// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that /// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the -/// form. Elsewhere, and on Linux when the flag can't be read, names keep the form. +/// form, as they are taken to when the flag can't be read. Elsewhere names keep the form. fn ignores_normalization(folder: &std::path::Path) -> bool { use unicode_normalization::UnicodeNormalization; for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { @@ -374,10 +374,11 @@ fn ignores_normalization(folder: &std::path::Path) -> bool { const FS_CASEFOLD_FL: u32 = 0x4000_0000; /// Whether the Linux folder `folder` carries the casefold inode flag, read with -/// `FS_IOC_GETFLAGS`. `false` when the folder can't be opened or its flags can't be read. +/// `FS_IOC_GETFLAGS`. `true` when the folder can't be opened or its flags can't be read: `false` +/// only when the flags are read and the flag is clear. #[cfg(target_os = "linux")] fn casefolded(folder: &std::path::Path) -> bool { - std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_some_and(|f| has_casefold(f.bits())) + std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_none_or(|f| has_casefold(f.bits())) } /// Whether the inode flags `bits` include `FS_CASEFOLD_FL`. @@ -680,7 +681,8 @@ mod source_tests { } /// A casefolded folder, which looks a name up in either normalization form, is recognized by - /// its inode flag, and a folder that can't be read is not taken for one. + /// its inode flag. A folder whose flags can't be read is taken for one, so a capture is never + /// written over a source under a name in another normalization form. #[cfg(target_os = "linux")] #[test] fn a_casefolded_folder_is_recognized_by_its_inode_flag() { @@ -689,6 +691,6 @@ mod source_tests { assert!(!has_casefold(0x10)); assert!(!has_casefold(0)); let dir = vectorcraft_testkit::TempDir::new("capture-nfd-missing"); - assert!(!casefolded(&dir.join("missing"))); + assert!(casefolded(&dir.join("missing"))); } }