Merge pull request #9075 from dotCooCoo/feat/scripts-api-d8c-rasterize-capture

Scripts: Document.rasterize and Document.imageCapture with their option classes
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-03 07:14:28 -08:00
commit 79fdfedfb5
26 files changed
+2565 -61

No files matched your search

Generated
+1
View File
@@ -8741,6 +8741,7 @@ dependencies = [
"skrifa 0.47.0",
"thiserror 2.0.21",
"tiff",
"unicode-normalization",
"vectorcraft-affinity",
"vectorcraft-apischema",
"vectorcraft-brush",
+3
View File
@@ -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,
@@ -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 {
+17 -1
View File
@@ -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<CommandSpec> {
"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 <name>-<artboard>.<ext> 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 <name>_<artboard>.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 <name>-<artboard>.<ext> 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 <name>_<artboard>.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)
),
@@ -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", &params).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::<std::io::Result<_>>().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", &params);
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<String> = 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();
+98 -8
View File
@@ -174,6 +174,11 @@ struct Group {
document: Option<Shown>,
/// An image placed from a DCS file: the plate files of their own its plates were read from.
plate_files: Vec<vectorcraft_doc::separated::PlateFile>,
/// 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<String>,
/// `other_relatives` as a set, looked up for every object added to the group.
relatives_seen: std::collections::HashSet<String>,
}
/// 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<u64>)> {
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<String> {
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<String> = 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<Group> {
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<Found> {
/// 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<Found> {
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<Item = String> + '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<Found> {
(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<String> {
@@ -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<String> = (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<String> = 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 [
+131 -11
View File
@@ -124,7 +124,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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<Node>, 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<Rect> = 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<Node>, 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<Node>, 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<Vec<NodeId>> {
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<Value> {
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<Node> = 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<Value> {
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);
}
+1 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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, contai Line truncated
"{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 creatio Line truncated
always,
run
),
+38 -4
View File
@@ -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<dyn Fn(&Path) -> Result<(), String>>;
thread_local! {
static WRITE_GUARD: RefCell<Option<WriteGuard>> = const { RefCell::new(None) };
}
/// Puts the write guard it replaced back when dropped (also when `f` panics).
struct RestoreWriteGuard(Option<WriteGuard>);
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<T>(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`.
+8 -1
View File
@@ -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<HostClass> {
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<HostClass> {
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
}
@@ -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
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/> 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<f64, HostError> {
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<Option<&'a [(String, Data)]>, 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<Option<Rect>, 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<Map<String, Value>, 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<Vec<u64>, 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<u64> = 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<u8, HostError> {
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<Placed> {
let s = h.session.borrow();
let interface = h.interface_docs.borrow();
let mut paths: Vec<String> = 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<Placed> {
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<Placed> {
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::<String>();
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<Option<Box<dyn FnOnce()>>> = 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::DirEntry> = std::fs::read_dir(folder).into_iter().flatten().flatten().take(256).collect();
let mut folded = std::collections::HashSet::new();
let names: std::collections::HashSet<String> = 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<Described> {
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<HostClass> {
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<Data>| {
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")));
}
}
+21 -2
View File
@@ -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<T>(h: &Host, f: impl FnOnce() -> Result<T, HostError>) ->
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.
+11 -1
View File
@@ -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<Vec<DocState>>,
/// The actions `app.doScript` can play.
actions: Vec<actions::Playable>,
/// 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<std::result::Result<Progress, RunError>, 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<std::result:
s.script_in_run = false;
// A panic in a member that opened the fence for one command skips its own reset.
s.script_unfenced = None;
std::mem::swap(&mut job.world.docs, &mut *job.host.interface_docs.borrow_mut());
job.world.swap(s);
s.depth = depth;
s.sync_front_profiles();
+1
View File
@@ -196,6 +196,7 @@ mod script_include;
mod script_io;
mod script_modules;
mod script_print;
mod script_raster_capture;
mod script_run;
mod script_save_open;
mod script_scriptui;
+14
View File
@@ -100,6 +100,20 @@ fn places_named_from_a_share_are_not_followed_after_a_save_elsewhere() {
assert_eq!(follow_from(link, on_share, Some(r"C:\b\poster.vectorcraft"), resolve), None);
}
#[test]
fn capture_sources_exclude_paths_the_document_cannot_follow() {
let dir = Folder::new("capture-paths");
let mut paths = far(&dir);
paths.push(dir.file("local.png"));
let path = save_linked(&dir, &paths);
let mut s = Session::new();
s.execute("document.open", &json!({"path": path})).unwrap();
let st = s.active().unwrap();
let places = crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st));
assert_eq!(far_reads(&places), Vec::<&String>::new(), "{places:?}");
assert!(places.contains(&dir.file("local.png")), "local links remain capture sources: {places:?}");
}
/// The final path Windows gives a folder of the drive `Z:` mapped to `\\server\share`. The
/// share's root folder has no trailing separator (`\\?\UNC\server\share`).
fn on_share(folder: &str) -> Option<std::path::PathBuf> {
+85
View File
@@ -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<NodeId> { 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::<vectorcraft_js::Data>() + "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");
File diff suppressed because it is too large. Load diff
+1
View File
@@ -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"),
+100
View File
@@ -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("<svg"));
assert_eq!(s.active().unwrap().format, "svg");
let extensionless = dir.join("no-extension");
std::os::unix::fs::symlink(&target, &extensionless).unwrap();
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&extensionless)));
assert!(std::fs::read_to_string(&target).unwrap().contains("<svg"));
assert_eq!(s.active().unwrap().format, "svg");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_save_rejects_directory_sidecars_before_replacing_the_main_file() {
for (format, options) in [("vectorcraft", json!({"separateArtboards": true})), ("eps", json!({"useArtboards": true}))] {
let base = folder(&format!("save-directory-{format}"));
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
let path = dir.join(format!("art.{format}"));
let mut params = options;
params["path"] = json!(path.to_string_lossy());
params["format"] = json!(format);
let saved = s.execute("file.saveAs", &params).unwrap();
let sidecar = PathBuf::from(saved["files"].as_array().unwrap().last().unwrap().as_str().unwrap());
std::fs::remove_file(&sidecar).unwrap();
std::fs::create_dir(&sidecar).unwrap();
let marker = sidecar.join("keep");
std::fs::write(&marker, b"sidecar").unwrap();
std::fs::write(&path, b"main").unwrap();
let e = s.execute("file.saveAs", &params).unwrap_err().to_string();
assert!(e.contains("not a file"), "{e}");
assert_eq!(std::fs::read(&path).unwrap(), b"main");
assert_eq!(std::fs::read(&marker).unwrap(), b"sidecar");
let _ = std::fs::remove_dir_all(base);
}
}
/// A test's folder, removed when the test ends, a failed assertion included. A read-only file in
/// it, which Windows does not delete, is made writable first when the first removal fails.
struct Workspace(PathBuf);
@@ -176,6 +224,58 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn scripted_file_writes_log_command_warnings() {
for (method, extension, call) in [("saveAs", "pdf", "d.saveAs(file)"), ("exportFile", "png", "d.exportFile(file, ExportType.PNG24)")] {
let base = folder(&format!("warning-{method}"));
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
super::menucmds::place_undecodable_png(&mut s);
let path = dir.join(format!("output.{extension}"));
let out = run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument, file = new File({}); {call};", quoted(&path))).unwrap();
assert!(path.is_file(), "{method}");
let prefix = format!("{method}: ");
let lines = out["console"]["lines"].as_array().unwrap();
assert!(lines.iter().filter_map(Value::as_str).any(|s| s.starts_with(&prefix) && s.contains("couldn't be decoded")), "{method}: {out}");
let _ = std::fs::remove_dir_all(base);
}
}
#[test]
fn open_does_not_inherit_an_existing_documents_link_permission() {
let base = folder("inherited-link");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let linked = base.join("outside/linked.png");
std::fs::write(&linked, super::links::png(2, 2, [255, 0, 0])).unwrap();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("file.place", &json!({"path": linked.to_string_lossy(), "link": true})).unwrap();
let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&amp;").replace('<', "&lt;").replace('\'', "&apos;");
let page = dir.join("page.svg");
std::fs::write(
&page,
format!("<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='20' height='20'><image width='10' height='10' xlink:href='{href}'/></svg>"),
)
.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");
@@ -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.
+115 -21
View File
@@ -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<File>,
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<File>,
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<File>,
/// Creates a missing target after the final check and fails if its name is taken.
#[cfg(unix)]
create_target: &'a dyn Fn() -> io::Result<File>,
/// 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");
+1 -1
View File
@@ -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"];
+15
View File
@@ -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::<Vec<_>>(), [("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::<Vec<_>>(), [("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() {
+5 -4
View File
@@ -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
+61 -3
View File
@@ -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
`<name>-<artboard>.<ext>` 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
+2 -1
View File
@@ -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`.