Scripts: script file writes and rasterize report their warnings

Document.rasterize, imageCapture, saveAs and exportFile send command
warnings to the Script Console, as app.open does. app.open no longer
inherits the linked-file permissions of documents open at the start of
the run. Rasterize by id refuses art on a locked artboard, and clip
bounds within floating-point error of whole pixels use that pixel count.
Capture sources leave out link paths the document cannot follow.
This commit is contained in:
dotCooCoo committed 2026-11-28 23:02:05 -08:00
1 parent 5dbd4357c1
commit 88d9a6e601
10 files changed
+176 -29

No files matched your search

+3 -2
View File
@@ -212,7 +212,8 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
/// from, wherever it is stored, brush art included, whether or not a file is there: each place
/// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file,
/// as its plate-change check finds them. A link's absolute stored and relative paths are listed
/// as they are too, for the relative path of every object in a group.
/// too, for the relative path of every object in a group. Document-path restrictions apply before
/// any filesystem probe.
pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec<String> {
let mut out = vec![];
for g in groups(d, None) {
@@ -221,7 +222,7 @@ pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec<String> {
let mut mains: Vec<String> = std::iter::once(link.path.as_str())
.chain(link.relative.as_deref())
.filter(|p| Path::new(p).is_absolute())
.map(str::to_string)
.filter_map(|p| fileio::document_path(p, base.doc).ok())
.collect();
mains.extend(places(&link, base));
for main in mains {
+13 -3
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), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
"{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}",
has_selection,
rasterize
),
@@ -916,8 +916,14 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec<Node>, p
}
let scale = ppi / 72.0;
// The image covers the bounds in whole pixels.
let px = |len: f64| (len * scale).ceil().max(1.0);
let region = Rect::new(b.x0, b.y0, b.x0 + px(b.width()) / scale, b.y0 + px(b.height()) / scale);
let px = |lo: f64, hi: f64| {
let pixels = (hi - lo) * scale;
let nearest = pixels.round();
let error = 8.0 * f64::EPSILON * (lo.abs() + hi.abs()) * scale;
let pixels = if (pixels - nearest).abs() <= error { nearest } else { pixels };
pixels.ceil().max(1.0)
};
let region = Rect::new(b.x0, b.y0, b.x0 + px(b.x0, b.x1) / scale, b.y0 + px(b.y0, b.y1) / scale);
// Create Clipping Mask: the image is clipped to the art's outline with its geometry effects
// applied, as on the canvas.
let clip = look
@@ -975,6 +981,7 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
}
}
let mut roots = Vec::with_capacity(ids.len());
let locks = d.locked_artboards();
for id in &ids {
// The layers and groups from the top down to the object itself.
let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) };
@@ -1000,6 +1007,9 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) {
return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0)));
}
if locks.holds_id(*id) {
return Err(bad(cmd, format!("id {} is on a locked artboard", id.0)));
}
roots.push(*id);
}
Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d))
+1 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul Line truncated
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the contain Line truncated
always,
run
),
@@ -222,6 +222,7 @@ fn doc_rasterize(h: &Host, a: &[Data]) -> Answer {
p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1]));
}
let r = on_doc(h, doc.uid, true, |h| command(h, "object.rasterize", &Value::Object(p)))?;
super::save_open::command_warnings(h, "rasterize", &r);
let image = match &r {
Data::Object(o) => o.iter().find_map(|(k, v)| match (k.as_str(), v) {
("imageId", Data::Number(n)) => super::whole(*n),
@@ -421,7 +422,7 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer {
h.disk.borrow_mut().exact = true;
let r = on_doc(h, doc.uid, false, |h| command(h, "document.export", &p));
h.disk.borrow_mut().exact = false;
r?;
super::save_open::command_warnings(h, "imageCapture", &r?);
Ok(Data::Undefined)
}
+22 -13
View File
@@ -571,6 +571,23 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
r
}
pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) {
if let Data::Object(items) = result {
for (key, value) in items {
let warnings: &[Data] = match (key.as_str(), value) {
("warning", Data::String(_)) => std::slice::from_ref(value),
("warnings", Data::Array(warnings)) => warnings,
_ => continue,
};
for warning in warnings {
if let Data::String(warning) = warning {
super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
}
}
}
}
}
/// The path to give a command for the real path `real`.
fn plain(real: std::path::PathBuf) -> String {
crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()
@@ -602,7 +619,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
}
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
p.insert("path".into(), json!(plain(real)));
exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?;
let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?;
command_warnings(h, "saveAs", &r);
Ok(Data::Undefined)
}
@@ -656,7 +674,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
let named = with_extension(path, &kind, svgz);
let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?;
p.insert("path".into(), json!(plain(real)));
exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?;
let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?;
command_warnings(h, "exportFile", &r);
Ok(Data::Undefined)
}
@@ -705,17 +724,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
}),
_ => None,
};
// Each warning from reading the file (content left out, an image that could not be read) goes
// to the console, as `addDocument` sends its profile's.
if let Data::Object(items) = &r {
for (k, v) in items {
if let ("warnings", Data::Array(ws)) = (k.as_str(), v) {
for w in ws.iter().filter_map(|w| if let Data::String(w) = w { Some(w) } else { None }) {
super::super::each_line(&format!("open: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
}
}
}
}
command_warnings(h, "open", &r);
let s = h.session.borrow();
let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
Ok(doc_ref(h, st.uid))
+2 -1
View File
@@ -1296,7 +1296,8 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
// the open documents; it also reads the files the documents open when the run began link to, as the
// person left them. A document a script's command opened gives it no file.
let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect();
let gate = host.disk.borrow().gate(documents, host.linked());
let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { host.linked() };
let gate = host.disk.borrow().gate(documents, linked);
let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect();
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
// What the command opened, changed or gave another file is not as the person left it.
+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> {
@@ -166,12 +166,12 @@ fn script_rasterize_fractional_clip_bounds_stay_inside_the_rectangle() {
/// though the subtraction of its edges is not exact.
#[test]
fn script_rasterize_clip_bounds_from_a_fractional_origin_keep_whole_pixels() {
for (right, width, partial) in [(10.7, 3, false), (10.75, 4, true)] {
for (left, right, width, partial) in [(10.4, 10.7, 3, false), (10.1, 10.4, 3, false), (10.4, 10.75, 4, true)] {
let (mut s, ..) = doc();
log(
&mut s,
&format!(
"{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [10.4, 280, {right}, 240], o);"
"{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [{left}, 280, {right}, 240], o);"
),
);
assert_eq!(images(&s), vec![(width, 400)]);
@@ -243,6 +243,53 @@ fn script_rasterize_rejects_locked_art() {
refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked");
}
#[test]
fn rasterize_rejects_explicit_art_on_a_locked_artboard() {
let (mut s, a, b) = doc();
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let before = s.active().unwrap().doc.clone();
let undo = undo_steps(&s);
let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap_err().to_string();
assert!(e.contains("locked artboard"), "{e}");
assert_eq!(*s.active().unwrap().doc, *before);
assert_eq!(undo_steps(&s), undo);
refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked artboard");
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap();
}
#[test]
fn script_rasterize_logs_a_missing_image_warning() {
let (mut s, ..) = doc();
let id = super::menucmds::place_undecodable_png(&mut s);
let out = run(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);").unwrap();
let lines = out["console"]["lines"].as_array().unwrap();
assert!(
lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("rasterize: ") && s.contains("couldn't be decoded")),
"{out}"
);
assert_eq!(out["log"], json!(["RasterItem"]));
assert!(s.active().unwrap().doc.node(id).is_none());
}
#[test]
fn image_capture_logs_a_missing_image_warning() {
let base = folder("warning");
let (mut s, dir) = capture_doc(&base);
let id = super::menucmds::place_undecodable_png(&mut s);
let before = s.active().unwrap().doc.clone();
let out = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("capture.png")))).unwrap();
let lines = out["console"]["lines"].as_array().unwrap();
assert!(
lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("imageCapture: ") && s.contains("couldn't be decoded")),
"{out}"
);
assert!(dir.join("capture.png").is_file());
assert!(s.active().unwrap().doc.node(id).is_some());
assert_eq!(*s.active().unwrap().doc, *before);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn script_rasterize_rejects_art_inside_listed_art() {
let (mut s, a, b) = doc();
@@ -93,6 +93,61 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn scripted_file_writes_log_command_warnings() {
for (method, extension, call) in [("saveAs", "pdf", "d.saveAs(file)"), ("exportFile", "png", "d.exportFile(file, ExportType.PNG24)")] {
let base = folder(&format!("warning-{method}"));
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
super::menucmds::place_undecodable_png(&mut s);
let path = dir.join(format!("output.{extension}"));
let out = run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument, file = new File({}); {call};", quoted(&path))).unwrap();
assert!(path.is_file(), "{method}");
let prefix = format!("{method}: ");
let lines = out["console"]["lines"].as_array().unwrap();
assert!(
lines.iter().filter_map(Value::as_str).any(|s| s.starts_with(&prefix) && s.contains("couldn't be decoded")),
"{method}: {out}"
);
let _ = std::fs::remove_dir_all(base);
}
}
#[test]
fn open_does_not_inherit_an_existing_documents_link_permission() {
let base = folder("inherited-link");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let linked = base.join("outside/linked.png");
std::fs::write(&linked, super::links::png(2, 2, [255, 0, 0])).unwrap();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("file.place", &json!({"path": linked.to_string_lossy(), "link": true})).unwrap();
let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&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);
}
/// Without options, a save or export writes what an untouched new options object of its class gives.
#[test]
fn omitted_options_are_a_new_options_objects_defaults() {
+15 -6
View File
@@ -3148,8 +3148,11 @@ other files through `$`:
document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is
read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs`
and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the
files a command reads or writes besides the one named, such as an SVG's linked files, are
read and written only where the script's folders allow. `userInteractionLevel` does not change what a command
files `app.open` reads besides the one named, such as an SVG's linked files, are read only where the script's
folders allow, including links inherited from documents that were already open. Rendering existing documents
can still read their inherited linked files. Ancillary writes require the script's write grants.
`saveAs` and `exportFile` send command warnings to the Script Console with the method name.
`userInteractionLevel` does not change what a command
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
@@ -3177,7 +3180,10 @@ other files through `$`:
below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture`
writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another
document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in
a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With
a locked layer or group or on a locked artboard throw an error, and nothing changes.
Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional
dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name.
`rasterize` keeps the selection, less the art it replaces. With
`clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and
`padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an
error that says they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With
@@ -3186,7 +3192,8 @@ other files through `$`:
opened for writing is checked, and a path that is an open document's file or a file one of them links throws an
error, also when that file is missing. The linked files are every place opening the document looks for a link's
file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS
image's plate files beside each, and the documents count whether they were open when the run started or were
image's plate files beside each. Paths rejected by the document's path restrictions are excluded before filesystem
probes. The documents count whether they were open when the run started or were
opened while it was paused. A name that differs from it only in letter case throws the same error in a
folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or
32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to
@@ -11083,8 +11090,10 @@ With `ids`, `object.rasterize` rasterizes those objects instead of the selection
without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id
listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's
clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or
in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down)
keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's
in a locked layer or group or on a locked artboard are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down)
keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused.
Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions
round up. The result's
`imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group.
```json