diff --git a/Cargo.lock b/Cargo.lock index ff70d04bdf..7c6d5f5c89 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/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index f44b390a70..19c754be4b 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::access::may_write_file(p)?; + if std::fs::metadata(p).is_ok_and(|meta| 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/save.rs b/crates/engine/src/cmd/fileio/save.rs index 453fed3971..8878456b5c 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1093,6 +1093,22 @@ impl SaveJob { { return Err(refused); } + // An existing destination that is a folder or a read-only file is refused before any file + // is written too. + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 { + for (p, _) in &files { + let Ok(meta) = std::fs::metadata(p) else { continue }; + let refused = if meta.is_dir() { + crate::EngineError::Other(format!("{p}: is a folder, not a file")) + } else if meta.is_file() && meta.permissions().readonly() { + super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + } else { + continue; + }; + return Err(if self.redact_paths { super::access::naming_in_error(refused, p) } else { refused }); + } + } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { write(p, bytes)?; @@ -1400,7 +1416,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 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..a60e9841b2 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -28,6 +28,64 @@ 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_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/links.rs b/crates/engine/src/cmd/links.rs index afc1a85f3d..6a88bf74ef 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -174,6 +174,11 @@ 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, + /// `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, @@ -203,6 +208,32 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } +/// 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 +/// 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) { + 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()) + .filter_map(|p| fileio::document_path(p, base.doc).ok()) + .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 /// (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 @@ -220,10 +251,26 @@ 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![], + relatives_seen: Default::default(), + }); 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.relatives_seen.contains(r) + { + g.relatives_seen.insert(r.clone()); + g.other_relatives.push(r.clone()); + } + if let Some(id) = id { g.ids.push(id); } }; @@ -399,6 +446,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), @@ -407,12 +465,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)) } pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option { @@ -3278,6 +3331,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 [ diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 8385350b2e..661fe741e7 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 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 ), @@ -896,11 +896,39 @@ 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 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; + 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 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); + 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 = |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 @@ -918,7 +946,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 = @@ -937,9 +973,88 @@ 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, 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; + 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))); + } + } + 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))) }; + 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))); + } + // 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))); + } + 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))); + } + 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); + } + // 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)) +} + +/// 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)?; @@ -947,16 +1062,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/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b007cde660..9cf80039db 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); $.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), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.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, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), 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), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.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, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), 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/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 2ad7469dbb..28b215315c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -107,6 +107,9 @@ mod matrix; 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; @@ -3344,7 +3347,9 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { text::install_enums(realm)?; - for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) { + for (name, members) in + ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) + { let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name); items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}")))))); @@ -3475,6 +3480,7 @@ fn classes(link: &Link) -> Vec { document.extend(print::document_members(l)); document.extend(images::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); + document.extend(raster_capture::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "Views", @@ -3639,6 +3645,7 @@ fn classes(link: &Link) -> Vec { classes.extend(tracing::classes(l)); classes.extend(save_open::classes(l)); classes.extend(print::classes(l)); + classes.extend(raster_capture::classes(l)); classes.extend(tags::classes(l)); classes } 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..f067b430d4 --- /dev/null +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -0,0 +1,696 @@ +//! 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, 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. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +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, 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. +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, none inside another listed one. The command checks that none is listed twice 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); + } + 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) +} + +/// `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])); + } + // 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 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, also when a file is missing, in the form +/// [`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().iter().chain(interface.iter()) { + 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| 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 { + 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)) +} + +/// 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, or only in their Unicode +/// normalization form in a folder whose volume ignores that. +fn same_file(a: &Placed, b: &Placed) -> bool { + 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 +/// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the +/// 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) { + 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 = "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`. `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_none_or(|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 +/// 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 +/// 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 { + #[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 + } +} + +/// 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 { + 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 +/// 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 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": plain, + "format": "png", + "rect": [region.x0, region.y0, region.width(), region.height()], + "ppi": ppi, + "background": background, + "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 = 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) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec { + let mut members = named(vec![ + ( + "rasterize", + method(l, doc_rasterize), + returns("RasterItem", &[("sourceArt", "*"), ("clipBounds", "Array"), ("options", "RasterizeOptions")]), + ), + ( + "imageCapture", + method(l, doc_image_capture), + returns("undefined", &[("imageFile", "File"), ("clipBounds", "Array"), ("options", "ImageCaptureOptions")]), + ), + ]); + 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 { construct: Some(f), ..class(name, None, Vec::new(), None) } + }) + .collect() +} + +#[cfg(test)] +mod source_tests { + use super::*; + + #[test] + fn capture_sources_keep_files_outside_automation_read_roots() { + let dir = vectorcraft_testkit::TempDir::new("capture-source-roots"); + 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"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(&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)); + }); + } + + /// 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. 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() { + 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/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b2f33027c5..1ec57d7ba9 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -19,8 +19,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 @@ -878,6 +879,24 @@ pub(super) fn exactly(h: &Host, f: impl FnOnce() -> Result) -> r } +/// Writes each warning in a command's answer `result` to the console after `method`'s name. +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)); + } + } + } + } +} + /// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s /// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or /// a linked image an open could not read. → the command's answer. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0890a75fcd..cd966a5605 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -858,6 +858,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>, /// The actions `app.doScript` can play. actions: Vec, /// The index of each open document's active artboard as the run starts, by document uid. The @@ -1374,7 +1377,10 @@ 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()); + // 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)); // What the command opened, changed or gave another file is not as the person left it. @@ -2432,6 +2438,7 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::new(self.documents(), heap_bytes), + interface_docs: RefCell::new(Vec::new()), actions: request.actions, active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), artboard_picks, @@ -2988,6 +2995,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(); @@ -3021,6 +3030,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result::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_dom.rs b/crates/engine/src/tests/script_dom.rs index b23f105b6d..d484e10e81 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1138,6 +1138,34 @@ fn a_copy_goes_beside_its_source() { assert!(e.contains("into itself"), "{e}"); } +/// A clipping group's clipping path stays at the bottom of the group, so an object cannot go +/// below it; above it is the bottom of the clipped art. +#[test] +fn nothing_goes_below_a_clipping_path() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "loose"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let children = |s: &Session| -> 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("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); + 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(); @@ -2204,6 +2232,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 root = vectorcraft_testkit::TempDir::new("script-add-document-profile"); 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..9e0d53c696 --- /dev/null +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -0,0 +1,1069 @@ +//! 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 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() { + 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)]); +} + +/// 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 (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, [{left}, 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(); +} + +/// 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(); + 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_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_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(); + 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(); + 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[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[1], [42, 280, 48, 240], o);", + "does not overlap the art", + ); +} + +#[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(); + 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()); +} + +#[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); +} + +/// `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() { + 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_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"); + 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); +} + +/// 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); +} + +/// 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"); + 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_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); +} + +/// 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); +} + +/// 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] +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"); + 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/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 11bcd74225..3952955779 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,6 +182,7 @@ 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"), + // Names the app's own reference errors give a hint for: a script's own text keeps none. ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("throw new ReferenceError('BridgeTalk is not defined');", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 52fc48cf73..643e8f50ea 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(""), + ) + .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); +} + #[test] fn export_file_logs_encoder_warnings() { let base = folder("export-warnings"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 645f6bfdf8..b833c5d07f 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -47,6 +47,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), ("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"), ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; @@ -332,6 +333,11 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of rasterizing and the document's rasterize and window capture methods. + ("", "AntiAliasingMethod RasterizationColorModel"), + ("Document.prototype.", "rasterize windowCapture windowCapture="), + ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), + ("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"), // The enumerations of placed and raster items. ("", "ImageColorSpace RasterLinkState"), ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), @@ -559,10 +565,12 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// that have no members of their own, the color classes, and the save and export option classes. +/// that have no members of their own, the color classes, and the save, export, rasterize and image +/// capture option classes. const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \ MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \ - EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 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/format/src/atomic.rs b/crates/format/src/atomic.rs index dd0cd4cc6c..83901874fd 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(), @@ -457,11 +473,20 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { 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: &|| Ok(()), + still_allowed: check, }; write_over_in(&over, refused) } @@ -481,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<()>, @@ -494,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); @@ -502,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), }; @@ -547,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. @@ -560,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)); @@ -1100,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] @@ -1121,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: &|| { @@ -1753,6 +1789,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"); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 9fdf4d73ce..6a40857796 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -77,7 +77,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", "exportVariables", "saveAs"]; +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "imageCapture", "saveAs"]; // Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_FILE_READS: &[&str] = &["open"]; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 05b8077967..9aee330bd4 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -550,6 +550,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][..])]); +} + /// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. #[test] fn export_variables_writes_a_file() { diff --git a/docs/gaps.md b/docs/gaps.md index fdf8eb1dcc..6054399bc1 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -862,15 +862,16 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi selection, its page items, layers, groups, compound paths and artboards, its text frames with their text ranges and character and paragraph attributes, their links to each other and the stories they form, its character and paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its - linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, - rasterizing and capturing images are still missing. + linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`). `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms. Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a 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 d10f81b426..80b85b3b48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2756,7 +2756,7 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`, `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not - have; a document's `saveAs`, `exportFile` or `exportVariables` counts too, and so do `print` called on + have; a document's `saveAs`, `exportFile`, `imageCapture` or `exportVariables` counts too, and so do `print` called on `app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or `app.open()`, or on a variable that holds one of them, and `SaveOptions.SAVECHANGES` wherever the script reads it, since `close` given it saves the document to its file), `filesOpened` (files opened in other apps), `network`, @@ -3415,7 +3415,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, and 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`), `saveMultipleArtboards` and `artboardRange` of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint`, `compatibility`, @@ -3471,7 +3472,9 @@ through `$`: `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 a DXF of a drawing with placed raster images writes each image it exports beside it as a PNG file, or a JPEG - file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. When the script's folders refuse one of those files, none of them is written; a write that fails once the + file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. 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 does `ExportType.FLASH`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and @@ -3946,6 +3949,47 @@ through `$`: on `add()`; `add()` gives a tag with an empty name and value; `getByName` gives the first tag with the name; `name` and `value` take strings of at most 65,536 bytes, and an object has at most 64 tags. A tag that was deleted throws `Stale tag`, and one whose page item was deleted throws `Stale page item`. +- `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. 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, 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). + 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 + 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, 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 + 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 + 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 @@ -11942,6 +11986,17 @@ 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 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, and an object that is hidden or in a hidden layer or group, are +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 +`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}}} @@ -12767,6 +12822,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 + 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 3eda44df91..51d2fb2510 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1114,10 +1114,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. + - Scripts: `Document.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: 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: `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: `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 deciding whether an inverted value overflows from its exact quotient, 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 hidden or locked or 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: `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`.