Merge main into feat/scripts-api-d8b-tracing

This commit is contained in:
dotCooCoo committed 2026-12-02 02:46:39 -08:00
commit 47a8bcde18
38 files changed
+2780 -190

No files matched your search

+18 -3
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Mark Bounds of Each",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
"{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}",
has_selection,
mark_bounds
)]
@@ -55,10 +55,16 @@ fn corners(r: Rect) -> Vec<(Point, f64, f64)> {
out
}
/// The lengths of the across and down legs of the corner marks of `r`: `length`, at most half the
/// side each runs along.
fn legs(r: Rect, length: f64) -> (f64, f64) {
(length.min(r.width() / 2.0), length.min(r.height() / 2.0))
}
/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per
/// corner, a line where `r` has no width or no height.
fn corner_paths(r: Rect, length: f64) -> Vec<PathData> {
let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0));
let (lx, ly) = legs(r, length);
corners(r)
.into_iter()
.filter_map(|(p, sx, sy)| {
@@ -103,14 +109,23 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
let symbols = d.symbol_boxes();
let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len());
let mut too_small = false;
for id in roots {
let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue };
let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) };
if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) {
let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue };
// Corner legs are at most half a side, so an object too small for any leg gets no marks.
let (lx, ly) = legs(r, length);
if rectangle || lx > FLAT || ly > FLAT {
marked.push((anchor(d, id), r));
} else {
too_small = true;
}
}
if marked.is_empty() {
if too_small {
return Err(bad(C, "nothing to mark: the selection is too small for corner marks"));
}
return Err(bad(C, "nothing to mark: the selection has no bounds"));
}
let ap = Appearance::basic(Paint::None, Paint::solid(color), weight);
@@ -325,6 +325,28 @@ fn flat_objects_get_lines_and_guides_and_empty_groups_none() {
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
}
#[test]
fn an_object_too_small_for_corner_legs_gets_no_empty_group() {
let mut s = session();
// Wider than the flat limit, but each leg (half the side at most) is shorter than it.
let tiny = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 1.5e-9, "y2": 50})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[tiny]);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
assert!(refused.contains("nothing to mark") && refused.contains("too small for corner marks"), "{refused}");
assert_eq!(steps(&s), n, "no undo step");
assert!(*s.doc().unwrap().doc == *before);
// The rectangle style still marks it, and a real object beside it gets its corner marks alone.
let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap();
assert_eq!(r["count"], 1);
s.execute("edit.undo", &json!({})).unwrap();
let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
select(&mut s, &[tiny, a]);
let r = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(r["count"], 1);
assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0)));
}
#[test]
fn bad_params_are_refused_and_it_is_off_without_a_selection() {
let mut s = session();
+65 -6
View File
@@ -1,5 +1,3 @@
#[cfg(not(target_arch = "wasm32"))]
use super::write_atomic;
use super::{EngineError, Result, Session, Value, bad, json};
// ---------- the file system (none on the web, where commands take and return bytes) ----------
@@ -336,8 +334,30 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
// Work that stops early for a cancel can leave a truncated result: none of it is written.
vectorcraft_doc::cancel::check()?;
may_write(path)?;
// Never a half-written file: see [`write_atomic`].
write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e))
// Never a half-written file: see [`vectorcraft_format::write_atomic`].
write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e))
}
/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes
/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is
/// checked again as it is opened, and the file goes into that open folder
/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the
/// check does not redirect the write.
#[cfg(not(target_arch = "wasm32"))]
fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> {
let path = std::path::Path::new(path);
if !crate::file_access::writes_checked() {
return vectorcraft_format::write_atomic_with(path, fill);
}
vectorcraft_format::write_atomic_checked(path, fill, |opened| {
// On Unix `opened` is the open folder's real path with the file's name: compared as it is,
// without looking the folder up again. Elsewhere it is `path` itself.
#[cfg(unix)]
let checked = crate::file_access::check_write_real(opened);
#[cfg(not(unix))]
let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy());
checked.map_err(std::io::Error::other)
})
}
/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the
@@ -355,7 +375,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError {
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
vectorcraft_doc::cancel::check()?;
may_write(path)?;
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e))
write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e))
}
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
@@ -369,7 +389,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> {
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
vectorcraft_doc::cancel::check()?;
may_write(path)?;
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e))
write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e))
}
#[cfg(not(target_arch = "wasm32"))]
@@ -762,4 +782,43 @@ mod tests {
assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw);
let _ = std::fs::remove_dir_all(base);
}
/// The second check of a checked write compares the open folder's real path as it is: a folder
/// on that path replaced afterwards by a link into the write root does not make a place outside
/// the root pass.
#[cfg(unix)]
#[test]
fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() {
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (root, out) = (base.join("root"), base.join("out"));
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(out.join("x")).unwrap();
let real = out.join("x/doc.svg");
std::fs::remove_dir(out.join("x")).unwrap();
std::os::unix::fs::symlink(&root, out.join("x")).unwrap();
let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap();
assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes");
let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real));
assert!(checked.is_err_and(|e| e.contains("outside the write root")));
let _ = std::fs::remove_dir_all(base);
}
/// A checked write through a link to a folder whose name is not valid UTF-8, inside the write
/// root, is saved.
#[cfg(target_os = "linux")]
#[test]
fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() {
use std::os::unix::ffi::OsStrExt;
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff"));
std::fs::create_dir_all(&bytes).unwrap();
std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap();
let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap();
let path = base.join("text/doc.svg").to_string_lossy().into_owned();
confine(roots.as_ref(), || write_file(&path, b"new")).unwrap();
assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new");
let _ = std::fs::remove_dir_all(base);
}
}
+3 -2
View File
@@ -1933,7 +1933,8 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line
let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect();
let fonts: Vec<String> = family.into_iter().map(str::to_string).collect();
let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &fonts), &wanted);
let first = index.matches(&pieces[0].path);
// Every match, as Retype reads them: the first MAX_CANDIDATES can all be faces drawn alike.
let first = index.all_matches(&pieces[0].path);
let face = match family {
Some(f) => first.iter().find(|m| m.face.family == f).unwrap_or_else(|| panic!("the first glyph matches no glyph of {f}")),
None => &first[0],
@@ -1942,7 +1943,7 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec<super::Line
.id();
let mut lines: Vec<super::Line> = vec![];
for pc in &pieces {
let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
let cands: Vec<_> = index.all_matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect();
if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) {
lines.extend(super::new_line(pc, &cands, 0.0));
}
+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), $.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 handler 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); $.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
always,
run
),
+9 -1
View File
@@ -12,6 +12,8 @@ use vectorcraft_doc::{Node, Scaling};
const CMD: &str = "object.stepAndRepeat";
const MAX_CELLS: usize = 10_000;
/// The most objects the copies may hold in all, counting every object inside each copy.
const MAX_COPIED_OBJECTS: usize = 250_000;
const EPS: f64 = 1e-9;
pub fn specs() -> Vec<CommandSpec> {
@@ -20,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Step and Repeat…",
["Object", "Transform"],
None,
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
has_selection,
step_and_repeat
)]
@@ -174,6 +176,12 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
if rows.saturating_mul(cols) > MAX_CELLS {
return Err(bad(CMD, format!("more than {MAX_CELLS} copies")));
}
// Each copy holds every object of the selection, the art of opacity masks included, and the
// group that a selection of several objects goes into.
let objects = roots.iter().filter_map(|r| d.node(*r)).fold(usize::from(roots.len() > 1), |sum, n| sum.saturating_add(n.count_with_masks()));
if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS {
return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects")));
}
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0));
let cells = layout(w, h, gx, gy, rows, cols, alt);
let center = b.center().to_vec2();
@@ -131,6 +131,21 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() {
assert!(e.execute(CMD, &json!({})).is_err());
}
#[test]
fn rejects_a_grid_whose_copies_would_hold_too_many_objects() {
let (mut s, _) = setup();
for i in 1..25 {
s.execute("shape.rectangle", &json!({"x": i, "y": 0, "width": 10, "height": 10})).unwrap();
}
s.execute("select.all", &json!({})).unwrap();
let (count, steps) = (s.doc().unwrap().doc.node_count(), undo_steps(&s));
// 25 objects and the group they go into, in each of 9,999 copies, are more than the limit,
// though the cells are not.
let e = s.execute(CMD, &json!({"rows": 100, "columns": 100})).unwrap_err();
assert!(e.to_string().contains("objects"), "{e}");
assert_eq!((s.doc().unwrap().doc.node_count(), undo_steps(&s)), (count, steps));
}
#[test]
fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() {
let (mut s, _) = setup();
+1 -1
View File
@@ -115,7 +115,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
}
let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::<Vec<_>>() });
let mut wraps = false;
vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id)));
vectorcraft_doc::text::wrap_source_objects(&s.doc()?.doc, |_, sources| wraps |= sources.iter().any(|n| objects.contains(&n.id)));
if !wraps {
out["warning"] = json!(NO_AREA_TYPE_BELOW);
}
+85 -29
View File
@@ -100,16 +100,9 @@ impl AutomationRoots {
/// May the file or folder at `path` be read (or written)? It must lie inside one of the roots
/// of that kind. `Err` says why not.
pub fn check(&self, path: &str, access: Access) -> Result<(), String> {
let roots = match access {
Access::Read => &self.read,
Access::Write => &self.write,
};
// The messages are spelled out whole, as the translation catalogs match them.
let roots = self.of(access);
if roots.is_empty() {
return match access {
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")),
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
};
return Err(refused(roots, path, access));
}
// Resolving a path on another computer connects to it: unless a root is on a network
// share, such a path is refused by its name before anything is looked up.
@@ -120,12 +113,22 @@ impl AutomationRoots {
return Ok(());
}
}
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
match (shown.as_slice(), access) {
([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {path}")),
([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {path}")),
(_, Access::Read) => Err(format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", "))),
(_, Access::Write) => Err(format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", "))),
Err(refused(roots, path, access))
}
/// [`AutomationRoots::check`] for `real`, a path whose links have been followed already: it is
/// compared with the roots as it is, and not looked up again.
#[cfg(unix)]
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
let roots = self.of(access);
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
}
/// The roots of the kind `access`.
fn of(&self, access: Access) -> &[Root] {
match access {
Access::Read => &self.read,
Access::Write => &self.write,
}
}
@@ -157,6 +160,24 @@ impl AutomationRoots {
}
}
/// Why `path` is refused `access` under `roots`, the roots of that kind.
fn refused(roots: &[Root], path: &str, access: Access) -> String {
// The messages are spelled out whole, as the translation catalogs match them.
if roots.is_empty() {
return match access {
Access::Read => format!("automation filesystem access is not granted: read authority is absent: {path}"),
Access::Write => format!("automation filesystem access is not granted: write authority is absent: {path}"),
};
}
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
match (shown.as_slice(), access) {
([root], Access::Read) => format!("automation path rejected: outside the read root {root}: {path}"),
([root], Access::Write) => format!("automation path rejected: outside the write root {root}: {path}"),
(_, Access::Read) => format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", ")),
(_, Access::Write) => format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", ")),
}
}
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
#[derive(Clone, Debug)]
enum Scope {
@@ -371,18 +392,34 @@ impl ScriptGate {
also.check(path, access)?;
}
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
let allowed = real.is_some_and(|real| {
let scoped = match access {
Access::Read => self.read.allows(&real) || self.write.allows(&real),
Access::Write => self.write.allows(&real),
};
// A read-only file is not written over, also where a rename could replace it.
let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
let held = matches!(access, Access::Write) && self.held.contains(&real);
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
});
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
if real.is_some_and(|real| self.allows_real(&real, access)) { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
}
/// [`ScriptGate::check`] for `real`, a path whose links have been followed already: it is
/// compared as it is, and not looked up again.
#[cfg(unix)]
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
if let Some(also) = &self.also {
also.check_real(real, access)?;
}
if !ScriptScope::refused_by_name(real) && self.allows_real(real, access) {
Ok(())
} else {
Err(format!("Script file access denied: {}", real.display()))
}
}
/// May the place at the real path `real` be read (or written) through this gate alone?
fn allows_real(&self, real: &Path, access: Access) -> bool {
let scoped = match access {
Access::Read => self.read.allows(real) || self.write.allows(real),
Access::Write => self.write.allows(real),
};
// A read-only file is not written over, also where a rename could replace it.
let read_only = matches!(access, Access::Write) && std::fs::metadata(real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
let held = matches!(access, Access::Write) && self.held.iter().any(|h| h == real);
let linked = matches!(access, Access::Read) && self.linked.has(real) && !self.read.keeps_out(real);
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
}
}
@@ -462,8 +499,7 @@ pub fn is_path_key(key: &str) -> bool {
/// May `path` be written here? Always, without roots in force and outside a script's command
/// ([`with_script_gate`]).
pub fn check_write(path: &str) -> Result<(), String> {
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
check_gate(path, Access::Write)?;
check_write_unrecorded(path)?;
WRITES.with(|w| {
if let Some(paths) = w.borrow_mut().as_mut()
&& !paths.iter().any(|(p, _)| p == path)
@@ -474,6 +510,26 @@ pub fn check_write(path: &str) -> Result<(), String> {
Ok(())
}
/// [`check_write`] without recording `path` as 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_write_unrecorded`] for `real`, the path of a file in a folder whose links have been
/// followed already (the folder a checked write has opened): it is compared as it is, so the folder
/// is not looked up again by its path.
#[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))
}
/// Whether a write here is checked: roots are in force, or a script's command runs.
pub(crate) fn writes_checked() -> bool {
current().is_some() || in_script_command()
}
/// A file's modification time and length; `None` when there is no file at `path`.
type Stamp = Option<(Option<std::time::SystemTime>, u64)>;
+35 -21
View File
@@ -1006,9 +1006,16 @@ pub(super) fn after_kept_command(h: &Host) {
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
/// paths stay valid through the change ([`paths::see_all_points`]).
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
edit_item_with(h, item, |h| command(h, id, params))
}
/// Runs `f` on the item's document as [`edit_item`] runs its command. `f` runs after the document
/// is made active, so bounds it reads take in type that the switch measured again (in the
/// document's own composite fonts, [`Session::set_active`]).
fn edit_item_with<T>(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f));
h.dom.editing.set(kept);
r
}
@@ -2604,14 +2611,18 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
let item = this_item(h, a)?;
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let c = h.dom.coords.get();
let now = f.to_script(c, Point::new(r.x0, r.y0));
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
let (dx, dy) = (to.x - r.x0, to.y - r.y0);
if dx.abs() > 1e-9 || dy.abs() > 1e-9 {
edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
}
// Measured once the document is active.
edit_item_with(h, item, |h| {
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) };
let c = h.dom.coords.get();
let now = f.to_script(c, Point::new(r.x0, r.y0));
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
let (dx, dy) = (to.x - r.x0, to.y - r.y0);
if dx.abs() > 1e-9 || dy.abs() > 1e-9 {
command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?;
}
Ok(())
})?;
Ok(Data::Undefined)
}
@@ -2645,18 +2656,21 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
}
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let now = if width { r.width() } else { r.height() };
if now <= 0.0 {
return Err(HostError::Error(format!("the object has no {what} to scale")));
}
if (now - size).abs() < 1e-9 {
return Ok(Data::Undefined);
}
let pct = size / now * 100.0;
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"});
edit_item(h, item, "object.scale", &p)?;
// Measured once the document is active, so the ratio applies to the bounds the scale works on.
edit_item_with(h, item, |h| {
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) };
let now = if width { r.width() } else { r.height() };
if now <= 0.0 {
return Err(HostError::Error(format!("the object has no {what} to scale")));
}
if (now - size).abs() < 1e-9 {
return Ok(());
}
let pct = size / now * 100.0;
let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) };
command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?;
Ok(())
})?;
Ok(Data::Undefined)
}
+6 -1
View File
@@ -373,7 +373,12 @@ const AI_KEPT: &[(&str, Default)] = &[
];
fn ai_starts() -> Vec<(&'static str, Data)> {
vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))]
vec![
("compatibility", text("Compatibility.ILLUSTRATOR19")),
("compressed", Data::Bool(true)),
("pdfCompatible", Data::Bool(true)),
("embedICCProfile", Data::Bool(false)),
]
}
fn eps_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
+1 -1
View File
@@ -1352,7 +1352,7 @@ fn encode(s: &str) -> String {
}
/// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8.
fn decode(s: &str) -> String {
pub(crate) fn decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
+45 -4
View File
@@ -359,6 +359,32 @@ fn has_parent(p: &str) -> bool {
p.split(['/', '\\']).any(|name| name == "..")
}
/// The paths `value` can name in a `File`'s URI notation, as `File.parent` and `File.fullName` give
/// them, other than `value` as written: on a platform that reads drive letters (`windows`), `/c/…`
/// is the drive path `C:/…`, and on every platform `%20` and the other escapes are decoded. Only a
/// path that starts with one `/` has them; `$.evalFile` tries them after `value` as written
/// misses. A `//host/share` path, and a form with a `..` name, is left out.
pub fn uri_forms(value: &str, windows: bool) -> Vec<String> {
if !value.starts_with('/') || value.starts_with("//") {
return Vec::new();
}
let drive = value.strip_prefix('/').filter(|_| windows && !value.starts_with("//")).and_then(|rest| {
let (first, after) = rest.split_once('/').unwrap_or((rest, ""));
let letter = first.as_bytes();
(letter.len() == 1 && letter[0].is_ascii_alphabetic()).then(|| format!("{}:/{after}", letter[0].to_ascii_uppercase() as char))
});
let mut forms = Vec::new();
for form in drive.iter().map(String::as_str).chain(drive.is_none().then_some(value)) {
let decoded = crate::script::files::decode(form);
for f in [decoded.as_str(), form] {
if f != value && !has_parent(f) && !(windows && f.replace('\\', "/").starts_with("//")) && !forms.iter().any(|g| g == f) {
forms.push(f.to_string());
}
}
}
forms
}
/// A real path as people read it.
fn display(path: &Path) -> Arc<str> {
Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref())
@@ -575,13 +601,18 @@ impl Files {
let refused = || (FailKind::Error, format!("script file read refused: {value}"));
// A script given as text has no folder, and so no file it may read.
let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) };
// Each candidate, and whether the scope's refusal passes it over.
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), false)];
// Each candidate, and whether the scope's refusal passes it over. The path as written comes
// first; for `$.evalFile` only, when it misses, fails or is refused, the forms of a path in
// URI notation are tried, and when none of them is read either, the error of the path as written stands.
let forms = if search { Vec::new() } else { uri_forms(value, cfg!(windows)) };
let mut literal_error = None;
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), !forms.is_empty())];
candidates.extend(forms.into_iter().map(|f| (Some(dir.join(f)), true)));
if search && !path.is_absolute() {
candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false)));
candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true)));
}
for (candidate, passed_over_when_refused) in candidates {
for (i, (candidate, passed_over_when_refused)) in candidates.into_iter().enumerate() {
let Some(candidate) = candidate else { return Err(refused()) };
self.probes += 1;
if self.probes > MAX_PROBES {
@@ -590,12 +621,22 @@ impl Files {
match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) {
Ok(found) => return Ok(found),
Err(ScriptRead::Missing) => {}
Err(ScriptRead::Refused) if passed_over_when_refused => {}
Err(ScriptRead::Refused) if passed_over_when_refused => {
if i == 0 {
literal_error = Some(refused());
}
}
Err(ScriptRead::Refused) => return Err(refused()),
Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))),
Err(ScriptRead::Failed(e)) if i == 0 && passed_over_when_refused => {
literal_error = Some((FailKind::Error, format!("cannot read script file {value}: {e}")));
}
Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))),
}
}
if let Some(error) = literal_error {
return Err(error);
}
Err((FailKind::Error, format!("include file not found: {value}")))
}
+31
View File
@@ -195,6 +195,37 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was");
}
/// Type in a document in the back that the switch to that document measures again (here: not
/// measured yet) is sized and moved by the bounds measured after the switch.
#[test]
fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the_switch() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap());
let uid = s.active().unwrap().uid;
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let front = s.active().unwrap().uid;
let unmeasure = |s: &mut Session| {
let st = s.document_mut(uid).unwrap();
if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) {
t.cached_bounds = None;
t.cached_baselines.clear();
}
};
let mut got = Vec::new();
for (set, want) in
[("t.width = 150; vc.log(t.width);", 150.0), ("t.height = 90; vc.log(t.height);", 90.0), ("t.top = 200; vc.log(t.top);", 200.0)]
{
unmeasure(&mut s);
let out = log(&mut s, &format!("var t = app.documents[1].pageItems[0]; {set}"));
got.push((set, out[0].as_f64().unwrap(), want));
}
for (set, got, want) in got {
assert!((got - want).abs() < 1e-6, "{set} read {got}");
}
assert_eq!(s.active().unwrap().uid, front, "the front document stays in front");
}
/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the
/// visible bounds.
#[test]
+34
View File
@@ -301,6 +301,40 @@ fn files_are_checked_before_they_are_read() {
assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err());
}
/// `$.evalFile` also tries a path in a `File`'s URI notation, as `File.parent` gives
/// it: on Windows `/c/…` as the drive path `C:/…`, and on every platform with its escapes decoded,
/// after the path as written misses. Relative, share, device and `..` forms are not tried.
#[test]
fn include_paths_in_uri_notation_name_a_windows_drive() {
use crate::script::include::uri_forms;
assert_eq!(uri_forms("/c/Users/Test/more.jsx", true), ["C:/Users/Test/more.jsx"]);
assert_eq!(uri_forms("/d", true), ["D:/"]);
assert_eq!(uri_forms("/c/My%20Scripts/more.jsx", true), ["C:/My Scripts/more.jsx", "C:/My%20Scripts/more.jsx"]);
assert_eq!(uri_forms("/home/My%20Scripts/more.jsx", false), ["/home/My Scripts/more.jsx"]);
assert!(uri_forms("/c/Users/Test/more.jsx", false).is_empty());
for kept in
["//host/share/more.jsx", "//?/c/more.jsx", "/c/x/../more.jsx", "/Users/more.jsx", "more.jsx", "my%20file.jsx", "C:/more.jsx", "/1/more.jsx"]
{
assert!(uri_forms(kept, true).is_empty(), "{kept}: {:?}", uri_forms(kept, true));
}
assert_eq!(uri_forms("/c/%2E%2E/more.jsx", true), ["C:/%2E%2E/more.jsx"], "an escaped `..` is not decoded into a parent name");
// From a folder whose name has a space, `File.parent` gives `%20`, and the sibling is read.
let dir = fresh_folder("uri forms");
std::fs::write(dir.join("more.jsx"), "'more';").unwrap();
let main = dir.join("main.jsx");
std::fs::write(&main, "vc.log(File($.fileName).parent + '');\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n").unwrap();
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
assert!(r["log"][0].as_str().is_some_and(|p| p.contains("uri%20forms")), "{r}");
assert_eq!(r["log"][1], "more", "{r}");
// A file whose name holds `%20` as written is read before the decoded name.
std::fs::write(dir.join("part%20one.jsx"), "'literal';").unwrap();
std::fs::write(dir.join("part one.jsx"), "'decoded';").unwrap();
let literal = dir.join("part%20one.jsx").to_string_lossy().replace('\\', "/");
std::fs::write(&main, format!("vc.log($.evalFile({literal:?}));\n")).unwrap();
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
assert_eq!(r["log"], json!(["literal"]), "{r}");
}
#[test]
fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
let dir = fresh_folder("es2015");
@@ -388,6 +388,28 @@ fn a_white_matte_color_is_the_default() {
let _ = std::fs::remove_dir_all(base);
}
/// A new `IllustratorSaveOptions` reads `compatibility` as its default, ILLUSTRATOR19, and saves
/// with it untouched.
#[test]
fn illustrator_save_options_start_at_illustrator19_compatibility() {
let base = folder("aicompat");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let out = logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new IllustratorSaveOptions(); vc.log(o.compatibility);\
app.activeDocument.saveAs(new File({}), o);",
quoted(&dir.join("a.ai"))
),
);
assert_eq!(out[0], json!("Compatibility.ILLUSTRATOR19"));
assert!(dir.join("a.ai").is_file());
let _ = std::fs::remove_dir_all(base);
}
/// A path that resolves to a name that is not valid UTF-8 is refused before anything is written or
/// opened, so no file with a lossy copy of the name is touched.
#[cfg(unix)]