diff --git a/ROADMAP.md b/ROADMAP.md index 84e40bc444..2b9961f821 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. + - 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. - 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 6e73f0f52b..c477ed4ff2 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -19,6 +19,9 @@ impl PrintService for SystemPrint { let note = system::print(job)?; Ok(sent(job.title, job.printer, ¬e)) } + fn shared_printers(&self) -> Option { + Some(std::sync::Arc::new(system::queues)) + } fn shared_print(&self) -> Option { Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e)))) } @@ -145,6 +148,10 @@ mod system { pub fn printers() -> Vec { craft::print::printers().into_iter().map(Printer::from).collect() } + /// The installed queues and the default one, without asking each driver for its capabilities. + pub fn queues() -> Vec { + craft::print::printer_queues().into_iter().map(Printer::from).collect() + } /// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings. pub fn papers(printer: &str) -> Vec { #[cfg(windows)] diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index d371bfb363..4f19f09a5a 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -173,13 +173,14 @@ fn curves_area(curves: &[CubicBez]) -> f64 { curves.iter().map(|c| c.signed_area()).sum() } -/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`. +/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`, one for each +/// quarter turn or part of one. fn ellipse_arc(out: &mut Vec, a: f64, b: f64, t0: f64, t1: f64) { if t1 <= t0 { return; } let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); - let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_2).ceil().max(1.0); let d = (t1 - t0) / n; let k = 4.0 / 3.0 * (d / 4.0).tan(); for i in 0..n as usize { @@ -294,20 +295,27 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { return four_quadrants(&spot_quadrant(t, h, kind)); } let mut bp = BezPath::new(); - let mut add = |curves: Vec, first: bool| { + let mut end: Option = None; + // Corners that meet at a point on the cell's side are joined without an anchor of their own. + let mut add = |curves: Vec| { for (k, c) in curves.iter().enumerate() { if k == 0 { - if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + match end { + None => bp.move_to(c.p0), + Some(e) if e.distance(c.p0) < 1e-9 => {} + Some(_) => bp.line_to(c.p0), + } } bp.curve_to(c.p1, c.p2, c.p3); + end = Some(c.p3); } }; // Round the corners counterclockwise, each one's hole the dot of the opposite tone. let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); - add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); - add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); - add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); - add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y)))); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y))); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h)))); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h))); bp.close_path(); bp } @@ -410,21 +418,28 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { } /// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other -/// three quadrants, counterclockwise. +/// three quadrants, counterclockwise. Quadrants that meet on an axis are joined without an anchor +/// of their own at the join. fn four_quadrants(q1: &[CubicBez]) -> BezPath { let mut bp = BezPath::new(); - let mut add = |curves: Vec, first: bool| { + let mut end: Option = None; + let mut add = |curves: Vec| { for (k, c) in curves.iter().enumerate() { if k == 0 { - if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + match end { + None => bp.move_to(c.p0), + Some(e) if e.distance(c.p0) < 1e-9 => {} + Some(_) => bp.line_to(c.p0), + } } bp.curve_to(c.p1, c.p2, c.p3); + end = Some(c.p3); } }; - add(q1.to_vec(), true); - add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false); - add(mapped(q1, |p| Point::new(-p.x, -p.y)), false); - add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false); + add(q1.to_vec()); + add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y)))); + add(mapped(q1, |p| Point::new(-p.x, -p.y))); + add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y)))); bp.close_path(); bp } @@ -731,6 +746,7 @@ mod tests { use super::*; use vectorcraft_doc::Effect; use vectorcraft_geom::Shape; + use vectorcraft_geom::kurbo::PathEl; /// A black square's samples: `side` points of black from (10, 10), white around it. fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { @@ -833,6 +849,31 @@ mod tests { } } + #[test] + fn a_dot_inside_its_cell_is_four_curves() { + for shape in [DotShape::Circle, DotShape::Ellipse] { + let bp = shape.path(0.2, 10.0).to_bezpath(); + let curves = bp.elements().iter().filter(|el| matches!(el, PathEl::CurveTo(..))).count(); + let lines = bp.elements().iter().filter(|el| matches!(el, PathEl::LineTo(..))).count(); + assert_eq!((curves, lines), (4, 0), "{shape:?}: {:?}", bp.elements()); + } + } + + #[test] + fn dot_quadrants_join_without_a_repeated_anchor() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + for t in [0.2, 0.45, 0.55, 0.6, 0.85] { + for sp in &shape.path(t, 10.0).subpaths { + let n = sp.anchors.len(); + for i in 0..n { + let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p); + assert!(a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors); + } + } + } + } + } + #[test] fn euclidean_dots_meet_corner_to_corner_at_half() { let s = DotShape::Euclidean; diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 680e2902c8..bf900adcf1 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -385,6 +385,16 @@ impl Session { self.prefs.copy_as_svg && !self.clipboard_svg_refused() } + /// After a Copy or Cut has filled the clipboard: counts it in [`Session::copies`] when it put + /// something there, and marks the clipboard as holding a copy ([`Session::clipboard_copied`]). + pub(crate) fn note_copy(&mut self) { + let filled = !self.clipboard.is_empty(); + if filled { + self.copies = self.copies.wrapping_add(1); + } + self.clipboard_copied = filled; + } + /// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first /// artboard's centre) → the number of objects. pub(super) fn load_clipboard(&mut self, mut clip: Clipboard, p: &Value) -> Result { @@ -400,6 +410,7 @@ impl Session { } let count = clip.nodes.len(); self.clipboard = clip; + self.clipboard_copied = false; Ok(count) } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index d9b6e25b96..99ef61ef44 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), @@ -1221,6 +1221,7 @@ fn copy(s: &mut Session, p: &Value) -> Result { } clip.guides = guides; s.clipboard = clip; + s.note_copy(); Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() })) } diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 263cbf57e1..aec75eb4c6 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -23,6 +23,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { s.plugin_events_batch_settled(open); } let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); + let (clipboard_copied, copies) = (s.clipboard_copied, s.copies); // The documents as they are now, whole: what a failed step brings back. Their art, history, // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); @@ -48,6 +49,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { s.active = active; s.sync_front_profiles(); (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved; + (s.clipboard_copied, s.copies) = (clipboard_copied, copies); s.pending_paint = None; return Err(e); } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 51241f63ad..26c5d2bbac 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -858,6 +858,18 @@ pub fn find(s: &Session, name: &str) -> Option { .or_else(|| CATEGORIES.iter().flat_map(|c| builtin(c, s.default_units())).find(|p| p.name.eq_ignore_ascii_case(name))) } +/// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names +/// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without +/// `preset`. +fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { + let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; + let found = match str_param(p, "presetCategory") { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))) +} + impl Session { /// New Document's starting settings: Letter in Preferences ▸ Units ▸ General. fn default_settings(&self) -> DocSettings { @@ -871,10 +883,7 @@ const RECENT: usize = 12; /// `file.new`: a new document from a preset and/or explicit settings. pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { const C: &str = "file.new"; - let base = match str_param(p, "preset") { - Some(name) => find(s, name).ok_or_else(|| bad(C, format!("no preset called `{name}` (see file.newPresets)")))?, - None => s.default_settings(), - }; + let base = preset_param(s, p, C)?; // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); @@ -964,10 +973,7 @@ fn save(s: &mut Session, p: &Value) -> Result { .map(str::trim) .filter(|n| !n.is_empty() && n.chars().count() <= 64) .ok_or_else(|| bad(C, "give the preset a name (1–64 characters)"))?; - let base = match str_param(p, "preset") { - Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?, - None => s.default_settings(), - }; + let base = preset_param(s, p, C)?; let mut preset = base.with_params_inner(p, C, s.replaying())?; preset.name = name.to_string(); let saved = &mut s.prefs.new_doc_presets; diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 433c69202c..0f604d81f1 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -384,6 +384,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result, clipboard: crate::Clipboard, + clipboard_copied: bool, + copies: u64, untitled_counter: u32, explicit_undo_group: Option>, prefs: crate::Prefs, @@ -664,6 +666,8 @@ impl Saved { draw_mode: s.draw_mode, draw_inside: s.draw_inside, clipboard: s.clipboard.clone(), + clipboard_copied: s.clipboard_copied, + copies: s.copies, untitled_counter: s.untitled_counter, explicit_undo_group: s.explicit_undo_group.clone(), prefs: s.prefs.clone(), @@ -688,6 +692,8 @@ impl Saved { s.draw_mode = self.draw_mode; s.draw_inside = self.draw_inside; s.clipboard = self.clipboard; + s.clipboard_copied = self.clipboard_copied; + s.copies = self.copies; s.untitled_counter = self.untitled_counter; s.explicit_undo_group = self.explicit_undo_group; s.prefs = self.prefs; diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 02994a9f8c..4936a06d74 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -419,8 +419,9 @@ impl FolderStore { /// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on /// Windows they must be the same file (volume serial number and file index); elsewhere `path` - /// must exist. When either file can't be read, it does not. - fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { + /// must exist. A link at `path` is not followed, so it names the link and not `file`. When + /// either file can't be read, it does not. + pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { #[cfg(unix)] { use std::os::unix::fs::MetadataExt as _; @@ -431,8 +432,19 @@ impl FolderStore { } #[cfg(windows)] { + use std::os::windows::fs::OpenOptionsExt as _; + // FILE_FLAG_OPEN_REPARSE_POINT opens a link itself rather than its target, and + // FILE_FLAG_BACKUP_SEMANTICS lets a folder be opened, as `same_file::Handle::from_path` + // opens one. + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; let opened = file.try_clone().and_then(same_file::Handle::from_file); - match (opened, same_file::Handle::from_path(path)) { + let named = std::fs::OpenOptions::new() + .read(true) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS) + .open(path) + .and_then(same_file::Handle::from_file); + match (opened, named) { (Ok(a), Ok(b)) => a == b, _ => false, } diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index d273dabad5..b007cde660 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 145954340a..1220649429 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -66,6 +66,10 @@ pub struct Session { pub fill_active: bool, /// Internal clipboard: the copied objects and the document resources they use. pub clipboard: Clipboard, + /// How many times Copy or Cut has put art, guides or artboards on [`Self::clipboard`]. + pub(crate) copies: u64, + /// [`Self::clipboard`] holds what the last Copy or Cut put there, not what an import put there. + pub(crate) clipboard_copied: bool, /// Executed commands (for actions and debugging), the most recent ones kept ([`Journal`]). pub journal: Journal, /// About the most memory the undo steps of all the open documents may keep together @@ -541,7 +545,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::{HeldInteraction, PreviewCopies}; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs}; +pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs, ScriptPreference}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 3c2f3e3299..fab9f5f06b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -463,6 +463,34 @@ pub struct Prefs { /// preferences keeps it. #[serde(skip_serializing_if = "Vec::is_empty")] pub import_matches: Vec, + /// The values scripts store with `app.preferences` under keys that are not VectorCraft + /// preferences. Not a Preferences dialog field: it has no [`cmd::prefscmds::PREF_SPECS`] row, + /// and resetting the preferences keeps it. + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub script_preferences: std::collections::BTreeMap, +} + +/// A value a script stored with `app.preferences`, with the type it was stored as. Two real +/// values are equal when their bits are, so 0 and -0 differ. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScriptPreference { + Boolean(bool), + Integer(i64), + Real(f64), + String(String), +} + +impl PartialEq for ScriptPreference { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Self::Boolean(a), Self::Boolean(b)) => a == b, + (Self::Integer(a), Self::Integer(b)) => a == b, + (Self::Real(a), Self::Real(b)) => a.to_bits() == b.to_bits(), + (Self::String(a), Self::String(b)) => a == b, + _ => false, + } + } } /// The default Hold Shortcut Delay, in seconds (VectorCraft's own value). @@ -712,6 +740,7 @@ impl Default for Prefs { blend_options: None, perspective_widget: Default::default(), import_matches: vec![], + script_preferences: Default::default(), } } } diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index c635db0585..3067361727 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -200,6 +200,13 @@ fn known_answer(o: &Map) -> Result { } } +/// What the app does when the person answers Yes to a confirm it opens for a script ([`Dialogs::ask`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum OnYes { + /// Turn off the warning before a script picked with File › Scripts › Other Script… runs. + ExternalScriptWarningOff, +} + /// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits /// for the person's answer, and the list the report gives. pub(crate) struct Dialogs { @@ -209,6 +216,10 @@ pub(crate) struct Dialogs { can_wait: Rc>, answers: RefCell>, waiting: RefCell>, + /// What Yes to the waiting dialog does, when the app opened it with [`Dialogs::ask`]. + on_yes: Cell>, + /// What the person approved with Yes, until [`Dialogs::take_approved`] takes it. + approved: Cell>, /// The error that ended the run when an answer could not reach the script. failed: RefCell>, records: RefCell>, @@ -233,6 +244,8 @@ impl Dialogs { can_wait: realm.wait_flag(), answers: RefCell::new(answers.into()), waiting: RefCell::default(), + on_yes: Cell::new(None), + approved: Cell::new(None), failed: RefCell::default(), records: RefCell::default(), record_bytes: Cell::new(0), @@ -444,14 +457,45 @@ impl Dialogs { let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; self.record(d, answer.json()); *waiting = None; - if let Err(e) = realm.answer(answer.data()) { + let on_yes = self.on_yes.take(); + // A confirm the app opened returns `undefined` to the call that opened it. + let data = if on_yes.is_some() { Data::Undefined } else { answer.data() }; + if answer == DialogAnswer::Confirm(true) { + self.approved.set(on_yes); + } + if let Err(e) = realm.answer(data) { *self.failed.borrow_mut() = Some(e); } true } + /// Opens `dialog`, a confirm the app shows for the script, whose Yes does `on_yes`; the call + /// that opens it then waits ([`HostError::Wait`]) and returns `undefined`. Only a person answers + /// it, never `script.run`'s `answers`. → false when it cannot open: the run has nobody to ask, + /// or the call comes from a callback, a getter, a conversion or a file `$.evalFile` runs. + pub(crate) fn ask(&self, dialog: ScriptDialog, on_yes: OnYes) -> bool { + if !self.framed || !self.can_wait.get() { + return false; + } + *self.waiting.borrow_mut() = Some(dialog); + self.on_yes.set(Some(on_yes)); + true + } + + /// Whether the waiting dialog is the confirm [`Dialogs::ask`] opened to turn off the external + /// script warning, whatever a script's own dialogs say. + pub(crate) fn asks_warning_off(&self) -> bool { + self.waiting.borrow().is_some() && self.on_yes.get() == Some(OnYes::ExternalScriptWarningOff) + } + + /// What the person approved with Yes to a confirm from [`Dialogs::ask`], once. + pub(crate) fn take_approved(&self) -> Option { + self.approved.take() + } + /// The run ends while a dialog waits: the report lists it with the answer `"stop"`. pub(crate) fn stopped(&self) { + self.on_yes.set(None); if let Some(d) = self.waiting.borrow_mut().take() { self.record(&d, json!("stop")); } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 91159585a0..9fe63f8c35 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -53,8 +53,8 @@ //! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at //! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an //! error. A run that fails leaves the tool as it was. -//! - `controlBounds` is the visible bounds, widened to take in the direction points of the paths -//! those bounds take in. +//! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of +//! the paths in the object; a clipping group counts its clipping path only. //! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]), //! in view-number order, and none without one. View objects keep their window's identity when //! windows are renumbered. The screen mode is the app's: @@ -98,12 +98,16 @@ use vectorcraft_js::{ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; +mod clipboard; mod images; +mod matrix; +pub mod preferences; mod print; mod save_open; mod tags; mod text; mod tracing; +mod transform; mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; @@ -932,7 +936,8 @@ fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> /// commands changed it (commands given ids select them first), direct-selected anchors, segments, /// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic /// symbol instance or an Objects on Path group included, less the objects that are now deleted, -/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together +/// hidden or locked; the current layer, which selecting art changes, is put back too while it is +/// still a layer that can be edited. `f`'s commands and the steps that put things back succeed or fail together /// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s /// changes are undone as well. fn on_doc( @@ -3100,6 +3105,14 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul (_, None) => count, }; let at = if clips { at.max(1) } else { at }; + // The index `node.move` puts the object at: art stays below the ruler guides. + // This is `Node::insert_index` on the parent's children without the object, read in place + // so that no list of them is copied. + let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let rest = || d.children(Some(to.parent)).into_iter().flatten().filter(|n| n.id != id); + let start = rest().enumerate().filter(|(_, n)| !n.is_ruler_guide()).last().map_or(0, |(i, _)| i + 1); + let i = at.min(rest().count()); + let at = if node.is_ruler_guide() { i.max(start) } else { i.min(start) }; // An image left or put first in an ordinary group named as a tracing would make that group // one, in the group it leaves as in the group it goes into. let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent); @@ -3307,6 +3320,7 @@ const ENUMS: &[(&str, &[&str])] = &[ ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), ("DocumentColorSpace", &["CMYK", "RGB"]), ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]), ("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]), ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), @@ -3370,6 +3384,9 @@ fn classes(link: &Link) -> Vec { ]); application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); application.push(later(l, "Application", "beep")); + application.extend(preferences::app_members()); + application.extend(matrix::app_members(l)); + application.extend(clipboard::app_members(l)); application.extend(save_open::application_members(l)); application.extend(print::application_members(l)); application.extend(super::actions::app_members(l)); @@ -3389,6 +3406,7 @@ fn classes(link: &Link) -> Vec { }; let mut classes = vec![ class("Application", None, application, None), + preferences::class(l), preset, class( "Documents", @@ -3530,27 +3548,75 @@ fn classes(link: &Link) -> Vec { ("remove", method(l, item_remove), returns("undefined", &[])), ("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ("toString", method(l, item_to_string), returns("string", &[])), + ( + "translate", + method(l, transform::translate), + returns( + "undefined", + &[ + ("deltaX", "number"), + ("deltaY", "number"), + ("transformObjects", "boolean"), + ("transformFillPatterns", "boolean"), + ("transformFillGradients", "boolean"), + ("transformStrokePatterns", "boolean"), + ], + ), + ), + ( + "rotate", + method(l, transform::rotate), + returns( + "undefined", + &[ + ("angle", "number"), + ("changePositions", "boolean"), + ("changeFillPatterns", "boolean"), + ("changeFillGradients", "boolean"), + ("changeStrokePattern", "boolean"), + ("rotateAbout", "Transformation"), + ], + ), + ), + ( + "resize", + method(l, transform::resize), + returns( + "undefined", + &[ + ("scaleX", "number"), + ("scaleY", "number"), + ("changePositions", "boolean"), + ("changeFillPatterns", "boolean"), + ("changeFillGradients", "boolean"), + ("changeStrokePattern", "boolean"), + ("changeLineWidths", "number"), + ("scaleAbout", "Transformation"), + ], + ), + ), + ( + "transform", + method(l, transform::transform), + returns( + "undefined", + &[ + ("transformationMatrix", "Matrix"), + ("changePositions", "boolean"), + ("changeFillPatterns", "boolean"), + ("changeFillGradients", "boolean"), + ("changeStrokePattern", "boolean"), + ("changeLineWidths", "number"), + ("transformAbout", "Transformation"), + ], + ), + ), ]); page_item.extend(layers::page_item_members(l)); page_item.extend( - [ - "artworkKnockout", - "isIsolated", - "pixelAligned", - "sliced", - "uRL", - "uuid", - "wrapInside", - "wrapOffset", - "wrapped", - "bringInPerspective", - "resize", - "rotate", - "transform", - "translate", - ] - .into_iter() - .map(|m| later(l, "PageItem", m)), + ["artworkKnockout", "isIsolated", "pixelAligned", "sliced", "uRL", "uuid", "wrapInside", "wrapOffset", "wrapped", "bringInPerspective"] + .into_iter() + .map(|m| later(l, "PageItem", m)), ); page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); diff --git a/crates/engine/src/script/dom/clipboard.rs b/crates/engine/src/script/dom/clipboard.rs new file mode 100644 index 0000000000..a6fb102f03 --- /dev/null +++ b/crates/engine/src/script/dom/clipboard.rs @@ -0,0 +1,56 @@ +//! `app.copy()`, `app.cut()` and `app.paste()`, as the help page +//! describes them: Edit › Copy, Cut +//! and Paste on the active document, run as `edit.copy`, `edit.cut` and `edit.paste` in the run's +//! transaction. +//! +//! VectorCraft's own rules, which the help page does not state: with nothing selected, or no +//! document open, `copy` and `cut` do nothing; with the clipboard empty `paste` does nothing; and +//! `paste` with no document open throws `No active document`. `paste` takes the session's +//! clipboard, not art another app copied since. A run that finishes after a Copy or Cut, by any +//! command, with the clipboard still holding what it copied, reports `copied`, and the desktop app +//! then offers the clipboard to other apps. + +use serde_json::json; +use vectorcraft_js::{Data, HostError}; + +use super::{Answer, Described, Host, Link, NO_ACTIVE_DOCUMENT, command, method, named, returns}; + +/// The clipboard functions of `Application`. +pub(super) fn app_members(link: &Link) -> Vec { + named(vec![ + ("copy", method(link, copy), returns("undefined", &[])), + ("cut", method(link, cut), returns("undefined", &[])), + ("paste", method(link, paste), returns("undefined", &[])), + ]) +} + +/// Runs `id` when the active document has something it acts on. +fn on_selection(h: &Host, id: &str) -> Answer { + let ready = crate::cmd::has_selection_guides_or_artboard_tool(&h.session.borrow()).is_ok(); + if ready { + command(h, id, &json!({}))?; + } + Ok(Data::Undefined) +} + +fn copy(h: &Host, _: &[Data]) -> Answer { + on_selection(h, "edit.copy") +} + +fn cut(h: &Host, _: &[Data]) -> Answer { + on_selection(h, "edit.cut") +} + +fn paste(h: &Host, _: &[Data]) -> Answer { + let ready = { + let s = h.session.borrow(); + if s.active().is_none() { + return Err(HostError::Error(NO_ACTIVE_DOCUMENT.into())); + } + !s.clipboard.is_empty() + }; + if ready { + command(h, "edit.paste", &json!({}))?; + } + Ok(Data::Undefined) +} diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs new file mode 100644 index 0000000000..fcecd62659 --- /dev/null +++ b/crates/engine/src/script/dom/matrix.rs @@ -0,0 +1,430 @@ +//! The matrix functions of `app`, as the help pages +//! and +//! describe them. A matrix is a plain +//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the +//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a +//! new record, those two give a boolean, and none changes the records passed to it. +//! +//! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix +//! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `concatenateMatrix(m, n)` gives the matrix that applies `m` and then `n`; the other +//! `concatenate…` functions apply `m` and then the rotation, scale or translation they make. +//! - Left-out arguments are 0 for a translation and an angle, and 100 for a horizontal scale; a +//! left-out vertical scale is the horizontal one. +//! - Angles are degrees, positive counterclockwise, and quarter turns are exact. +//! - A matrix whose determinant is 0 is singular, and `invertMatrix` of one throws. +//! - `isEqualMatrix` compares the six values exactly. +//! - An argument that is not a finite number, or a matrix with a value that is not one, throws a +//! `TypeError`; a result with a value too large for a number throws a `RangeError`. + +use vectorcraft_js::{Data, HostError}; + +use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text}; + +/// A matrix's six values: `[a, b, c, d, tx, ty]`. +pub(super) type Matrix = [f64; 6]; + +const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; + +const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// The matrix functions of `Application`. +pub(super) fn app_members(link: &Link) -> Vec { + let l = link; + named(vec![ + ("getIdentityMatrix", method(l, identity), returns("Matrix", &[])), + ("getTranslationMatrix", method(l, translation), returns("Matrix", &[("deltaX", "number"), ("deltaY", "number")])), + ("getScaleMatrix", method(l, scale), returns("Matrix", &[("scaleX", "number"), ("scaleY", "number")])), + ("getRotationMatrix", method(l, rotation), returns("Matrix", &[("angle", "number")])), + ("concatenateMatrix", method(l, concatenate), returns("Matrix", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])), + ( + "concatenateTranslationMatrix", + method(l, concatenate_translation), + returns("Matrix", &[("matrix", "Matrix"), ("deltaX", "number"), ("deltaY", "number")]), + ), + ( + "concatenateScaleMatrix", + method(l, concatenate_scale), + returns("Matrix", &[("matrix", "Matrix"), ("scaleX", "number"), ("scaleY", "number")]), + ), + ("concatenateRotationMatrix", method(l, concatenate_rotation), returns("Matrix", &[("matrix", "Matrix"), ("angle", "number")])), + ("invertMatrix", method(l, invert), returns("Matrix", &[("matrix", "Matrix")])), + ("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])), + ("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])), + ]) +} + +/// The record for `m`, or a `RangeError` when a value is not finite. +fn record(m: Matrix) -> Answer { + if m.iter().any(|v| !v.is_finite()) { + return Err(HostError::Range("the matrix has a value too large for a number".into())); + } + let mut items: Vec<(String, Data)> = KEYS.iter().zip(m).map(|(k, v)| ((*k).to_string(), num(v))).collect(); + items.push(("typename".into(), text("Matrix"))); + Ok(Data::Object(items)) +} + +/// The matrix argument `d`. +pub(super) fn matrix(d: &Data, what: &str) -> std::result::Result { + let bad = || HostError::Type(format!("{what} must be a Matrix")); + let Data::Object(items) = d else { return Err(bad()) }; + let mut m = [0.0; 6]; + for (slot, k) in m.iter_mut().zip(KEYS) { + match items.iter().find(|(n, _)| n == k) { + Some((_, Data::Number(v))) if v.is_finite() => *slot = *v, + _ => return Err(bad()), + } + } + Ok(m) +} + +/// A number argument, `default` when it is left out. +fn number(d: &Data, what: &str, default: f64) -> std::result::Result { + match d { + Data::Undefined => Ok(default), + Data::Number(n) if n.is_finite() => Ok(*n), + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// The matrix that applies `m` and then `n`. Adding 0 turns -0 into 0. +fn then(m: Matrix, n: Matrix) -> Matrix { + let [a, b, c, d, e, f] = m; + let [a2, b2, c2, d2, e2, f2] = n; + [ + products_sum(a, a2, b, c2, 0.0) + 0.0, + products_sum(a, b2, b, d2, 0.0) + 0.0, + products_sum(c, a2, d, c2, 0.0) + 0.0, + products_sum(c, b2, d, d2, 0.0) + 0.0, + products_sum(e, a2, f, c2, e2) + 0.0, + products_sum(e, b2, f, d2, f2) + 0.0, + ] +} + +/// `x·y + z·w + t`. When at most one of the three terms is not 0 and it is finite, that term is the +/// sum, rounded once. When both products and their sum are exact numbers, adding `t` rounds once. +/// Otherwise the products are summed past the range of a number and rounded at +/// the end, so a finite value is not lost to a product too large or too small for a number, to a +/// sum that rounds twice, or to a rounding error that a later term cancels down to. +fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { + let (p, q) = (x * y, z * w); + let terms = [x != 0.0 && y != 0.0, z != 0.0 && w != 0.0, t != 0.0]; + let total = p + q + t; + if terms.iter().filter(|&&on| on).count() <= 1 && total.is_finite() { + return total; + } + // A product at or above 2^-969 that rounds drops a part a number can hold, so a zero + // remainder shows the product is exact. + let exact = |v: f64, a: f64, b: f64| a == 0.0 || b == 0.0 || (v.abs() >= f64::MIN_POSITIVE * 2f64.powi(53) && a.mul_add(b, -v) == 0.0); + let plain = p + q; + if total.is_finite() && exact(p, x, y) && exact(q, z, w) && plain - p == q && plain - q == p { + return total; + } + // Each product is split into its rounded value and the part that rounding drops, both exact. + // The five parts are added one at a time into a list of values that do not overlap, smallest + // first, whose sum is exact (Shewchuk's expansion). + let product = |a: f64, b: f64| { + let (a, b) = (Wide::of(a), Wide::of(b)); + let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); + [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] + }; + let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w)); + let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow); + nearest(exact) +} + +/// Values that do not overlap, smallest first, held without allocating. Each value added keeps at +/// most one more, so the five parts of a sum and the two of a comparison fit. +#[derive(Clone, Copy)] +struct Parts { + v: [Wide; 8], + n: usize, +} + +impl Parts { + const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 }; + + fn as_slice(&self) -> &[Wide] { + &self.v[..self.n] + } +} + +/// `sums` with `part` added: values that do not overlap, smallest first, whose sum is exactly the +/// sum of `sums` and `part`. The last value is the largest and has the sign of the sum. +fn grow(sums: Parts, part: Wide) -> Parts { + let mut carry = part; + let mut kept = Parts::EMPTY; + let mut keep = |w: Wide| { + if w.m != 0.0 && kept.n < kept.v.len() { + kept.v[kept.n] = w; + kept.n += 1; + } + }; + for &h in sums.as_slice() { + let (sum, rest) = carry.two_sum(h); + keep(rest); + carry = sum; + } + keep(carry); + kept +} + +/// The sign of the exact sum of `sums`, `0.0 - v` and `offset`: 1, -1 or 0. +fn sign_past(sums: Parts, v: f64, offset: Wide) -> i32 { + let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums, grow); + match rest.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } +} + +/// The number nearest the exact sum of `sums`, ties to the even one, and infinite when the sum +/// rounds to 2^1024 or past it. The sum of the values from the smallest up comes within a step of +/// it; the halfway points to the neighbors of that number are then compared with the exact sum, so +/// the result is rounded once. +fn nearest(sums: Parts) -> f64 { + let even = |v: f64| v.to_bits() & 1 == 0; + let mut v = sums.as_slice().iter().fold(Wide::of(0.0), |total, &h| total.two_sum(h).0).value().clamp(f64::MIN, f64::MAX); + for _ in 0..4 { + // Half the step to the next number up, and to the next number down. Past the largest + // number the step is to 2^1024, which is 2^971 away. + let up = if v == f64::MAX { f64::INFINITY } else { v.next_up() }; + let down = if v == f64::MIN { f64::NEG_INFINITY } else { v.next_down() }; + let half_up = if up.is_finite() { Wide::new(up - v, -1) } else { Wide::new(1.0, 970) }; + let half_down = if down.is_finite() { Wide::new(v - down, -1) } else { Wide::new(1.0, 970) }; + match sign_past(sums, v, Wide { m: 0.0 - half_up.m, e: half_up.e }) { + 1 => { + v = up; + if !v.is_finite() { + return v; + } + continue; + } + 0 => return if even(v) { v } else { up }, + _ => {} + } + match sign_past(sums, v, half_down) { + -1 => { + v = down; + if !v.is_finite() { + return v; + } + } + 0 => return if even(v) { v } else { down }, + _ => return v, + } + } + v +} + +pub(super) fn translate(dx: f64, dy: f64) -> Matrix { + [1.0, 0.0, 0.0, 1.0, dx, dy] +} + +/// A scale by `sx` and `sy` percent. +pub(super) fn scaled(sx: f64, sy: f64) -> Matrix { + [sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0] +} + +/// A turn of `degrees` counterclockwise, exact at quarter turns. The remainder keeps the sign of +/// `degrees` and is exact, so an angle next to a quarter turn is not rounded onto it. +pub(super) fn rotate(degrees: f64) -> Matrix { + let turn = degrees % 360.0; + let (sin, cos) = match turn { + 0.0 => (0.0, 1.0), + 90.0 | -270.0 => (1.0, 0.0), + 180.0 | -180.0 => (0.0, -1.0), + 270.0 | -90.0 => (-1.0, 0.0), + _ => turn.to_radians().sin_cos(), + }; + // `0.0 - sin` rather than `-sin`, so a turn of 0 gives 0 and not -0. + [cos, sin, 0.0 - sin, cos, 0.0, 0.0] +} + +fn translation_of(a: &[Data], at: usize) -> std::result::Result { + Ok(translate(number(arg(a, at), "deltaX", 0.0)?, number(arg(a, at + 1), "deltaY", 0.0)?)) +} + +fn scale_of(a: &[Data], at: usize) -> std::result::Result { + let sx = number(arg(a, at), "scaleX", 100.0)?; + Ok(scaled(sx, number(arg(a, at + 1), "scaleY", sx)?)) +} + +fn rotation_of(a: &[Data], at: usize) -> std::result::Result { + Ok(rotate(number(arg(a, at), "angle", 0.0)?)) +} + +fn identity(_: &Host, _: &[Data]) -> Answer { + record(IDENTITY) +} + +fn translation(_: &Host, a: &[Data]) -> Answer { + record(translation_of(a, 1)?) +} + +fn scale(_: &Host, a: &[Data]) -> Answer { + record(scale_of(a, 1)?) +} + +fn rotation(_: &Host, a: &[Data]) -> Answer { + record(rotation_of(a, 1)?) +} + +fn concatenate(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, matrix(arg(a, 2), "secondMatrix")?)) +} + +fn concatenate_translation(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, translation_of(a, 2)?)) +} + +fn concatenate_scale(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, scale_of(a, 2)?)) +} + +fn concatenate_rotation(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, rotation_of(a, 2)?)) +} + +/// A number as `m · 2^e` with `m` 0 or in `[0.5, 1)`, so products and quotients of such numbers +/// keep their value however far they go past the range of an `f64`. +#[derive(Clone, Copy)] +struct Wide { + m: f64, + e: i32, +} + +/// `2^e`, for `e` from -1022 to 1023. +fn pow2(e: i32) -> f64 { + f64::from_bits(u64::from((e + 1023).clamp(1, 2046).unsigned_abs()) << 52) +} + +impl Wide { + /// `x`, a finite number. + fn of(x: f64) -> Self { + if x == 0.0 { + return Self { m: 0.0, e: 0 }; + } + if x.abs() < f64::MIN_POSITIVE { + let w = Self::of(x * pow2(54)); + return Self { m: w.m, e: w.e - 54 }; + } + let bits = x.to_bits(); + let e = i32::try_from((bits >> 52) & 0x7ff).unwrap_or(0) - 1022; + Self { m: f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e } + } + + /// `m · 2^e`, with `m` any finite number. + fn new(m: f64, e: i32) -> Self { + let w = Self::of(m); + Self { m: w.m, e: w.e.saturating_add(e) } + } + + fn div(self, o: Self) -> Self { + Self::new(self.m / o.m, self.e.saturating_sub(o.e)) + } + + /// The sum and the part of it that rounding drops, so that `self + o` is exactly their sum. A + /// number more than 2^110 times smaller than the other is returned whole as the dropped part. + fn two_sum(self, o: Self) -> (Self, Self) { + let (big, small) = if self.m == 0.0 || (o.m != 0.0 && o.e > self.e) { (o, self) } else { (self, o) }; + let gap = small.e.saturating_sub(big.e); + if small.m == 0.0 || gap < -110 { + return (big, small); + } + // Knuth's two-sum: `small` scaled to `big`'s power of 2 is exact, and so is the error. + let s = small.m * pow2(gap); + let sum = big.m + s; + let back = sum - big.m; + let rest = (big.m - (sum - back)) + (s - back); + (Self::new(sum, big.e), Self::new(rest, big.e)) + } + + /// The nearest `f64`: infinite past its range, and 0 or a subnormal number below it. + fn value(self) -> f64 { + let (mut m, mut e) = (self.m, self.e); + while e > 1000 && m.is_finite() { + m *= pow2(1000); + e -= 1000; + } + while e < -1000 && m != 0.0 { + m *= pow2(-1000); + e += 1000; + } + m * pow2(e) + } +} + +/// `a·d − b·c` with no product passing the range of a number; its `m` is 0 only when the two +/// products are equal. The products are taken whole with fused multiply-adds (Kahan's method), so +/// a difference that is small next to them keeps its value. +fn products_difference(a: f64, d: f64, b: f64, c: f64) -> Wide { + let [a, b, c, d] = [a, b, c, d].map(Wide::of); + let (ad, bc) = (a.e.saturating_add(d.e), b.e.saturating_add(c.e)); + if b.m == 0.0 || c.m == 0.0 { + return Wide::new(a.m * d.m, ad); + } + if a.m == 0.0 || d.m == 0.0 { + return Wide::new(0.0 - b.m * c.m, bc); + } + // `a·d` and `b·c` both lie in [0.25, 1) times a power of 2; one more than 2^120 times the other + // decides the sign and size alone. + let gap = bc.saturating_sub(ad); + if gap < -120 { + return Wide::new(a.m * d.m, ad); + } + if gap > 120 { + return Wide::new(0.0 - b.m * c.m, bc); + } + let b = b.m * pow2(gap); + let w = b * c.m; + let err = (0.0 - b).mul_add(c.m, w); + Wide::new(a.m.mul_add(d.m, 0.0 - w) + err, ad) +} + +/// The determinant of `m`'s linear part. +fn determinant(m: Matrix) -> Wide { + products_difference(m[0], m[3], m[1], m[2]) +} + +/// The square root of the size of `m`'s determinant: the factor by which `m` scales lengths on +/// average. It is infinite only when that factor is too large for a number. +pub(super) fn area_scale(m: Matrix) -> f64 { + let d = determinant(m); + let (mut v, mut e) = (d.m.abs(), d.e); + if e % 2 != 0 { + v *= 2.0; + e -= 1; + } + Wide::new(v.sqrt(), e / 2).value() +} + +pub(super) fn singular(m: Matrix) -> bool { + determinant(m).m == 0.0 +} + +fn invert(_: &Host, a: &[Data]) -> Answer { + let m = matrix(arg(a, 1), "matrix")?; + let det = determinant(m); + if det.m == 0.0 { + return Err(HostError::Error("the matrix is singular and cannot be inverted".into())); + } + let [a, b, c, d, e, f] = m; + // Each value is divided by the determinant before it is brought back into the range of a + // number, and the translations are taken whole, so a finite inverse is not lost to an + // intermediate value. Adding 0 turns -0 into 0. + let over = |w: Wide| w.div(det).value() + 0.0; + let plain = |v: f64| over(Wide::of(v)); + record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))]) +} + +fn is_equal(_: &Host, a: &[Data]) -> Answer { + Ok(Data::Bool(matrix(arg(a, 1), "matrix")? == matrix(arg(a, 2), "secondMatrix")?)) +} + +fn is_singular(_: &Host, a: &[Data]) -> Answer { + Ok(Data::Bool(singular(matrix(arg(a, 1), "matrix")?))) +} diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index b26ac6747f..0d86a0c97f 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -72,8 +72,8 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, class_text, colors, command, - command_value, coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, - method, named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, + command_value, coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, + num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -1298,136 +1298,37 @@ fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { set_overprint(h, a, false) } -// ---- PathItem transforms ---- +// ---- PathItem stroke weights for `resize` ---- -/// The member of `Transformation` that `d` names (left out: `CENTER`). -fn about_name(d: &Data) -> std::result::Result<&'static str, HostError> { - let name = match d { - Data::Undefined => "Transformation.CENTER", - Data::String(s) => s.as_str(), - _ => return Err(HostError::Type("give a Transformation value".into())), - }; - let members = ENUMS.iter().find(|(e, _)| *e == "Transformation").map_or(&[][..], |(_, m)| *m); - let member = name.strip_prefix("Transformation.").and_then(|m| members.iter().find(|x| **x == m)); - member.copied().ok_or_else(|| HostError::Type("give a Transformation value".into())) -} - -/// The point of the path's geometric bounds `r`, in document coordinates, that the `Transformation` -/// member `name` ([`about_name`]) names. -fn about(h: &super::Host, item: Item, name: &str, r: Rect) -> std::result::Result { - let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); - Ok(match name { - "CENTER" => Point::new(cx, cy), - "TOP" => Point::new(cx, r.y0), - "BOTTOM" => Point::new(cx, r.y1), - "LEFT" => Point::new(r.x0, cy), - "RIGHT" => Point::new(r.x1, cy), - "TOPLEFT" => Point::new(r.x0, r.y0), - "TOPRIGHT" => Point::new(r.x1, r.y0), - "BOTTOMLEFT" => Point::new(r.x0, r.y1), - "BOTTOMRIGHT" => Point::new(r.x1, r.y1), - "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(Coords::Document, [0.0, 0.0])))?, - _ => return Err(HostError::Type("give a Transformation value".into())), - }) -} - -/// The `objects` and `patterns` options of a transform command from the four flags from `i`: -/// objects, fill patterns, fill gradients and stroke patterns, each left out or true or false. -fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::Result<(), HostError> { - let names = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; - let mut flags = [None; 4]; - for (k, name) in names.iter().enumerate() { - flags[k] = given(arg(a, i + k)).map(|d| boolean(d, name)).transpose()?; - } - if flags[2] == Some(false) { - return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2]))); - } - if let (Some(f), Some(s)) = (flags[1], flags[3]) - && f != s - { - return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3]))); - } - if let Some(o) = params.as_object_mut() { - if let Some(b) = flags[0] { - o.insert("objects".into(), json!(b)); - } - if let Some(b) = flags[1].or(flags[3]) { - o.insert("patterns".into(), json!(b)); - } - } - Ok(()) -} - -/// `translate(deltaX = 0, deltaY = 0, transformObjects?, transformFillPatterns?, ...)`. -fn path_translate(h: &super::Host, a: &[Data]) -> Answer { - let dx = given(arg(a, 1)).map_or(Ok(0.0), |d| coordinate(d, "deltaX"))?; - let dy = given(arg(a, 2)).map_or(Ok(0.0), |d| coordinate(d, "deltaY"))?; - let item = this_path(h, a)?; - let mut params = json!({"dx": dx, "dy": if h.dom.coords.get() == Coords::Document { -dy } else { dy }}); - transform_options(a, 3, &mut params)?; - if dx != 0.0 || dy != 0.0 { - edit_path(h, item, "object.move", params)?; - } - Ok(Data::Undefined) -} - -/// `rotate(angle, changePositions?, ..., rotateAbout?)`: counterclockwise on the page for a -/// positive angle. -fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { - let angle = number(arg(a, 1), "angle")?; - let item = this_path(h, a)?; - let place = about_name(arg(a, 6))?; - let mut params = json!({"angle": angle}); - transform_options(a, 2, &mut params)?; - // A path with no anchors has no bounds to turn about, and turning it changes nothing. - if angle.rem_euclid(360.0) != 0.0 - && let (Some(r), _) = item_rect(h, item, false)? - { - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.rotate", params)?; - } - Ok(Data::Undefined) -} - -/// `resize(scaleX, scaleY, changePositions?, ..., changeLineWidths?, scaleAbout?)`: 100 is 100%; -/// `changeLineWidths` scales the stroke weight by that percent. -fn path_resize(h: &super::Host, a: &[Data]) -> Answer { - let sx = number(arg(a, 1), "scaleX")?; - let sy = number(arg(a, 2), "scaleY")?; - if sx == 0.0 || sy == 0.0 || sx.abs() > 100_000.0 || sy.abs() > 100_000.0 { - return Err(HostError::Range("scaleX and scaleY must not be 0 and at most 100000 percent".into())); - } - let widths = given(arg(a, 7)).map(|d| number(d, "changeLineWidths")).transpose()?; - if widths.is_some_and(|w| !(0.0..=100_000.0).contains(&w)) { +/// The stroke weight `resize`'s `changeLineWidths` of `percent` gives the path `item`, or `None` +/// when the weight stays. A `custom` percent, one other than the resize's own scale, is at most +/// 100000. +pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, custom: bool) -> std::result::Result, HostError> { + if custom && !(0.0..=100_000.0).contains(&percent) { return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into())); } - let item = this_path(h, a)?; - let place = about_name(arg(a, 8))?; - let mut params = json!({"sx": sx, "sy": sy, "basis": "page", "strokes": false}); - transform_options(a, 3, &mut params)?; let width = look(h, item)?.width; - let new_width = widths.map(|w| width * w / 100.0); - if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { + let new_width = width * percent / 100.0; + if new_width > MAX_STROKE_WIDTH { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } - // The scale and the new stroke weight are one edit: a failure of either undoes both. - super::atomically(h, |h| { - if (sx != 100.0 || sy != 100.0) - && let (Some(r), _) = item_rect(h, item, false)? - { - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.scale", params)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } - Ok(()) - })?; - Ok(Data::Undefined) + Ok(((new_width - width).abs() > 1e-9).then_some(new_width)) +} + +/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it. +pub(super) fn is_path(h: &super::Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) +} + +/// Whether the path `item` is a member of a compound path or compound shape, whose stroke the +/// compound holds. +pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id)) +} + +/// Sets the stroke weight of the path `item` to `weight` points. +pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> { + edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ()) } // ---- PathPoints ---- @@ -2039,28 +1940,7 @@ fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: u /// The members `PathItem` adds to `PageItem`'s. pub(super) fn path_item_members(l: &Link) -> Vec { - let transform = |first: &[(&'static str, &'static str)]| { - let mut args: Vec<(&str, &str)> = first.to_vec(); - args.extend([ - ("changePositions", "boolean"), - ("changeFillPatterns", "boolean"), - ("changeFillGradients", "boolean"), - ("changeStrokePattern", "boolean"), - ]); - args - }; - let mut resize = transform(&[("scaleX", "number"), ("scaleY", "number")]); - resize.extend([("changeLineWidths", "number"), ("scaleAbout", "Transformation")]); - let mut rotate = transform(&[("angle", "number")]); - rotate.push(("rotateAbout", "Transformation")); - let translate = [ - ("deltaX", "number"), - ("deltaY", "number"), - ("transformObjects", "boolean"), - ("transformFillPatterns", "boolean"), - ("transformFillGradients", "boolean"), - ("transformStrokePattern", "boolean"), - ]; + // `translate`, `rotate` and `resize` are `PageItem`'s ([`super::transform`]). let mut m = named(vec![ ("pathPoints", point_get(l, path_points), MemberInfo { collection: true, ..typed("PathPoints") }), ("closed", point_property(l, path_closed, path_set_closed), typed("boolean")), @@ -2086,9 +1966,6 @@ pub(super) fn path_item_members(l: &Link) -> Vec { ("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")), ("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")), ("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")), - ("translate", method(l, path_translate), returns("undefined", &translate)), - ("rotate", method(l, path_rotate), returns("undefined", &rotate)), - ("resize", method(l, path_resize), returns("undefined", &resize)), ("selectedPathPoints", get(l, path_selected_points), typed("Array")), ]); m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n))); diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs new file mode 100644 index 0000000000..c4308efba2 --- /dev/null +++ b/crates/engine/src/script/dom/preferences.rs @@ -0,0 +1,297 @@ +//! `app.preferences`, as the help page +//! describes it: values a script reads and stores by key with a getter and a setter for each type. +//! +//! `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`, the warning before a +//! script picked with File › Scripts › Other Script… runs. A script turns it on at once; turning it +//! off waits for the person to answer Yes to a confirm, and throws when the run cannot ask anyone +//! (VectorCraft's own rule). Every other key is kept in +//! [`crate::Prefs::script_preferences`], with the preferences, so it lasts across runs and restarts +//! and a failed or stopped run puts it back as it was. +//! +//! VectorCraft's own rules, which the help page does not state: +//! - A key that was never stored reads as `false`, `0`, `0` or `""`. +//! - A getter of another type converts the stored value as `Boolean`, `Number` or `String` do; +//! `getIntegerPreference` drops the fraction, and gives `0` for a value that is not a number. +//! - A key is a string of 1 to [`MAX_KEY_UNITS`] UTF-16 units without control characters, a string +//! value has at most [`MAX_STRING_BYTES`] bytes, and at most [`MAX_KEYS`] keys and +//! [`MAX_TOTAL_BYTES`] bytes are stored. A set that would pass a limit throws and stores nothing. +//! - A setter's value must have its type: `setIntegerPreference` takes a whole number within +//! ±2^53, and `setRealPreference` a finite number. +//! - Removing a key that is not stored does nothing; removing `ShowExternalJSXWarning` turns the +//! warning back on. + +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; + +use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text, typed, typename_of}; +use crate::ScriptPreference; +use crate::script::dialogs::{DialogKind, OnYes, ScriptDialog}; + +/// The key that stands for the preference `showExternalScriptWarning`. +pub const EXTERNAL_SCRIPT_WARNING: &str = "ShowExternalJSXWarning"; +/// The longest key, in UTF-16 units. +pub const MAX_KEY_UNITS: usize = 256; +/// The longest string value, in bytes. +pub const MAX_STRING_BYTES: usize = 64 * 1024; +/// The most keys stored. +pub const MAX_KEYS: usize = 4096; +/// The most bytes stored, keys and values together; a value that is not a string counts 8. +pub const MAX_TOTAL_BYTES: usize = 1024 * 1024; + +/// The confirm a run shows before a script turns off [`EXTERNAL_SCRIPT_WARNING`]; No is its default. +pub const WARNING_OFF_QUESTION: &str = "The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off?"; +/// The error when a script turns off [`EXTERNAL_SCRIPT_WARNING`] in a run that cannot ask the person. +pub const WARNING_OFF_NEEDS_A_PERSON: &str = + "ShowExternalJSXWarning can be turned off only after the person at the computer agrees, in a run that can show a dialog"; + +/// The largest whole number `setIntegerPreference` takes. +const MAX_INTEGER: f64 = 9_007_199_254_740_992.0; + +/// The `app.preferences` member of `Application`. +pub(super) fn app_members() -> Vec { + named(vec![("preferences", HostMember::Get(std::rc::Rc::new(|_| Ok(host_ref("Preferences", &[])))), typed("Preferences"))]) +} + +/// The `Preferences` class. +pub(super) fn class(link: &Link) -> HostClass { + let l = link; + let key = [("key", "string")]; + super::class( + "Preferences", + None, + named(vec![ + ("typename", typename_of("Preferences"), typed("string")), + ("getBooleanPreference", method(l, |h, a| get(h, a, Kind::Boolean)), returns("boolean", &key)), + ("getIntegerPreference", method(l, |h, a| get(h, a, Kind::Integer)), returns("number", &key)), + ("getRealPreference", method(l, |h, a| get(h, a, Kind::Real)), returns("number", &key)), + ("getStringPreference", method(l, |h, a| get(h, a, Kind::String)), returns("string", &key)), + ("setBooleanPreference", method(l, |h, a| set(h, a, Kind::Boolean)), returns("undefined", &[("key", "string"), ("value", "boolean")])), + ("setIntegerPreference", method(l, |h, a| set(h, a, Kind::Integer)), returns("undefined", &[("key", "string"), ("value", "number")])), + ("setRealPreference", method(l, |h, a| set(h, a, Kind::Real)), returns("undefined", &[("key", "string"), ("value", "number")])), + ("setStringPreference", method(l, |h, a| set(h, a, Kind::String)), returns("undefined", &[("key", "string"), ("value", "string")])), + ("removePreference", method(l, remove), returns("undefined", &key)), + ]), + None, + ) +} + +#[derive(Clone, Copy)] +enum Kind { + Boolean, + Integer, + Real, + String, +} + +/// The key of a call on `app.preferences`: `this` must be that object, and the key a string within +/// the limits. +fn key_of(a: &[Data]) -> std::result::Result<&str, HostError> { + if !matches!(host_ref_parts(arg(a, 0)), Some(("Preferences", _))) { + return Err(HostError::Type("this is not a Preferences object".into())); + } + let Data::String(key) = arg(a, 1) else { return Err(HostError::Type("a preference's key must be a string".into())) }; + if key.is_empty() || key.encode_utf16().count() > MAX_KEY_UNITS { + return Err(HostError::Range(format!( + "a preference's key must have a length of 1 to {MAX_KEY_UNITS} (UTF-16 code units, as `length` counts)" + ))); + } + if key.chars().any(char::is_control) { + return Err(HostError::Error("a preference's key cannot hold control characters".into())); + } + Ok(key) +} + +/// The value stored under `key`, if any. +fn stored(h: &Host, key: &str) -> Option { + let s = h.session.borrow(); + if key == EXTERNAL_SCRIPT_WARNING { + return Some(ScriptPreference::Boolean(s.prefs.show_external_script_warning)); + } + s.prefs.script_preferences.get(key).cloned() +} + +/// `Number(text)`: blank text is 0, `0x`, `0o` and `0b` start a whole number in base 16, 8 or 2, +/// and text that is not a number is NaN. The whitespace trimmed is JavaScript's: Unicode's +/// `White_Space` without U+0085 (NEXT LINE), and U+FEFF. +fn text_number(t: &str) -> f64 { + let t = t.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'); + if t.is_empty() { + return 0.0; + } + let radix = match t.get(..2) { + Some("0x" | "0X") => 16, + Some("0o" | "0O") => 8, + Some("0b" | "0B") => 2, + _ => 0, + }; + if radix != 0 { + return radix_number(t.get(2..).unwrap_or(""), radix).unwrap_or(f64::NAN); + } + match t.strip_prefix(['+', '-']).unwrap_or(t) { + "Infinity" => { + if t.starts_with('-') { + f64::NEG_INFINITY + } else { + f64::INFINITY + } + } + rest if rest.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-')) => t.parse().unwrap_or(f64::NAN), + _ => f64::NAN, + } +} + +/// The whole number `digits` writes in base `radix` (16, 8 or 2), rounded once to the nearest +/// number, ties to the even one, and infinite past the largest; `None` when it is empty or holds a +/// character that is not a digit of that base. +fn radix_number(digits: &str, radix: u32) -> Option { + if digits.is_empty() { + return None; + } + let width = radix.trailing_zeros(); + // The first 64 bits from the leading 1, how many bits come after them, and whether any of + // those is 1. + let (mut top, mut taken, mut past, mut sticky) = (0u64, 0u32, 0u64, false); + for c in digits.chars() { + let d = c.to_digit(radix)?; + for bit in (0..width).rev().map(|i| (d >> i) & 1 == 1) { + if taken == 0 && !bit { + continue; + } + if taken < 64 { + top = (top << 1) | u64::from(bit); + taken += 1; + } else { + past = past.saturating_add(1); + sticky |= bit; + } + } + } + if taken <= 53 { + return Some(top as f64); + } + // Keep 53 bits; the dropped ones round them to the nearest, ties to even. + let drop = taken - 53; + let (kept, rest, half) = (top >> drop, top & ((1u64 << drop) - 1), 1u64 << (drop - 1)); + let up = rest > half || (rest == half && (sticky || kept & 1 == 1)); + let kept = kept + u64::from(up); + let exp = i32::try_from(u64::from(drop).saturating_add(past)).unwrap_or(i32::MAX).min(2000); + Some(kept as f64 * 2f64.powi(exp)) +} + +#[allow(clippy::cast_precision_loss)] +fn as_number(v: &ScriptPreference) -> f64 { + match v { + ScriptPreference::Boolean(b) => f64::from(u8::from(*b)), + ScriptPreference::Integer(n) => *n as f64, + ScriptPreference::Real(n) => *n, + ScriptPreference::String(t) => text_number(t), + } +} + +fn get(h: &Host, a: &[Data], kind: Kind) -> Answer { + let key = key_of(a)?; + let v = stored(h, key); + Ok(match (kind, v) { + (Kind::Boolean, None) => Data::Bool(false), + (Kind::Integer | Kind::Real, None) => num(0.0), + (Kind::String, None) => text(""), + (Kind::Boolean, Some(v)) => Data::Bool(match v { + ScriptPreference::Boolean(b) => b, + ScriptPreference::String(t) => !t.is_empty(), + v => { + let n = as_number(&v); + n != 0.0 && !n.is_nan() + } + }), + (Kind::Real, Some(v)) => num(as_number(&v)), + (Kind::Integer, Some(v)) => { + let n = as_number(&v).trunc(); + num(if n.is_finite() { n } else { 0.0 }) + } + (Kind::String, Some(v)) => text(match v { + ScriptPreference::Boolean(b) => b.to_string(), + ScriptPreference::String(t) => t, + v => vectorcraft_js::number_to_string(as_number(&v)), + }), + }) +} + +/// The bytes `key` and `v` count toward [`MAX_TOTAL_BYTES`]. +fn size(key: &str, v: &ScriptPreference) -> usize { + key.len() + if let ScriptPreference::String(t) = v { t.len() } else { 8 } +} + +/// Whether `store` holds at most [`MAX_KEYS`] keys and [`MAX_TOTAL_BYTES`] bytes. +pub fn within_limits(store: &std::collections::BTreeMap) -> bool { + store.len() <= MAX_KEYS && store.iter().map(|(k, v)| size(k, v)).sum::() <= MAX_TOTAL_BYTES +} + +#[allow(clippy::cast_possible_truncation)] +fn set(h: &Host, a: &[Data], kind: Kind) -> Answer { + let key = key_of(a)?.to_string(); + let v = arg(a, 2); + let value = match (kind, v) { + (Kind::Boolean, Data::Bool(b)) => ScriptPreference::Boolean(*b), + (Kind::Integer, Data::Number(n)) if n.fract() == 0.0 && n.abs() <= MAX_INTEGER => ScriptPreference::Integer(*n as i64), + (Kind::Real, Data::Number(n)) if n.is_finite() => ScriptPreference::Real(*n), + (Kind::String, Data::String(t)) if t.len() <= MAX_STRING_BYTES => ScriptPreference::String(t.clone()), + (Kind::String, Data::String(_)) => return Err(HostError::Range(format!("a preference's text has at most {MAX_STRING_BYTES} bytes"))), + (Kind::Boolean, _) => return Err(HostError::Type("setBooleanPreference needs true or false".into())), + (Kind::Integer, _) => return Err(HostError::Type("setIntegerPreference needs a whole number".into())), + (Kind::Real, _) => return Err(HostError::Type("setRealPreference needs a finite number".into())), + (Kind::String, _) => return Err(HostError::Type("setStringPreference needs a string".into())), + }; + if key == EXTERNAL_SCRIPT_WARNING { + let ScriptPreference::Boolean(on) = value else { + return Err(HostError::Type(format!("{EXTERNAL_SCRIPT_WARNING} is set with setBooleanPreference"))); + }; + return set_warning(h, on); + } + let mut s = h.session.borrow_mut(); + let store = &mut s.prefs.script_preferences; + if store.get(&key) == Some(&value) { + return Ok(Data::Undefined); + } + let total: usize = store.iter().filter(|(k, _)| **k != key).map(|(k, v)| size(k, v)).sum(); + let count = store.len() + usize::from(!store.contains_key(&key)); + if count > MAX_KEYS { + return Err(HostError::Range(format!("app.preferences holds at most {MAX_KEYS} keys"))); + } + if total + size(&key, &value) > MAX_TOTAL_BYTES { + return Err(HostError::Range(format!("app.preferences holds at most {MAX_TOTAL_BYTES} bytes"))); + } + store.insert(key, value); + Ok(Data::Undefined) +} + +/// Sets `showExternalScriptWarning` in the run's preferences: on at once, and off only after the +/// person answers Yes to [`WARNING_OFF_QUESTION`] ([`crate::Session::script_answer`] sets it). With +/// nobody to ask, turning it off throws and changes nothing. Scripts cannot run `prefs.set`; the +/// run's preferences are put back when the run fails and merged into the app's when it ends. +fn set_warning(h: &Host, on: bool) -> Answer { + if on || !h.session.borrow().prefs.show_external_script_warning { + h.session.borrow_mut().prefs.show_external_script_warning = on; + return Ok(Data::Undefined); + } + let question = ScriptDialog { + kind: DialogKind::Confirm, + message: WARNING_OFF_QUESTION.into(), + title: None, + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) { + return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into())); + } + Err(HostError::Wait) +} + +fn remove(h: &Host, a: &[Data]) -> Answer { + let key = key_of(a)?; + if key == EXTERNAL_SCRIPT_WARNING { + h.session.borrow_mut().prefs.show_external_script_warning = true; + } else if h.session.borrow().prefs.script_preferences.contains_key(key) { + h.session.borrow_mut().prefs.script_preferences.remove(key); + } + Ok(Data::Undefined) +} diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs new file mode 100644 index 0000000000..f8dbeba57f --- /dev/null +++ b/crates/engine/src/script/dom/transform.rs @@ -0,0 +1,356 @@ +//! The transform methods of a page item, `translate`, `rotate`, `resize` and `transform`, as the +//! help page describes them. Each one +//! runs `object.transform` on the object, with its selection kept, so it joins the run's one undo +//! step for the document; a call that changes nothing runs no command. `PathItem` uses these +//! methods too. +//! +//! VectorCraft's own rules, which the help page does not state: +//! - Offsets, angles and matrices are taken with Y up, as `Matrix` records are, whatever +//! `app.coordinateSystem` is: `translate(0, 10)` moves the object up, and a positive angle turns +//! it counterclockwise. +//! - `rotate`, `resize` and `transform` act about the center of the object's geometric bounds, +//! unless a `Transformation` value names another point of those bounds; `DOCUMENTORIGIN` is the +//! bottom-left corner of the first artboard. A matrix's own translation is added after it acts +//! about that point. The value is checked even when the call changes nothing. +//! - Positions, pattern fills and pattern strokes, and gradients each follow their argument: +//! positions and gradients default to `true`, and patterns to the Transform Pattern Tiles +//! preference. Fill and stroke patterns transform together, and gradients with the object, so a +//! call whose values differ, counting the defaults of the arguments it leaves out, throws an error +//! that says so. +//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own +//! scale in percent, the square root of the area it scales by (stroke weights and effects scale +//! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to +//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any +//! other value, and a scale of strokes and effects with positions left as they are, throws an +//! error that says so. +//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a +//! locked object, and an object on a locked artboard are refused with nothing changed, and so are +//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object +//! past the canvas. + +use serde_json::json; +use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_js::{Data, HostError}; + +use super::matrix::{self, Matrix}; +use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc}; + +/// The error for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; + +/// The error for a locked object. +const LOCKED: &str = "cannot transform locked objects"; + +/// The error for a hidden object. +const HIDDEN: &str = "cannot transform hidden objects"; + +/// The identity matrix. +const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// What a transform method changes besides the object's geometry. +struct Options { + /// Positions and orientations (`changePositions`, `transformObjects`). + objects: bool, + /// Pattern fills and strokes. + patterns: bool, + /// Stroke weights and effects (`changeLineWidths`). + strokes: bool, +} + +/// An optional `true` or `false` argument. +fn flag(d: &Data, what: &str) -> std::result::Result, HostError> { + match d { + Data::Undefined => Ok(None), + Data::Bool(b) => Ok(Some(*b)), + _ => Err(HostError::Type(format!("{what} must be true or false"))), + } +} + +/// The positions, fill patterns, fill gradients and stroke patterns arguments at `at` and after, +/// with the names the method gives them. +fn options(h: &Host, a: &[Data], at: usize, names: [&str; 4]) -> std::result::Result { + let tiles = h.session.borrow().prefs.transform_pattern_tiles; + let objects = flag(arg(a, at), names[0])?.unwrap_or(true); + let fill = flag(arg(a, at + 1), names[1])?.unwrap_or(tiles); + let gradients = flag(arg(a, at + 2), names[2])?.unwrap_or(true); + let stroke = flag(arg(a, at + 3), names[3])?.unwrap_or(tiles); + if fill != stroke { + return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3]))); + } + if gradients != objects { + return Err(HostError::Error(format!("{} different from {} is not available yet", names[2], names[0]))); + } + Ok(Options { objects, patterns: fill, strokes: false }) +} + +/// Whether `changeLineWidths` (`d`) is the scale of the linear part `m` of a matrix, so stroke +/// weights and effects scale with it (`Some(true)`), or 100 (`Some(false)`); `None` for any other +/// number. +fn own_line_widths(d: &Data, m: Matrix) -> std::result::Result<(Option, f64, f64), HostError> { + let lw = match d { + Data::Undefined => return Ok((Some(false), 100.0, 100.0)), + d => number(d, "changeLineWidths")?, + }; + if lw < 0.0 { + return Err(HostError::Range("changeLineWidths must not be negative".into())); + } + // The determinant is taken past the range of a number, so a scale whose square is too large + // for one still has its own value. + // 100 keeps the stroke weights, even for a scale within the tolerance of it. + let own = matrix::area_scale(m) * 100.0; + if (lw - 100.0).abs() <= 1e-9 { + return Ok((Some(false), lw, own)); + } + if lw > 0.0 && own.is_finite() && (lw - own).abs() <= 1e-9 * own { + return Ok((Some((own - 100.0).abs() > 1e-9), lw, own)); + } + Ok((None, lw, own)) +} + +/// The error for a `changeLineWidths` the method does not take. +fn other_line_widths(own: f64) -> HostError { + HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet")) +} + +/// Whether `changeLineWidths` (`d`) scales stroke weights for the linear part `m` of a matrix. +fn line_widths(d: &Data, m: Matrix) -> std::result::Result { + match own_line_widths(d, m)? { + (Some(strokes), _, _) => Ok(strokes), + (None, _, own) => Err(other_line_widths(own)), + } +} + +/// The member of `Transformation` that `d` names (left out: `CENTER`). +fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> { + const MEMBERS: [&str; 10] = ["CENTER", "TOPLEFT", "TOP", "TOPRIGHT", "LEFT", "RIGHT", "BOTTOMLEFT", "BOTTOM", "BOTTOMRIGHT", "DOCUMENTORIGIN"]; + let name = match d { + Data::Undefined => "CENTER", + Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""), + _ => "", + }; + if MEMBERS.contains(&name) { Ok(name) } else { Err(HostError::Type("the point to transform about must be a Transformation value".into())) } +} + +/// The point of `r` (document coordinates, Y down) that the `Transformation` member `name` +/// ([`anchor_name`]) names. +fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result { + let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + Ok(match name { + "TOPLEFT" => Point::new(r.x0, r.y0), + "TOP" => Point::new(cx, r.y0), + "TOPRIGHT" => Point::new(r.x1, r.y0), + "LEFT" => Point::new(r.x0, cy), + "RIGHT" => Point::new(r.x1, cy), + "BOTTOMLEFT" => Point::new(r.x0, r.y1), + "BOTTOM" => Point::new(cx, r.y1), + "BOTTOMRIGHT" => Point::new(r.x1, r.y1), + "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?, + _ => Point::new(cx, cy), + }) +} + +/// The matrix `m` (Y up) as it acts on the page (Y down), about `o`. +fn on_page(m: Matrix, o: Point) -> Affine { + let [a, b, c, d, tx, ty] = m; + let (b, c, ty) = (0.0 - b, 0.0 - c, 0.0 - ty); + if [a, b, c, d] == [1.0, 0.0, 0.0, 1.0] { + return Affine::translate((tx, ty)); + } + Affine::translate((o.x + tx, o.y + ty)) * Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate((-o.x, -o.y)) +} + +/// Whether the object `id` of `d` stays within the canvas under `xf` (page coordinates), symbol +/// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. The +/// object is measured whole, and a group is looked into object by object, as the native file's +/// canvas check does (`vectorcraft_doc::canvas_range`), since a clipping group's bounds are its +/// clipping path's and leave out the art it clips. +fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool { + fn within(n: &vectorcraft_doc::Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool { + if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. } | vectorcraft_doc::NodeKind::Layer { .. }) { + n.children().into_iter().flatten().all(|c| within(c, symbols)) + } else { + n.geometric_bounds_with(symbols).is_none_or(crate::sanity::rect_in_range) + } + } + d.node(id).is_some_and(|n| { + let mut n = n.clone(); + n.transform(xf, false); + within(&n, &d.symbol_boxes()) + }) +} + +/// Applies `m` (Y up) to `item`, about the point `about` names (`None`: the matrix acts as a move, +/// which needs no point), with `opts`, then sets the stroke weight of a path to `weight` points +/// when it is given. +fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, weight: Option) -> Answer { + let about = about.map(anchor_name).transpose()?; + if m.iter().any(|v| !v.is_finite()) { + return Err(HostError::Range("the transformation has a value too large for a number".into())); + } + if matrix::singular(m) { + return Err(HostError::Error("the transformation is singular and would flatten the object".into())); + } + let (locked, hidden, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let line = d.ancestry(item.id); + let mut locked = line.as_ref().is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); + let hidden = line.as_ref().is_none_or(|a| a.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(|n| !n.visible))); + let (mut uses, mut clipped) = (false, false); + if let Some(n) = d.node(item.id) { + n.walk(&mut |c| { + locked |= c.locked; + uses |= vectorcraft_doc::pattern::uses_pattern(c, None); + clipped |= + matches!(c.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. }); + }); + } + (locked, hidden, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, clipped) + }); + if locked { + return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0))); + } + if hidden { + return Err(HostError::Error(format!("{HIDDEN}: {}", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } + // The identity acts the same about every point, so an object without bounds (an empty path) + // takes it too. + let o = match (about, bounds) { + _ if m == IDENTITY => Point::ORIGIN, + (Some(name), Some(r)) => anchor(h, item, r, name)?, + // A path with no anchors has no bounds to turn or scale about, and turning or scaling it + // changes nothing; only a stroke weight the call sets is applied. + (Some(_), None) if paths::is_path(h, item) => { + if let Some(w) = weight { + paths::set_stroke_weight(h, item, w)?; + } + return Ok(Data::Undefined); + } + (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), + (None, _) => Point::ORIGIN, + }; + let xf = on_page(m, o); + if opts.strokes && !opts.objects { + return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); + } + if opts.objects && xf != Affine::IDENTITY { + // The transformed corners of the bounds hold the transformed object. When one of them is + // past the canvas, or the object holds a clipping group (whose bounds leave out the art + // it clips), the transformed object itself is measured. + let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD; + let outside = bounds.is_some_and(|r| { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)]; + !corners.iter().all(|p| inside(xf * *p)) + }); + if (clipped || outside) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) { + return Err(HostError::Range("the transformation would take the object past the canvas".into())); + } + } + let c = xf.as_coeffs(); + let identity = xf == Affine::IDENTITY; + let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; + // The transformation and the stroke weight change together or not at all. + atomically(h, |h| { + if changes { + let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes}); + edit_item(h, item, "object.transform", &p)?; + } + if let Some(w) = weight { + paths::set_stroke_weight(h, item, w)?; + } + Ok(Data::Undefined) + }) +} + +/// `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?, +/// transformStrokePatterns?)`: moves the object by `deltaX` and `deltaY` points (0 when left out). +pub(super) fn translate(h: &Host, a: &[Data]) -> Answer { + let delta = |i: usize, what: &str| match arg(a, i) { + Data::Undefined => Ok(0.0), + d => number(d, what), + }; + let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?); + let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"]; + let opts = options(h, a, 3, names)?; + let item = this_item(h, a)?; + // An offset past the canvas is refused only when the call moves the object or a pattern it + // uses. + let limit = coordinate(&Data::Number(dx), "deltaX").and_then(|_| coordinate(&Data::Number(dy), "deltaY")); + if let Err(e) = limit { + let moves = opts.objects + || opts.patterns + && with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).is_some_and(|n| { + let mut uses = false; + n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None)); + uses + }) + }); + if moves { + return Err(e); + } + } + apply(h, item, matrix::translate(dx, dy), None, &opts, None) +} + +const CHANGE_NAMES: [&str; 4] = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; + +/// `rotate(angle, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?, +/// rotateAbout?)`: turns the object by `angle` degrees, counterclockwise when it is positive. +pub(super) fn rotate(h: &Host, a: &[Data]) -> Answer { + let angle = number(arg(a, 1), "angle")?; + let opts = options(h, a, 2, CHANGE_NAMES)?; + apply(h, this_item(h, a)?, matrix::rotate(angle), Some(arg(a, 6)), &opts, None) +} + +/// `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, +/// changeStrokePattern?, changeLineWidths?, scaleAbout?)`: scales the object by `scaleX` and +/// `scaleY` percent along the page's axes. +pub(super) fn resize(h: &Host, a: &[Data]) -> Answer { + let (sx, sy) = (number(arg(a, 1), "scaleX")?, number(arg(a, 2), "scaleY")?); + if sx == 0.0 || sy == 0.0 { + return Err(HostError::Range("scaleX and scaleY must not be 0".into())); + } + let m = matrix::scaled(sx, sy); + let mut opts = options(h, a, 3, CHANGE_NAMES)?; + let item = this_item(h, a)?; + let weight = match own_line_widths(arg(a, 7), m)? { + // The compound holds a member's visible stroke, so its weight is set through the compound + // as well as the member's own strokes and effects scaling, by the scale itself. + (Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { + opts.strokes = true; + paths::resized_stroke_weight(h, item, own, false)? + } + (Some(strokes), _, _) => { + opts.strokes = strokes; + None + } + (None, lw, _) if paths::is_path(h, item) => paths::resized_stroke_weight(h, item, lw, true)?, + (None, _, own) => return Err(other_line_widths(own)), + }; + apply(h, item, m, Some(arg(a, 8)), &opts, weight) +} + +/// `transform(transformationMatrix, changePositions?, changeFillPatterns?, changeFillGradients?, +/// changeStrokePattern?, changeLineWidths?, transformAbout?)`: applies a `Matrix` record to the +/// object. +pub(super) fn transform(h: &Host, a: &[Data]) -> Answer { + let m = matrix::matrix(arg(a, 1), "transformationMatrix")?; + let mut opts = options(h, a, 2, CHANGE_NAMES)?; + let item = this_item(h, a)?; + let weight = match own_line_widths(arg(a, 6), m)? { + // As in `resize`: the compound holds a member's visible stroke, so its weight is set + // through the compound as well. + (Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { + opts.strokes = true; + paths::resized_stroke_weight(h, item, own, false)? + } + _ => { + opts.strokes = line_widths(arg(a, 6), m)?; + None + } + }; + apply(h, item, m, Some(arg(a, 7)), &opts, weight) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 870040160b..03b5e7437a 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -482,6 +482,7 @@ struct World { draw_mode: DrawMode, draw_inside: Option, clipboard: Clipboard, + clipboard_copied: bool, untitled_counter: u32, menu: cmd::menucmds::MenuState, last_solid: crate::Color, @@ -563,19 +564,35 @@ impl Choices { } /// The preferences after a run: `current`, the session's, which the app may have changed while the -/// run went on, with each preference the run changed from `start` set to the run's value. +/// run went on, with each preference the run changed from `start` set to the run's value. A +/// preference the run emptied, which is then left out of the saved form, is left out of the result. +/// The values scripts store with `app.preferences` are merged the same way one key at a time. fn merged_prefs(start: &crate::Prefs, run: &crate::Prefs, current: &crate::Prefs) -> crate::Prefs { - let (Ok(Value::Object(start)), Ok(Value::Object(run)), Ok(Value::Object(mut out))) = + const SCRIPT_KEYS: &str = "scriptPreferences"; + let (Ok(Value::Object(start_json)), Ok(Value::Object(run_json)), Ok(Value::Object(mut out))) = (serde_json::to_value(start), serde_json::to_value(run), serde_json::to_value(current)) else { return current.clone(); }; - for (key, value) in run { - if start.get(&key) != Some(&value) { + for key in start_json.keys().filter(|k| *k != SCRIPT_KEYS && !run_json.contains_key(*k)) { + out.remove(key); + } + for (key, value) in run_json { + if key != SCRIPT_KEYS && start_json.get(&key) != Some(&value) { out.insert(key, value); } } - serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()) + let mut merged: crate::Prefs = serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()); + let script = &mut merged.script_preferences; + for key in start.script_preferences.keys().filter(|k| !run.script_preferences.contains_key(*k)) { + script.remove(key); + } + for (key, value) in &run.script_preferences { + if start.script_preferences.get(key) != Some(value) { + script.insert(key.clone(), value.clone()); + } + } + merged } impl World { @@ -595,6 +612,7 @@ impl World { draw_mode: s.draw_mode, draw_inside: s.draw_inside, clipboard: s.clipboard.clone(), + clipboard_copied: s.clipboard_copied, untitled_counter: s.untitled_counter, menu: s.menu.clone(), last_solid: s.last_solid, @@ -618,6 +636,7 @@ impl World { swap(&mut self.draw_mode, &mut s.draw_mode); swap(&mut self.draw_inside, &mut s.draw_inside); swap(&mut self.clipboard, &mut s.clipboard); + swap(&mut self.clipboard_copied, &mut s.clipboard_copied); swap(&mut self.untitled_counter, &mut s.untitled_counter); swap(&mut self.menu, &mut s.menu); swap(&mut self.last_solid, &mut s.last_solid); @@ -629,9 +648,11 @@ impl World { } } -/// The commands that can change the clipboard and still fail, and that do not put it back -/// themselves. The clipboard can hold a great deal, so a savepoint copies it only for these. -const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "edit.cut"]; +/// The commands that can change the clipboard and still fail, or still be put back because their +/// result cannot reach the script, and that do not put it back themselves. The clipboard can hold +/// a great deal, so a savepoint copies it only for these. +const CAN_FAIL_AFTER_COPYING: &[&str] = + &["action.batch", "artboard.copy", "artboard.cut", "clipboard.importSvg", "command.batch", "edit.copy", "edit.cut"]; /// The commands that remove a document's undo history, or the document: a savepoint keeps a whole /// copy of the histories for these. Any other command that removes or changes a step under the @@ -655,7 +676,8 @@ pub(crate) struct Savepoint { fill_active: bool, draw_mode: DrawMode, draw_inside: Option, - clipboard: Option, + /// The clipboard, [`Session::clipboard_copied`] and [`Session::copies`]. + clipboard: Option<(Clipboard, bool, u64)>, untitled_counter: u32, menu: cmd::menucmds::MenuState, last_solid: crate::Color, @@ -691,7 +713,7 @@ impl Savepoint { fill_active: s.fill_active, draw_mode: s.draw_mode, draw_inside: s.draw_inside, - clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| s.clipboard.clone()), + clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| (s.clipboard.clone(), s.clipboard_copied, s.copies)), untitled_counter: s.untitled_counter, menu: s.menu.clone(), last_solid: s.last_solid, @@ -742,8 +764,10 @@ impl Savepoint { s.fill_active = self.fill_active; s.draw_mode = self.draw_mode; s.draw_inside = self.draw_inside; - if let Some(clipboard) = self.clipboard { + if let Some((clipboard, copied, copies)) = self.clipboard { s.clipboard = clipboard; + s.clipboard_copied = copied; + s.copies = copies; } s.untitled_counter = self.untitled_counter; s.menu = self.menu; @@ -781,6 +805,9 @@ struct Host { log: RefCell>, log_bytes: Cell, written: RefCell, + /// A command ran a Copy or Cut ([`Session::copies`]), also inside a batch or an action, and + /// the run kept it. + copied: Cell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, name: Arc, @@ -1337,8 +1364,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value raise_ids(s); s.script_style_trail = StyleTrail::start(s); let mutating = waits_for_tool_edit(id); - // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. - let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); + // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A + // query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard. + let save = ((mutating || CAN_FAIL_AFTER_COPYING.contains(&id)) && !host.dom.saving()).then(|| Savepoint::take(s, id)); let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); @@ -1436,9 +1464,9 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: let session = host.session.clone(); let started = clock(); let before = dom::before_command(host, id); - let r = { + let (copies, r) = { let mut s = session.borrow_mut(); - step(&mut s, host, id, params) + (s.copies, step(&mut s, host, id, params)) }; // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(id)) { @@ -1469,14 +1497,19 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: if crossed.is_err() { host.put_growth_back(mark); } + let mut s = session.borrow_mut(); if let Some(save) = save { - let mut s = session.borrow_mut(); if crossed.is_ok() { save.keep(&mut s); } else if !save.restore(&mut s) { return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + // A Copy or Cut counts for the run only once what it put on the clipboard is kept. + if s.copies != copies { + host.copied.set(true); + } + drop(s); dom::after_command(host, before); // Style objects follow only a command that is kept. if crossed.is_ok() { @@ -2082,12 +2115,28 @@ impl Session { self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting())).flatten() } + /// Whether [`Session::script_dialog`] is the confirm the app opened to turn off the external + /// script warning, which only a person answers Yes to. A script's own confirm with the same + /// text is not. + pub fn script_dialog_turns_warning_off(&self) -> bool { + self.script_dialog().is_some() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.asks_warning_off())).unwrap_or(false) + } + /// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`] /// goes on from the call. → false when nothing waits, the answer is for another kind of - /// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. + /// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. Yes to a confirm the + /// app opened for the script ([`dialogs::Dialogs::ask`]) also does what it asked. pub fn script_answer(&mut self, answer: DialogAnswer) -> bool { let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false }; - with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) + with_job(k, |j| { + let given = j.host.dialogs.answer(&mut j.realm, answer); + // Between slices the run's preferences are in its working copy. + if let Some(dialogs::OnYes::ExternalScriptWarningOff) = j.host.dialogs.take_approved() { + j.world.choices.prefs.show_external_script_warning = false; + } + given + }) + .unwrap_or(false) } /// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run @@ -2345,6 +2394,7 @@ impl Session { log: RefCell::new(Vec::new()), log_bytes: Cell::new(0), written: RefCell::new(Written::default()), + copied: Cell::new(false), run: self.script_runs, name: console::line_name(&name), console: RefCell::default(), @@ -2710,6 +2760,13 @@ impl Session { if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) { report["activeArtboards"] = boards; } + // The run ran a Copy or Cut, and the clipboard still holds what one put there. + if host.copied.get() + && self.clipboard_copied + && let Some(o) = report.as_object_mut() + { + o.insert("copied".into(), json!(true)); + } // The jobs it prepared for a printer wait for the frontend now that its changes are kept. let prints = host.dom.take_prints(); if !prints.is_empty() { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 15192a6593..187991483c 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -54,6 +54,8 @@ impl Session { paint: PaintDefaults::default(), fill_active: true, clipboard: Clipboard::default(), + copies: 0, + clipboard_copied: false, journal: Journal::default(), history_budget: crate::default_history_budget(), histories_seen: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5726348db1..6aa26f2edc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -187,7 +187,9 @@ mod script_dom; mod script_dom_defaults; mod script_dom_images; mod script_dom_paths; +mod script_dom_prefs; mod script_dom_tracing; +mod script_dom_transform; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 53740a8f42..af12afa21f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -174,6 +174,18 @@ fn control_bounds_include_handles_inside_live_containers() { } } +#[test] +fn control_bounds_take_in_the_direction_points() { + let (mut s, _, _) = doc(); + // An arch whose top is at y 40 and whose direction points are at y 20. + let id = s.execute("path.create", &json!({"d": "M100 100C100 20 200 20 200 100"})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap_or(f64::NAN); + assert!(top(&out[0]) < 265.0, "{out:?}"); + assert_eq!(top(&out[1]), 280.0, "{out:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -764,6 +776,24 @@ fn control_bounds_take_in_direction_points_past_the_curve() { assert_eq!(out[2], out[3]); } +#[test] +fn a_failed_selection_assignment_leaves_the_selection_within_the_run() { + let (mut s, _, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + // The run goes on after the failed assignment, so nothing it ends with puts the selection back. + let c = rect(&mut s, 200.0, 20.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, open, shut;\ + for (var i = 0; i < p.length; i++) { if (p[i].locked) shut = p[i]; else if (!p[i].selected) open = p[i]; }\ + try { d.selection = [open, shut]; vc.log('assigned'); } catch (e) { vc.log(String(e.message).indexOf('Cannot select') >= 0); }\ + vc.log([d.selection.length, open.selected, d.selection[0].locked]);", + ); + assert_eq!(out, vec![json!(true), json!([1, false, false])]); + assert_eq!(s.active().unwrap().selection.objects, vec![c]); +} + #[test] fn a_guide_path_is_not_selected_while_guides_are_locked() { let (mut s, a, b) = doc(); @@ -1529,7 +1559,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() { for source in [ "app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", - "app.activeDocument.pageItems[0].transform(5);", + "app.activeDocument.pageItems[0].bringInPerspective(0, 0);", ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } @@ -1838,6 +1868,46 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document"); } +#[test] +fn a_startup_preset_uses_its_own_size_beside_a_saved_preset_of_the_same_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 300, "height": 200})).unwrap(); + let first = crate::cmd::newdoc::category(&s, "Print").unwrap().remove(0); + assert_eq!(first.name, "Letter"); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height]);"); + assert_eq!((out[0][0].as_f64(), out[0][1].as_f64()), (Some(first.width), Some(first.height)), "{out:?}"); +} + +#[test] +fn document_presets_hold_a_limited_amount_of_data() { + let mut s = Session::new(); + // A 4,096-byte title fits and replacing it does not add up; one byte more is refused. + let out = log( + &mut s, + "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset();\ + for (var k = 0; k < 20; k++) p.title = t; vc.log(p.title.length);", + ); + assert_eq!(out, vec![json!(4096)]); + let e = failure(&mut s, "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset(); p.title = t + 'x';"); + assert!(e.contains("the title is too long"), "{e}"); +} + +#[test] +fn moving_art_on_another_layer_keeps_the_current_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.active().unwrap().current_layer().unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let b = s.active().unwrap().current_layer().unwrap(); + assert_ne!(a, b); + rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + s.active_mut().unwrap().active_layer = Some(a); + log(&mut s, "var i = app.activeDocument.pageItems[0]; i.left = i.left + 5; i.translate(5, 0);"); + assert_eq!(s.active().unwrap().current_layer(), Some(a)); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); @@ -2353,6 +2423,37 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it +/// is runs no command, also in a layer whose ruler guides are above its art. +#[test] +fn move_refuses_art_on_a_locked_artboard_and_skips_a_move_to_the_same_place() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + let steps = undo_steps(&s); + // The topmost art, moved to the top of its layer, stays where it is. + log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, top = p[0];\ + for (var i = 1; i < p.length; i++) { if (p[i].zOrderPosition > top.zOrderPosition) top = p[i]; }\ + top.move(top.parent);", + ); + assert_eq!(undo_steps(&s), steps, "a move to the same place adds no step"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let order = |s: &Session| format!("{:?}", (s.active().unwrap().doc.position(a), s.active().unwrap().doc.position(b))); + let before = order(&s); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATBEGINNING);"); + assert!(e.contains("Cannot move PathItem"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1].parent, ElementPlacement.PLACEATEND);"); + assert!(e.contains("Cannot move PathItem"), "{e}"); + assert_eq!(order(&s), before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { let mut s = Session::new(); @@ -3765,7 +3866,7 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('layers'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index d24863c245..e9ff7536ea 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -973,6 +973,39 @@ fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() { } } +#[test] +fn resizing_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.resize(50, 50, true, true, true, true, 50);\ + vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);", + ); + assert_eq!(out, vec![json!(2), json!(2)], "the compound's stroke halves with the member"); +} + +#[test] +fn transforming_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.transform(app.getScaleMatrix(50), true, true, true, true, 50);\ + vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);", + ); + assert_eq!(out, vec![json!(2), json!(2)], "transform scales the compound's stroke as resize does"); + // 100 keeps the weight even when the scale is within the tolerance of 100%. + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.transform(app.getScaleMatrix(100.00000005), true, true, true, true, 100);\ + vc.log(p.strokeWidth);", + ); + assert_eq!(out, vec![json!(2)]); +} + #[test] fn set_anchors_reads_smooth_false_as_a_corner() { let (mut s, a, _) = doc(); @@ -1442,7 +1475,7 @@ fn locked_paths_and_wrong_objects_are_refused() { ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "Cannot edit PathItem"), ("app.activeDocument.pathItems[0].strokeWidth = 3;", "Cannot edit PathItem"), - ("app.activeDocument.pathItems[0].translate(5, 5);", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].translate(5, 5);", "cannot transform locked objects"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); @@ -1475,10 +1508,10 @@ fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { assert_eq!(out[3], json!(6)); assert!(failure(&mut s, "app.activeDocument.pathItems[0].rotate(10, true, true, true, true, 'CENTER');").contains("Transformation")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].resize(0, 100);").contains("scaleX")); - assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("changePositions")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("transformObjects")); let before = art(&s); for (source, part) in [ - ("app.activeDocument.pathItems[0].translate(1, 2, true, true, false);", "changeFillGradients false"), + ("app.activeDocument.pathItems[0].translate(1, 2, true, false, false);", "transformFillGradients different from transformObjects"), ("app.activeDocument.pathItems[0].rotate(10, true, true, true, false);", "must be the same"), ("app.activeDocument.pathItems.ellipse(10, 10, 5, 5, false, true);", "inscribed"), ( @@ -1782,18 +1815,16 @@ fn path_changes_refuse_paths_on_a_locked_artboard() { let (mut s, a, _) = doc(); s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); let (before, steps) = (art(&s), undo_steps(&s)); - // Points (waiting and written at once), paint, stroke and a transform. - for change in [ - "p.closed = false;", - "p.pathPoints[0].anchor = [1, 2];", - "p.setEntirePath([[0, 0], [10, 10]]);", - "p.filled = false;", - "p.strokeWidth = 7;", - "p.translate(5, 5);", - ] { + // Points (waiting and written at once), paint and stroke. + for change in + ["p.closed = false;", "p.pathPoints[0].anchor = [1, 2];", "p.setEntirePath([[0, 0], [10, 10]]);", "p.filled = false;", "p.strokeWidth = 7;"] + { let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}")); assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}"); } + // A transform is PageItem's, which refuses any object on a locked artboard. + let e = failure(&mut s, "app.activeDocument.pathItems[0].translate(5, 5);"); + assert!(e.contains(&format!("cannot transform objects on a locked artboard: {}", a.0)), "{e}"); let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); assert!(e.contains("cannot delete objects on a locked artboard"), "{e}"); assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps)); diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs new file mode 100644 index 0000000000..edd718ec46 --- /dev/null +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -0,0 +1,662 @@ +//! The script object model: `app.preferences`, the matrix functions of `app` and `app.copy`, +//! `app.cut` and `app.paste`. + +use serde_json::{Value, json}; + +use crate::script::dom::preferences::{MAX_KEYS, MAX_STRING_BYTES, MAX_TOTAL_BYTES, WARNING_OFF_NEEDS_A_PERSON, WARNING_OFF_QUESTION}; +use crate::script::{DialogAnswer, DialogKind, ScriptDialog}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn stored(s: &Session, key: &str) -> Option { + s.prefs.script_preferences.get(key).cloned() +} + +#[test] +fn show_external_jsx_warning_is_the_external_script_warning() { + let mut s = Session::new(); + assert!(s.prefs.show_external_script_warning); + let journal = s.journal.len(); + let out = log( + &mut s, + "var p = app.preferences; vc.log(p.typename); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));\ + vc.log(p.getIntegerPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);", + ); + assert_eq!(out, vec![json!("Preferences"), json!(true), json!(1)]); + // A preference is not a command, so the journal has no entry for the run. + assert_eq!(s.journal.len(), journal); + assert!(s.prefs.script_preferences.is_empty()); + assert!(failure(&mut s, "app.preferences.setIntegerPreference('ShowExternalJSXWarning', 1);").contains("setBooleanPreference")); + // Turned off by the person, a script reads it as off and can turn it back on, or remove it. + s.prefs.show_external_script_warning = false; + let out = log( + &mut s, + "var p = app.preferences; p.setBooleanPreference('ShowExternalJSXWarning', false);\ + vc.log(p.getBooleanPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);", + ); + assert_eq!(out, vec![json!(false)]); + assert!(s.prefs.show_external_script_warning); + s.prefs.show_external_script_warning = false; + log(&mut s, "app.preferences.removePreference('ShowExternalJSXWarning');"); + assert!(s.prefs.show_external_script_warning); +} + +/// A run with nobody to ask cannot turn the warning off, even with a Yes in `answers`. +#[test] +fn a_run_without_a_person_cannot_turn_the_warning_off() { + let mut s = Session::new(); + let off = "app.preferences.setBooleanPreference('ShowExternalJSXWarning', false);"; + assert!(failure(&mut s, off).contains(WARNING_OFF_NEEDS_A_PERSON)); + assert!(s.prefs.show_external_script_warning); + let r = s.execute("script.run", &json!({"source": off, "name": "t.js", "answers": [{"kind": "confirm", "value": true}]})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains(WARNING_OFF_NEEDS_A_PERSON)), "{r:?}"); + assert!(s.prefs.show_external_script_warning); + let caught = log(&mut s, &format!("try {{ {off} }} catch (e) {{ vc.log(e.message); }}")); + assert_eq!(caught, vec![json!(WARNING_OFF_NEEDS_A_PERSON)]); + assert!(s.prefs.show_external_script_warning); +} + +/// A run in the app, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +const ASK_OFF: &str = "var p = app.preferences; var r = p.setBooleanPreference('ShowExternalJSXWarning', false);\ + vc.log([r === undefined, p.getBooleanPreference('ShowExternalJSXWarning')]);"; + +#[test] +fn yes_to_the_confirm_turns_the_warning_off() { + let mut s = Session::new(); + framed(&mut s, ASK_OFF); + let want = ScriptDialog { + kind: DialogKind::Confirm, + message: WARNING_OFF_QUESTION.into(), + title: None, + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + assert_eq!(s.script_dialog(), Some(want)); + assert!(s.script_dialog_turns_warning_off()); + assert!(s.prefs.show_external_script_warning, "nothing changes while the confirm waits"); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, false]])); + assert_eq!(r["dialogs"][0]["answer"], true); + assert!(!s.prefs.show_external_script_warning); +} + +#[test] +fn a_script_confirm_with_the_same_text_is_not_the_warning_question() { + let mut s = Session::new(); + framed(&mut s, &format!("vc.log(confirm({}));", json!(WARNING_OFF_QUESTION))); + assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string())); + assert!(!s.script_dialog_turns_warning_off()); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([true])); +} + +#[test] +fn turning_the_warning_on_after_yes_keeps_it_on() { + let mut s = Session::new(); + framed( + &mut s, + &format!("{ASK_OFF} p.setBooleanPreference('ShowExternalJSXWarning', true); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));"), + ); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, false], true]), "the script sees the answer at once"); + assert!(s.prefs.show_external_script_warning, "the script's last write is what the run keeps"); +} + +#[test] +fn no_to_the_confirm_or_stop_leaves_the_warning_on() { + let mut s = Session::new(); + framed(&mut s, ASK_OFF); + assert!(s.script_answer(DialogAnswer::Confirm(false))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([[true, true]])); + assert!(s.prefs.show_external_script_warning); + framed(&mut s, ASK_OFF); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(!s.script_answer(DialogAnswer::Confirm(true))); + assert!(s.script_pump().unwrap().is_err()); + assert!(s.prefs.show_external_script_warning); + // Yes in a run that then fails is put back with the rest of the run. + framed(&mut s, &format!("{ASK_OFF} throw new Error('stop');")); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert!(pump(&mut s).unwrap().is_err()); + assert!(s.prefs.show_external_script_warning); +} + +/// Asking to show no dialogs does not skip the confirm, and a call from a callback, where no dialog +/// can open, throws. +#[test] +fn the_confirm_cannot_be_skipped() { + let mut s = Session::new(); + framed(&mut s, &format!("try {{ app.userInteractionLevel = 'DONTDISPLAYALERTS'; }} catch (e) {{}} {ASK_OFF}")); + assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string())); + assert!(s.script_answer(DialogAnswer::Confirm(false))); + assert!(pump(&mut s).unwrap().is_ok()); + assert!(s.prefs.show_external_script_warning); + let callback = "[1].forEach(function () { app.preferences.setBooleanPreference('ShowExternalJSXWarning', false); });"; + assert_eq!(run(&mut s, callback).unwrap()["running"], true); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains(WARNING_OFF_NEEDS_A_PERSON), "{e}"); + assert!(s.prefs.show_external_script_warning); +} + +#[test] +fn other_keys_keep_their_type_across_runs_and_a_restart() { + let mut s = Session::new(); + log( + &mut s, + "var p = app.preferences; p.setBooleanPreference('my/flag', true); p.setIntegerPreference('count', -7);\ + p.setRealPreference('ratio', 0.25); p.setStringPreference('name', 'Ünïcode \\u2713');", + ); + assert_eq!(stored(&s, "my/flag"), Some(ScriptPreference::Boolean(true))); + assert_eq!(stored(&s, "count"), Some(ScriptPreference::Integer(-7))); + assert_eq!(stored(&s, "ratio"), Some(ScriptPreference::Real(0.25))); + assert_eq!(stored(&s, "name"), Some(ScriptPreference::String("Ünïcode \u{2713}".into()))); + // The preferences as the app saves them, read into a new session. + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut t = Session::new(); + t.prefs = serde_json::from_str(&saved).unwrap(); + let out = log( + &mut t, + "var p = app.preferences; vc.log(p.getBooleanPreference('my/flag')); vc.log(p.getIntegerPreference('count'));\ + vc.log(p.getRealPreference('ratio')); vc.log(p.getStringPreference('name'));", + ); + assert_eq!(out, vec![json!(true), json!(-7), json!(0.25), json!("Ünïcode \u{2713}")]); +} + +#[test] +fn missing_keys_read_as_empty_values_and_getters_convert() { + let mut s = Session::new(); + let mut out = log( + &mut s, + "var p = app.preferences; vc.log([p.getBooleanPreference('none'), p.getIntegerPreference('none'),\ + p.getRealPreference('none'), p.getStringPreference('none')]);\ + p.setRealPreference('r', -2.75); p.setStringPreference('t', ' 12.5 '); p.setStringPreference('x', 'abc');\ + p.setBooleanPreference('b', true); p.setIntegerPreference('i', 0);\ + vc.log([p.getIntegerPreference('r'), p.getStringPreference('r'), p.getBooleanPreference('r')]);\ + vc.log([p.getRealPreference('t'), p.getIntegerPreference('t'), p.getBooleanPreference('t')]);\ + vc.log([isNaN(p.getRealPreference('x')), p.getIntegerPreference('x')]);\ + vc.log([p.getStringPreference('b'), p.getRealPreference('b'), p.getBooleanPreference('i'), p.getStringPreference('i')]);\ + var n = []; ['0x10', '0B101', '0o17', '-0x10', '0x', ' -Infinity ', '1e3', '.5', 'inf', '1_0'].forEach(function (t) {\ + p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));\ + p.setStringPreference('n', '0x200000000000018'); var r = [p.getRealPreference('n') === Math.pow(2, 57) + 32];\ + p.setStringPreference('n', '0x' + new Array(301).join('f')); r.push(String(p.getRealPreference('n')));\ + p.setStringPreference('n', '0b' + new Array(60).join('0') + '1' + new Array(53).join('0') + '1'); r.push(p.getRealPreference('n') === Math.pow(2, 53));\ + vc.log(r);", + ); + // Each whole number in base 16, 8 or 2 is rounded once: 2^57 + 24 to 2^57 + 32, 1,200 bits to + // Infinity, and 2^53 + 1 after leading zeros to 2^53 (ties to even). + assert_eq!(out.pop(), Some(json!([true, "Infinity", true]))); + assert_eq!(out.pop(), Some(json!("16 5 15 NaN NaN -Infinity 1000 0.5 NaN NaN"))); + assert_eq!( + out, + vec![json!([false, 0, 0, ""]), json!([-2, "-2.75", true]), json!([12.5, 12, true]), json!([true, 0]), json!(["true", 1, false, "0"])] + ); +} + +#[test] +fn text_reads_trim_javascript_whitespace_only() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = app.preferences; var r = [];\ + ['\\u0085' + '42', '\\ufeff 42\\u00a0', '\\u2028' + '42\\u3000'].forEach(function (t) {\ + p.setStringPreference('n', t); r.push(String(p.getRealPreference('n'))); }); vc.log(r.join(' '));", + ); + assert_eq!(out, vec![json!("NaN 42 42")]); +} + +#[test] +fn a_real_preference_changes_between_zero_and_negative_zero() { + let mut s = Session::new(); + log(&mut s, "app.preferences.setRealPreference('z', -0);"); + let out = log( + &mut s, + "var p = app.preferences; vc.log(String(1 / p.getRealPreference('z'))); p.setRealPreference('z', 0); vc.log(String(1 / p.getRealPreference('z')));", + ); + assert_eq!(out, vec![json!("-Infinity"), json!("Infinity")]); + // The change is kept when the run's keys are merged with the app's. + assert_eq!(stored(&s, "z").map(|v| matches!(v, ScriptPreference::Real(r) if r.to_bits() == 0)), Some(true)); +} + +#[test] +fn bad_arguments_throw_and_store_nothing() { + let mut s = Session::new(); + let mut wrong = Vec::new(); + for (source, message) in [ + ("app.preferences.setIntegerPreference('k', 1.5);", "whole number"), + ("app.preferences.setIntegerPreference('k', 1e300);", "whole number"), + ("app.preferences.setIntegerPreference('k', '3');", "whole number"), + ("app.preferences.setRealPreference('k', Infinity);", "finite number"), + ("app.preferences.setRealPreference('k', NaN);", "finite number"), + ("app.preferences.setBooleanPreference('k', 1);", "true or false"), + ("app.preferences.setStringPreference('k', 5);", "a string"), + ("app.preferences.setStringPreference(5, 'v');", "key must be a string"), + ("app.preferences.getBooleanPreference();", "key must be a string"), + ("app.preferences.setStringPreference('', 'v');", "1 to 256"), + ("app.preferences.setStringPreference(new Array(258).join('k'), 'v');", "1 to 256"), + // 129 characters outside the Basic Multilingual Plane are 258 UTF-16 code units. + ("app.preferences.setStringPreference(new Array(130).join('\\uD83D\\uDE00'), 'v');", "1 to 256"), + ("app.preferences.setStringPreference('a\\u0000b', 'v');", "control characters"), + ("app.preferences.setStringPreference('k', new Array(65538).join('v'));", "at most 65536 bytes"), + ("var f = app.preferences.getBooleanPreference; f.call({}, 'k');", "not a Preferences"), + ("Preferences.prototype.setBooleanPreference('k', true);", "not a Preferences"), + ] { + match run(&mut s, source) { + Err(e) if e.to_string().contains(message) => {} + r => wrong.push(format!("{source}: {r:?}")), + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + assert!(s.prefs.script_preferences.is_empty()); + // A key of exactly 256 code units and a value of exactly the limit are taken. + log(&mut s, "app.preferences.setStringPreference(new Array(257).join('k'), new Array(65537).join('v'));"); + assert_eq!(stored(&s, &"k".repeat(256)), Some(ScriptPreference::String("v".repeat(MAX_STRING_BYTES)))); + log(&mut s, "app.preferences.setStringPreference(new Array(129).join('\\uD83D\\uDE00'), 'v');"); + assert_eq!(stored(&s, &"\u{1F600}".repeat(128)), Some(ScriptPreference::String("v".into()))); +} + +#[test] +fn the_store_limits_its_keys() { + let mut s = Session::new(); + for i in 0..MAX_KEYS { + s.prefs.script_preferences.insert(format!("k{i}"), ScriptPreference::Integer(1)); + } + assert!(failure(&mut s, "app.preferences.setIntegerPreference('one more', 1);").contains("at most 4096 keys")); + assert_eq!(s.prefs.script_preferences.len(), MAX_KEYS); + // A key already stored can still change. + log(&mut s, "app.preferences.setIntegerPreference('k0', 2);"); + assert_eq!(stored(&s, "k0"), Some(ScriptPreference::Integer(2))); +} + +#[test] +fn the_store_limits_its_bytes() { + let mut s = Session::new(); + let big = "v".repeat(MAX_STRING_BYTES); + for i in 0..MAX_TOTAL_BYTES / MAX_STRING_BYTES - 1 { + s.prefs.script_preferences.insert(format!("{i:02}"), ScriptPreference::String(big.clone())); + } + let e = failure(&mut s, "app.preferences.setStringPreference('last', new Array(65537).join('v'));"); + assert!(e.contains("at most 1048576 bytes"), "{e}"); + assert_eq!(stored(&s, "last"), None); + // Replacing a stored value counts the new value instead of the old one. + log(&mut s, "app.preferences.setStringPreference('00', new Array(65537).join('w'));"); + assert_eq!(stored(&s, "00"), Some(ScriptPreference::String("w".repeat(MAX_STRING_BYTES)))); +} + +#[test] +fn a_failed_run_puts_the_store_back_and_removing_the_last_key_empties_it() { + let mut s = Session::new(); + log(&mut s, "app.preferences.setIntegerPreference('keep', 1);"); + let e = failure(&mut s, "app.preferences.setIntegerPreference('keep', 2); app.preferences.setRealPreference('new', 1); throw new Error('stop');"); + assert!(e.contains("stop")); + assert_eq!(stored(&s, "keep"), Some(ScriptPreference::Integer(1))); + assert_eq!(stored(&s, "new"), None); + let out = log( + &mut s, + "var p = app.preferences; p.removePreference('missing'); p.removePreference('keep');\ + vc.log(p.getIntegerPreference('keep'));", + ); + assert_eq!(out, vec![json!(0)]); + assert!(s.prefs.script_preferences.is_empty()); +} + +#[test] +fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() { + let mut s = Session::new(); + s.prefs.script_preferences.insert("gone".into(), ScriptPreference::Integer(1)); + s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(1)); + s.script_frames = true; + let source = "var p = app.preferences; p.removePreference('gone'); p.setIntegerPreference('mine', 2);\ + for (var i = 0; i < 2000000; i++) {}"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert!(s.script_running()); + s.prefs.script_preferences.insert("theirs".into(), ScriptPreference::Boolean(true)); + s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(3)); + while s.script_pump().is_none() {} + let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect(); + assert_eq!( + keys, + vec![("kept", &ScriptPreference::Integer(3)), ("mine", &ScriptPreference::Integer(2)), ("theirs", &ScriptPreference::Boolean(true))] + ); +} + +#[test] +fn matrix_functions_give_new_records() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.typename, m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + vc.log(v(app.getIdentityMatrix())); vc.log(v(app.getTranslationMatrix(100, 200))); vc.log(v(app.getTranslationMatrix()));\ + vc.log(v(app.getScaleMatrix(60))); vc.log(v(app.getScaleMatrix(50, 200))); vc.log(v(app.getScaleMatrix()));\ + vc.log(v(app.getRotationMatrix(90))); vc.log(v(app.getRotationMatrix(-270))); vc.log(v(app.getRotationMatrix()));", + ); + assert_eq!( + out, + vec![ + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 100, 200]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 0.6, 0, 0, 0.6, 0, 0]), + json!(["Matrix", 0.5, 0, 0, 2, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 0, 1, -1, 0, 0, 0]), + json!(["Matrix", 0, 1, -1, 0, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + ] + ); + let r = log(&mut s, "var m = app.getRotationMatrix(30); vc.log([m.mValueA, m.mValueB, m.mValueC, m.mValueD]);"); + let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + assert_eq!(r, vec![json!([c, sn, -sn, c])]); +} + +#[test] +fn concatenation_applies_the_first_matrix_first() { + let mut s = Session::new(); + // As PDF `cm` operators compose (ISO 32000-1, 8.3.4): [x y 1] × M × N. + // M = [2 0 0 3 5 7] then N = [0 1 -1 0 10 20]: (x, y) → (2x + 5, 3y + 7) → (-(3y + 7) + 10, 2x + 5 + 20). + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + var m = {mValueA: 2, mValueB: 0, mValueC: 0, mValueD: 3, mValueTX: 5, mValueTY: 7};\ + var n = {mValueA: 0, mValueB: 1, mValueC: -1, mValueD: 0, mValueTX: 10, mValueTY: 20};\ + var c = app.concatenateMatrix(m, n); vc.log(v(c)); vc.log(v(m)); vc.log(c === m);\ + vc.log(v(app.concatenateTranslationMatrix(m, 1, 2))); vc.log(v(app.concatenateScaleMatrix(m, 50)));\ + vc.log(v(app.concatenateRotationMatrix(m, 90)));\ + vc.log(app.isEqualMatrix(app.concatenateRotationMatrix(m, 90), app.concatenateMatrix(m, app.getRotationMatrix(90))));", + ); + assert_eq!( + out, + vec![ + json!([0, 2, -3, 0, 3, 25]), + json!([2, 0, 0, 3, 5, 7]), + json!(false), + json!([2, 0, 0, 3, 6, 9]), + json!([1, 0, 0, 1.5, 2.5, 3.5]), + json!([0, 2, -3, 0, -7, 5]), + json!(true), + ] + ); +} + +#[test] +fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_number() { + let mut s = Session::new(); + // N·(1 - 2^-53) is N - S/2, which rounds up to N; the exact A is -1.5·S, which rounds to -2·S. + // MAX - 2^969 + 2^970 rounds to MAX, while adding the rounded MAX - 2^969 and 2^970 overflows. + // MAX·(1 - 2^-53) + 2^971 + 2^970 - 2^917 is past the overflow midpoint by 2^917, which rounding + // the first product drops. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var n = Math.pow(2, -1022), s = Number.MIN_VALUE;\ + vc.log(app.concatenateMatrix(mat([n, n + s, 0, 1, 0, 0]), mat([1 - Math.pow(2, -53), 0, -1, 1, 0, 0])).mValueA === -2 * s);\ + vc.log(app.concatenateMatrix(mat([n, 0, 0, 1, 0, 0]), mat([1, 0, 0, 1, 0, 0])).mValueA === n);\ + var shift = mat([1, 0, -1, 1, Math.pow(2, 970), 0]);\ + vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 969)]), shift).mValueTX === Number.MAX_VALUE);\ + try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), shift); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + var near = mat([1 - Math.pow(2, -53), 0, 1, 1, Math.pow(2, 970) - Math.pow(2, 917), 0]);\ + try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 971)]), near); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }", + ); + assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError"), json!("RangeError")]); +} + +#[test] +fn concatenation_keeps_a_small_translation_that_a_large_one_cancels() { + let mut s = Session::new(); + // 2^53 + 1 rounds to 2^53, so adding the rounded products and then -2^53 gives 0; the exact X is 1. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var big = Math.pow(2, 53);\ + vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, big, 1]), mat([1, 0, 1, 1, -big, 0])).mValueTX);", + ); + assert_eq!(out, vec![json!(1)]); +} + +#[test] +fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_number() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var x = Math.pow(2, 600), y = Math.pow(2, -500), z = Math.pow(2, -575);\ + var c = app.concatenateMatrix(mat([x, x, 0, 1, x, x]), mat([x, 0, -x, 1, 0, 0]));\ + vc.log([c.mValueA, c.mValueB === x, c.mValueC === -x, c.mValueD, c.mValueTX, c.mValueTY === x]);\ + vc.log(app.concatenateMatrix(mat([y, y, 0, 1, 0, 0]), mat([z, 0, z, 1, 0, 0])).mValueA === Number.MIN_VALUE);\ + var p = 2.0543170765449965e-57, q = 6.201533916984909e-252;\ + vc.log(app.concatenateMatrix(mat([p, 0, 0, 1, 0, 0]), mat([q, 0, 0, 1, 0, 0])).mValueA === p * q);\ + vc.log(v(app.concatenateMatrix(mat([-2, 0, 0, -3, 0, 0]), mat([0, 1, -1, 0, 0, 0]))));\ + var big = mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), up = 1 + Math.pow(2, -52);\ + try { app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 971), 0])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + vc.log(app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 972), 0])).mValueTX === Number.MAX_VALUE);\ + var h = Math.pow(2, 500), far = mat([1, 0, 0, 1, Math.pow(2, 600), -Math.pow(2, 600)]);\ + vc.log(app.concatenateMatrix(far, mat([h, 0, h, 1, 1, 0])).mValueTX);\ + var g = Math.pow(2, 100), farther = mat([1, 0, 0, 1, Math.pow(2, 1000), -Math.pow(2, 1000)]);\ + vc.log(app.concatenateMatrix(farther, mat([g, 0, g, 1, Math.pow(2, -100), 0])).mValueTX === Math.pow(2, -100));\ + var tiny = mat([1, 0, 0, 1, y, 0]);\ + vc.log(app.concatenateMatrix(tiny, mat([z, 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);\ + var least = mat([1, 0, 0, 1, Number.MIN_VALUE, 0]);\ + vc.log(app.concatenateMatrix(least, mat([0.5 - Math.pow(2, -54), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === Number.MIN_VALUE);\ + vc.log(app.concatenateMatrix(least, mat([0.5 + Math.pow(2, -53), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);", + ); + assert_eq!( + out, + vec![ + json!([0, true, true, 1, 0, true]), + json!(true), + json!(true), + json!([0, -2, 3, 0, 0, 0]), + json!("RangeError"), + json!(true), + json!(1), + json!(true), + json!(true), + json!(true), + json!(true) + ] + ); +} + +#[test] +fn a_concatenated_translation_next_to_the_largest_number_is_rounded_once() { + let mut s = Session::new(); + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var a = Math.pow(2, 969), b = Math.pow(2, 970);\ + function tx(f, t) { try { return app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, f]), mat([1, 0, 1, 1, t, 0])).mValueTX === Number.MAX_VALUE; }\ + catch (e) { return e.name; } }\ + vc.log(tx(-a, b)); vc.log(tx(a, a));", + ); + // MAX + 2^969 is below the halfway point to 2^1024, and MAX + 2^970 is that point, which rounds + // to 2^1024. + assert_eq!(out, vec![json!(true), json!("RangeError")]); +} + +#[test] +fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD]; }\ + var m = app.getRotationMatrix(-89.99999999999999); vc.log(m.mValueA > 0); vc.log(m.mValueB);\ + vc.log(v(app.getRotationMatrix(-90))); vc.log(v(app.getRotationMatrix(-180))); vc.log(v(app.getRotationMatrix(-450)));", + ); + assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]); +} + +#[test] +fn inverse_singular_and_equal_matrices() { + let mut s = Session::new(); + let out = log( + &mut s, + "var m = app.concatenateTranslationMatrix(app.concatenateRotationMatrix(app.getScaleMatrix(40, 250), 33), 17, -4);\ + var i = app.invertMatrix(m), back = app.concatenateMatrix(m, i), id = app.getIdentityMatrix();\ + var d = [back.mValueA - 1, back.mValueB, back.mValueC, back.mValueD - 1, back.mValueTX, back.mValueTY];\ + vc.log(Math.max.apply(null, d.map(Math.abs)) < 1e-12);\ + vc.log(app.isSingularMatrix(app.getScaleMatrix(0, 100))); vc.log(app.isSingularMatrix(m));\ + vc.log(app.isEqualMatrix(id, app.getRotationMatrix(360))); vc.log(app.isEqualMatrix(id, app.getTranslationMatrix(0, 1e-300)));\ + var tiny = app.getScaleMatrix(1e-198, 1e202), t = app.invertMatrix(tiny);\ + function near(v, w) { return Math.abs(v / w - 1) < 1e-12; }\ + vc.log([app.isSingularMatrix(tiny), near(t.mValueA, 1e200), near(t.mValueD, 1e-200), t.mValueB, t.mValueC]);\ + vc.log(near(app.invertMatrix(app.getScaleMatrix(1e202)).mValueA, 1e-200));\ + function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: 0, mValueTY: 0}; }\ + var wide = mat([1e308, 0, 1e308, 1e-100]), w = app.invertMatrix(wide);\ + vc.log([app.isSingularMatrix(wide), near(w.mValueA, 1e-308), near(w.mValueC, -1e100), near(w.mValueD, 1e100)]);\ + var thin = app.invertMatrix(mat([1e300, 0, 1e300, 5e-24]));\ + vc.log([near(thin.mValueA, 1e-300), near(thin.mValueC, -2e23), near(thin.mValueD, 2e23)]);\ + var close = mat([7207, 7440, 382, 394.34993756070486]), ci = app.invertMatrix(close);\ + vc.log([app.isSingularMatrix(close), app.isSingularMatrix(mat([6, 4, 3, 2])), near(ci.mValueD, 7207 / -8.009237717487849e-11)]);\ + var far = mat([1e-100, 1e-100, 1e-100, 1e-100 + 1e-115]); far.mValueTX = 1e200; far.mValueTY = 1e200;\ + var fi = app.invertMatrix(far); vc.log([Math.abs(fi.mValueTX / -1e300 - 1) < 1e-6, fi.mValueTY]);", + ); + assert_eq!(out[..5], [json!(true), json!(true), json!(false), json!(true), json!(false)]); + assert_eq!(out[5], json!([false, true, true, 0, 0])); + assert_eq!(out[6], json!(true)); + assert_eq!(out[7], json!([false, true, true, true])); + assert_eq!(out[8], json!([true, true, true])); + assert_eq!(out[9], json!([false, true, true])); + assert_eq!(out[10], json!([true, 0])); + let mut wrong = Vec::new(); + for (source, message) in [ + ("app.invertMatrix(app.getScaleMatrix(100, 0));", "singular"), + ("app.getTranslationMatrix(NaN);", "not a finite number"), + ("app.getScaleMatrix('50');", "scaleX must be a finite number"), + ("app.getRotationMatrix(Infinity);", "not a finite number"), + ("app.getRotationMatrix(null);", "angle must be a finite number"), + ("app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1});", "secondMatrix must be a Matrix"), + ( + "app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: '0', mValueTY: 0});", + "secondMatrix must be a Matrix", + ), + ("app.invertMatrix(5);", "matrix must be a Matrix"), + ("var m = app.getIdentityMatrix(); m.mValueTX = Infinity; app.isSingularMatrix(m);", "not a finite number"), + ("app.concatenateScaleMatrix(app.getScaleMatrix(1e300), 1e300);", "too large"), + ] { + match run(&mut s, source) { + Err(e) if e.to_string().contains(message) => {} + r => wrong.push(format!("{source}: {r:?}")), + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn copy_and_paste_run_as_one_undo_step() { + let mut s = Session::new(); + assert!(failure(&mut s, "app.paste();").contains("No active document")); + log(&mut s, "app.copy(); app.cut();"); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + // Nothing selected and the clipboard empty: nothing happens and no step is added. + log(&mut s, "app.copy(); app.cut(); app.paste();"); + assert_eq!(s.active().unwrap().history.undo.len(), steps); + assert!(s.clipboard.is_empty()); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + let out = log(&mut s, "app.copy(); app.paste(); app.paste(); vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!(3)]); + assert_eq!(s.active().unwrap().history.undo.len(), steps + 1); + // A cut in a run that fails is put back. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + assert!(failure(&mut s, "app.cut(); throw new Error('stop');").contains("stop")); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_some()); + assert_eq!(s.active().unwrap().history.undo.len(), steps); + log(&mut s, "app.cut();"); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_none()); +} + +#[test] +fn only_copies_that_fill_the_clipboard_and_are_kept_are_counted() { + let mut s = Session::new(); + s.clipboard_copied = true; + s.note_copy(); + assert_eq!(s.copies, 0); + assert!(!s.clipboard_copied); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + assert_eq!(s.copies, 1); + assert!(s.clipboard_copied); + // A batch that copies and then fails puts the count back with the clipboard. + s.execute("clipboard.importSvg", &json!({"svg": ""})).unwrap(); + assert!(!s.clipboard_copied); + let batch = json!({"commands": [{"command": "edit.copy", "params": {}}, {"command": "no.such", "params": {}}]}); + assert!(s.execute("command.batch", &batch).is_err()); + assert_eq!(s.copies, 1); + assert!(!s.clipboard_copied); +} + +#[test] +fn a_copy_or_cut_the_run_puts_back_is_not_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + // The clipboard holds a copy from before the run. + s.execute("edit.copy", &json!({})).unwrap(); + let copies = s.copies; + // No command result reaches the script, so each command below is put back. + crate::script::TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + "try { vc.run('command.batch', {commands: [{command: 'edit.copy', params: {}}]}); } catch (e) { vc.log(e.name); }\ + try { vc.run('edit.cut'); } catch (e) { vc.log(e.name); }\ + try { vc.run('edit.copy'); } catch (e) { vc.log(e.name); }\ + try { vc.run('artboard.copy', {indices: [0]}); } catch (e) { vc.log(e.name); }\ + try { vc.run('clipboard.importSvg', {svg: ''}); }\ + catch (e) { vc.log(e.name); }", + ); + crate::script::TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", "RangeError", "RangeError"]), "{r}"); + assert_eq!(r.get("copied"), None, "{r}"); + assert_eq!(s.copies, copies); + assert!(s.clipboard_copied); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_some()); +} diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs new file mode 100644 index 0000000000..d57d4570d5 --- /dev/null +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -0,0 +1,341 @@ +//! The script object model: a page item's `translate`, `rotate`, `resize` and `transform`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with a 30 × 40 pt rectangle above a 50 × 50 pt one, so that `pageItems` +/// (topmost first) lists the 30 × 40 pt one first. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The numbers of a logged array, or a logged number as one. +fn numbers(v: &Value) -> Vec { + match v.as_array() { + Some(a) => a.iter().map(|n| n.as_f64().unwrap()).collect(), + None => vec![v.as_f64().unwrap()], + } +} + +fn close(a: &[f64], b: &[f64]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6) +} + +#[test] +fn translate_moves_by_the_offsets_with_y_up_in_one_undo_step() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; var l = i.left, t = i.top;\ + i.translate(10, 0); vc.log([i.left - l, i.top - t]);\ + i.translate(0, 10); vc.log([i.left - l, i.top - t]);\ + app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var t2 = i.top;\ + i.translate(0, 5); vc.log(i.top - t2);", + ); + assert!(close(&numbers(&out[0]), &[10.0, 0.0]), "{out:?}"); + assert!(close(&numbers(&out[1]), &[10.0, 10.0]), "{out:?}"); + // With Y down from the artboard's top, a move up reads as a smaller top. + assert!(close(&numbers(&out[2]), &[-5.0]), "{out:?}"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.active().unwrap().doc.bounds_of(&[a], false).unwrap(); + assert!(close(&[r.x0, r.y0], &[10.0, 20.0]), "{r:?}"); +} + +#[test] +fn rotate_turns_counterclockwise_about_the_center_or_the_named_point() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], r = g.geometricBounds; vc.log(g.typename);\ + vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);\ + g.rotate(90); r = g.geometricBounds; vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);", + ); + assert_eq!(out[0], json!("GroupItem")); + let (before, after) = (numbers(&out[1]), numbers(&out[2])); + // The width and height trade places, and the center stays. + assert!(close(&after, &[before[1], before[0], before[2], before[3]]), "{before:?} {after:?}"); + + // A positive angle about the bottom-left corner swings a rectangle to the left of that corner. + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; vc.log(i.geometricBounds);\ + i.rotate(90, true, true, true, true, Transformation.BOTTOMLEFT); vc.log(i.geometricBounds);", + ); + let (b0, b1) = (numbers(&out[0]), numbers(&out[1])); + // [left, top, right, bottom], Y up: the 30 pt wide side now stands up, and the 40 pt tall side + // lies to the left. + assert!(close(&b1, &[b0[0] - 40.0, b0[3] + 30.0, b0[0], b0[3]]), "{b0:?} {b1:?}"); +} + +#[test] +fn resize_scales_about_the_center_and_line_widths_follow_their_argument() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, i = p[0], j = p[1];\ + function stroke(o) { return (o.visibleBounds[2] - o.visibleBounds[0]) - o.width; }\ + var r = i.geometricBounds, s0 = stroke(i); i.resize(50, 50); var q = i.geometricBounds;\ + vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3]), stroke(i) - s0]);\ + var s1 = stroke(j); j.resize(50, 50, true, true, true, true, 50); vc.log([s0, stroke(j) / s1]);", + ); + let first = numbers(&out[0]); + assert!(close(&first, &[15.0, 20.0, 0.0, 0.0, 0.0]), "{first:?}"); + let second = numbers(&out[1]); + assert!(second[0] > 0.0, "the rectangles have a stroke: {second:?}"); + assert!(close(&second[1..], &[0.5]), "{second:?}"); + // On a path, any other line width sets the stroke weight to that percent of what it was. + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], w = i.strokeWidth; i.resize(50, 50, true, true, true, true, 70); vc.log(i.strokeWidth / w);", + ); + assert!(close(&numbers(&out[0]), &[0.7]), "{out:?}"); + // On a group, a line width that is neither 100 nor the scale itself is refused. + s.execute("select.all", &json!({})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(50, 50, true, true, true, true, 70);"); + assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}"); +} + +#[test] +fn transform_applies_a_matrix_record_about_the_center() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], r = i.geometricBounds;\ + i.transform(app.getRotationMatrix(45)); var q = i.geometricBounds;\ + vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3])]);\ + var l = i.left; i.transform(app.getTranslationMatrix(5, 0)); vc.log(i.left - l);", + ); + let side = 70.0 / 2f64.sqrt(); + assert!(close(&numbers(&out[0]), &[side, side, 0.0, 0.0]), "{out:?}"); + assert!(close(&numbers(&out[1]), &[5.0]), "{out:?}"); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn transforms_that_change_nothing_add_no_undo_step() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + log( + &mut s, + "var i = app.activeDocument.pageItems[0]; i.translate(); i.translate(0, 0); i.rotate(0); i.rotate(360);\ + i.resize(100, 100); i.transform(app.getIdentityMatrix()); i.translate(10, 0, false, false, false, false);\ + i.translate(7000000, 0, false, false, false, false);\ + i.transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 100);", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn a_scale_whose_square_is_too_large_for_a_number_keeps_its_own_line_width() { + let (mut s, _, _) = doc(); + let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 70);"; + let e = failure(&mut s, call); + assert!(e.contains("other than 100 or the scale itself"), "{e}"); +} + +#[test] +fn a_line_width_of_zero_is_not_the_scale_itself_however_small_the_scale() { + let (mut s, _, _) = doc(); + let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 0);"; + let e = failure(&mut s, call); + assert!(e.contains("other than 100 or the scale itself"), "{e}"); + // A positive request still matches a tiny scale of its own. + log(&mut s, "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 1e-10);"); +} + +#[test] +fn an_offset_past_the_canvas_is_taken_when_the_call_moves_nothing() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.clone(); + log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, false, false, false);"); + // The object uses no pattern, so moving patterns moves nothing either. + log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, true, false, true);"); + assert_eq!(*s.active().unwrap().doc, *before); + let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(Infinity, 0, false, false, false, false);"); + assert!(e.contains("finite number"), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0);"); + assert!(e.contains("outside the canvas"), "{e}"); +} + +#[test] +fn a_move_too_small_to_round_away_moves_the_object() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0], l = i.left; i.translate(5e-13, 0); vc.log(i.left > l);"); + assert_eq!(out, vec![json!(true)]); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn a_tiny_move_about_a_distant_center_moves_the_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The center is at x = 100, where 1e-15 rounds away; the left edge at 0 keeps it. + rect(&mut s, 0.0, 0.0, 200.0, 10.0); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], l = i.left;\ + i.transform({mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: 1e-15, mValueTY: 0}); vc.log(i.left > l);", + ); + assert_eq!(out, vec![json!(true)]); +} + +#[test] +fn a_scale_and_translation_about_the_center_straddle_the_origin() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 127, "y1": 0, "x2": 129, "y2": 0})).unwrap()["id"].as_u64().unwrap()); + log( + &mut s, + "app.activeDocument.pageItems[0].transform({mValueA: Math.pow(2, -55), mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: -128, mValueTY: 0});", + ); + let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap(); + assert!(r.x0 < 0.0 && r.x1 > 0.0, "{r:?}"); +} + +#[test] +fn a_clipped_object_moved_past_the_canvas_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let far = rect(&mut s, 0.9 * crate::MAX_COORD, 0.0, 10.0, 10.0); + let mask = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [far.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].translate({}, 0);", 0.2 * crate::MAX_COORD)); + assert!(e.contains("past the canvas"), "{e}"); + assert_eq!(s.active().unwrap().doc.node(far), before.node(far)); +} + +#[test] +fn a_transformation_whose_bounds_reach_past_the_canvas_is_kept_when_the_art_does_not() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // A diagonal line through the origin, 0.6 of the canvas limit out each way. + let a = 0.6 * crate::MAX_COORD; + let line = NodeId(s.execute("shape.line", &json!({"x1": -a, "y1": a, "x2": a, "y2": -a})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + // On the page (Y down), x' = x + y about the center: the line becomes upright at x = 0, while + // a corner of its bounds would go to 1.2 times the limit. + log( + &mut s, + "var m = {mValueA: 1, mValueB: 0, mValueC: -1, mValueD: 1, mValueTX: 0, mValueTY: 0};\ + app.activeDocument.pageItems[0].transform(m);", + ); + let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap(); + assert!(r.width() < 1e-6 && (r.height() - 2.0 * a).abs() < 1e-3, "{r:?}"); + // The same shear twice takes the line itself past the canvas. + let e = failure( + &mut s, + "var m = {mValueA: 1, mValueB: 0, mValueC: -2, mValueD: 1, mValueTX: 0, mValueTY: 0};\ + app.activeDocument.pageItems[0].transform(m);", + ); + assert!(e.contains("past the canvas"), "{e}"); +} + +#[test] +fn locked_art_and_art_on_a_locked_artboard_are_refused() { + let (mut s, a, b) = doc(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["translate(5, 0)", "rotate(30)", "resize(50, 50)", "transform(app.getScaleMatrix(200))"] { + let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0]; i.locked = true; i.{call};")); + assert!(e.contains(&format!("cannot transform locked objects: {}", a.0)), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.clone(), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(5, 0);"); + assert!(e.contains("cannot transform locked objects"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[1].rotate(45);"); + assert!(e.contains("cannot transform objects on a locked artboard"), "{e}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn bad_arguments_throw_and_change_nothing() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for (call, says) in [ + ("rotate('x')", "angle must be a finite number"), + ("rotate()", "angle must be a finite number"), + ("resize(50)", "scaleY must be a finite number"), + ("resize(0, 50)", "must not be 0"), + ("resize(50, 50, true, true, true, true, -1)", "changeLineWidths must not be negative"), + ("transform({})", "transformationMatrix must be a Matrix"), + ("transform(app.getScaleMatrix(0))", "singular"), + ("translate(1, 0, 'yes')", "transformObjects must be true or false"), + ("translate(7000000, 0)", "past the canvas"), + ("translate('x')", "deltaX must be a finite number"), + ("translate(NaN)", "is not a finite number"), + ("rotate(5, true, false, false)", "changeFillGradients different from changePositions"), + ("rotate(5, true, true, true, false)", "changeFillPatterns and changeStrokePattern"), + // Left out, the stroke pattern follows the Transform Pattern Tiles preference (off), and + // gradients default to true. + ("rotate(5, true, true)", "changeFillPatterns and changeStrokePattern"), + ("translate(10, 0, false)", "transformFillGradients different from transformObjects"), + ("rotate(5, true, true, true, true, 'Transformation.NOPE')", "Transformation value"), + ("rotate(5, true, true, true, true, 3)", "Transformation value"), + ("resize(1e9, 1e9)", "past the canvas"), + // Stroke weights cannot scale while the object stays where it is. + ("resize(50, 50, false, false, false, false, 50)", "with changePositions false is not available yet"), + ] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains(says), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A deleted object is stale before its arguments are used. + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.rotate(10);"); + assert!(e.contains("Stale page item"), "{e}"); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b68abca0a2..8cf9f4bc81 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,11 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Preferences.prototype.setBooleanPreference", "app.preferences.setBooleanPreference(k, true);", "preferences"), + ("Preferences.prototype.setIntegerPreference", "app.preferences.setIntegerPreference(k, 1);", "preferences"), + ("Preferences.prototype.setRealPreference", "app.preferences.setRealPreference(k, 0.5);", "preferences"), + ("Preferences.prototype.setStringPreference", "app.preferences.setStringPreference(k, s);", "preferences"), + ("Preferences.prototype.removePreference", "app.preferences.removePreference(k);", "preferences"), ("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"), ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"), @@ -51,7 +56,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// the open documents; `Document.close` closes a document, and saves it to its own file only when it /// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and /// `Document.path` only name its file and folder. `app.open` reads the file it is given, and -/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. +/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a +/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut` +/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit › +/// Copy does. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), ("Window.", "alert confirm length prompt prototype"), @@ -92,17 +100,22 @@ const INSIDE: &[(&str, &str)] = &[ CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement GroupItem \ GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PlacedItem \ - PlacedItems PluginItem PointType PolarityValues RasterItem RasterItems RulerUnits ScreenMode selection selection= \ - StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod", + PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \ + selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ - executeMenuCommand getIsFileOpen loadAction loadAction= open PPDFileList printPresetsList printerList redo redraw \ - selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \ + "activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \ + concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \ + executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \ + invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \ + printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \ + userInteractionLevel \ userInteractionLevel=", ), + ("Preferences.", "prototype"), + ("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"), ("DocumentPreset.", "prototype"), ( "DocumentPreset.prototype.", @@ -173,8 +186,8 @@ const INSIDE: &[(&str, &str)] = &[ "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \ left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ - transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \ + typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("PlacedItems.", "prototype"), @@ -217,10 +230,10 @@ const INSIDE: &[(&str, &str)] = &[ ( "PathItem.prototype.", "area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \ - filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \ + filled= guides guides= length pathPoints polarity polarity= resolution resolution= selectedPathPoints \ setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \ strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \ - strokeWidth strokeWidth= stroked stroked= translate", + strokeWidth strokeWidth= stroked stroked=", ), ("PathPoints.", "prototype"), ("PathPoints.prototype.", "add constructor index length parent removeAll toString typename"), diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index 0358acac90..fea760b548 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -118,6 +118,14 @@ pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { /// filled shape doesn't touch it, so a marquee drawn over a background picks only what is on it /// (#1103). pub fn intersects_rect(path: &PathData, r: Rect) -> bool { + // The control box holds every anchor and segment, and the path keeps it measured, so a path + // whose control box lies wholly apart from the rect misses it without measuring its segments. + // The test is strict: a control box that only touches the rect, or has no area, goes on to the + // exact checks below. + let (Some(c), n) = (path.control_bounds(), r.abs()) else { return false }; + if c.x1 < n.x0 || n.x1 < c.x0 || c.y1 < n.y0 || n.y1 < c.y0 { + return false; + } let Some(b) = path.bounds() else { return false }; let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0; if b.intersect(r).area() <= 0.0 && !degenerate(b) && !degenerate(r) { @@ -238,6 +246,30 @@ mod tests { // zero-height marquee missing it assert!(!intersects_rect(&p, Rect::new(20.0, 5.0, 30.0, 5.0))); } + + /// A marquee that lies apart from a path's control box misses it without measuring the path's + /// segments. One that reaches the control box but not the curve is still judged on the curve. + #[test] + fn marquee_apart_from_the_control_box_measures_no_segment() { + let p = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)); + let measured = crate::path::measured_segments; + let before = measured(); + assert!(!intersects_rect(&p, Rect::new(20.0, 20.0, 30.0, 30.0))); + assert!(!intersects_rect(&p, Rect::new(-30.0, 4.0, -20.0, 6.0))); + assert_eq!(measured(), before, "a marquee apart from the control box measures nothing"); + // A curve whose handle reaches into the marquee while the curve stays below it. + use crate::path::{Anchor, SubPath}; + let arch = PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 40.0)), + Anchor::with_handles(Point::new(10.0, 0.0), Point::new(10.0, 40.0), Point::new(10.0, 0.0)), + ], + false, + )]); + assert!(!intersects_rect(&arch, Rect::new(-1.0, 35.0, 11.0, 39.0)), "the curve peaks at y 30"); + assert!(measured() > before, "a marquee inside the control box measures the curve"); + assert!(intersects_rect(&arch, Rect::new(4.0, 25.0, 6.0, 35.0)), "a marquee across the peak"); + } } #[cfg(test)] diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 0f45f1cb50..9b45ba4e12 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -190,8 +190,10 @@ impl Indices { if self.lo >= self.hi { return Ok(None); } + // The object may have become one of a host class with an indexer meanwhile, whose + // elements are not properties: the rest of the range is then visited index by index. if self.sparse.as_ref().is_some_and(|s| s.epoch != interp.heap.index_epoch) { - self.sparse = self.gather(interp)?; + self.sparse = if interp.host_indexer(self.obj)?.is_some() { None } else { self.gather(interp)? }; } let k = match &mut self.sparse { None if self.ascending => self.lo, diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 9b6bd6017a..4314aa60f8 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -414,6 +414,11 @@ impl Interp { let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); self.constructing = was; let v = v?; + // `new` gives an object ([[Construct]]): a constructor that gives another value + // is a TypeError. + if !matches!(v, Value::Object(_)) { + return Err(self.type_error(&format!("the constructor {name} did not give an object"))); + } if let Value::Object(o) = &v && matches!(self.object(*o)?.class, Class::Ordinary) && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 4b705d601e..8be19d08f8 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -330,12 +330,15 @@ impl Interp { } } if let Some(id) = found { + // Its indexer and the indices its prototypes hold can change with its class, so a list + // of the indices it has is made again ([`crate::heap::Heap::index_epoch`]). let o = self.object_mut(id)?; if let Class::Host(h) = &mut o.class && h.class != class { h.class = class; o.proto = Some(proto); + self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1); } return Ok(Value::Object(id)); } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1855b929ee..5c44572144 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -1022,6 +1022,61 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() { + let mut r = realm(1_000_000); + let make: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + with_thing(&mut r, Some(make)); + let out = r.run("var e; try { new Thing(); } catch (x) { e = x; } [e instanceof TypeError, typeof Thing()].join()").unwrap(); + assert_eq!(out, JsValue::String("true,undefined".into())); +} + +#[test] +fn an_array_method_visits_every_element_after_its_object_takes_a_class_with_an_indexer() { + let mut r = realm(10_000_000); + // `Base` has a length of 5,000, an element `0` on its prototype and no indexer; `Indexed`, of + // the same family, gives `list[i]` for each index. `upgrade()` gives the same object as an + // `Indexed`. + let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0))); + let zero: HostFunction = Rc::new(|_| Ok(Data::Number(0.0))); + let upgrade: HostFunction = Rc::new(|_| Ok(host_ref("Indexed", &[1.0]))); + let members = vec![ + ("length".to_string(), HostMember::Get(length)), + ("0".to_string(), HostMember::Get(zero)), + ("upgrade".to_string(), HostMember::Method(upgrade)), + ]; + let base = HostClass { name: "Base".into(), parent: None, members, info: Vec::new(), index: None, construct: None }; + let index: HostFunction = Rc::new(|a| Ok(a.get(1).cloned().unwrap_or(Data::Undefined))); + let indexed = + HostClass { name: "Indexed".into(), parent: Some("Base".into()), members: Vec::new(), info: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![base, indexed], vec![("list".into(), host_ref("Base", &[1.0]))]).unwrap(); + let out = r + .run("var n = 0; Array.prototype.forEach.call(list, function () { if (n === 0) list.upgrade(); n++; }); [list instanceof Indexed, n].join()") + .unwrap(); + assert_eq!(out, JsValue::String("true,5000".into())); +} + +#[test] +fn array_methods_visit_every_element_of_a_long_host_list() { + let mut r = realm(10_000_000); + // `list[i]` is `i` below 5,000, past the span the array methods visit without listing. + let index: HostFunction = Rc::new(|a| { + let i = a.get(1).and_then(|i| if let Data::Number(n) = i { Some(*n) } else { None }); + Ok(i.filter(|n| *n < 5_000.0).map_or(Data::Undefined, Data::Number)) + }); + let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0))); + let members = vec![("length".to_string(), HostMember::Get(length))]; + let class = HostClass { name: "List".into(), parent: None, members, info: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("list".into(), host_ref("List", &[1.0]))]).unwrap(); + let out = r + .run( + "var n = 0; Array.prototype.forEach.call(list, function () { n++; });\ + [Array.prototype.indexOf.call(list, 4999), Array.prototype.lastIndexOf.call(list, 0), n].join()", + ) + .unwrap(); + assert_eq!(out, JsValue::String("4999,0,5000".into())); +} + #[test] fn objects_of_a_host_class_report_its_available_members_as_their_own() { let mut r = realm(1_000_000); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9dedb0dfc0..b8bf03ada6 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", ), ( "print.printers", diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1298051ad8..83fb4194bc 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -262,7 +262,7 @@ impl VectorcraftApp { } // A filter plug-in run becomes Object › Plug-ins › Apply Last Filter. dialogs::plugin::after_command(self, id, ¶ms, &r, plugins_before); - let copied = r.is_ok() && self.publish_copy(id); + let copied = r.as_ref().is_ok_and(|v| self.publish_copy(id, v)); self.sync_views(); self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. @@ -328,10 +328,11 @@ impl VectorcraftApp { r } - /// After a Copy or Cut `id` that ran: offer what it copied to other apps - /// ([`Self::publish_clipboard`]) → whether `id` is one. - fn publish_copy(&mut self, id: &str) -> bool { - let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut"); + /// After a Copy or Cut `id` that ran, or a script run to its end (`reply` without `running`) + /// that reports `copied`: offer what it copied to other apps ([`Self::publish_clipboard`]) → + /// whether it did. + fn publish_copy(&mut self, id: &str, reply: &Value) -> bool { + let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") || (id == "script.run" && reply["copied"] == true); if copy { self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut")); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7495e0ed02..bfe9f1991c 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1498,6 +1498,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val }; match (set, answer) { (Some(Ok(_)), Some(answer)) => { + if answer == "ui.dialog.confirm" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::print::prepare_confirm(app, host, id); + } craft::automation::dialogs::dialog_method(host, ctx, answer, &json!({ "dialog": params["dialog"] })) } // A set answers with the dialog it set, `{id, parent, key, fields}`, as production did. diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 5bebc27656..6c76cca2e5 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -24,7 +24,7 @@ use craft::print::ui::{ }; use craft::ui::buttons::ToggleButton; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Politeness, Props as _, Show as _, ShowContainer as _, announce}; use craft::ui::dialog::{DialogId, StackDialog as _}; use craft::ui::display::{Shade, Text}; use craft::ui::layout::empty_cell; @@ -119,6 +119,9 @@ struct Open { papers_pending: bool, /// The ids of the Size choices the dialog was last given. media: Vec, + /// The printer discovery still running on a background job. The dialog takes its list once it has arrived, so + /// PDF File stays available while the system's printers are looked up. + discovery: Option>>, } /// The document (uid, revision) and the settings a cached preview belongs to. @@ -292,13 +295,14 @@ fn start( ) -> Result { let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; let ctx = app.ui_ctx.clone().ok_or("no window to show the dialog in")?; - let (printers, service) = destinations(app); + let background = shared_printers(app).is_some(); + let (printers, service) = if background { (listed(Vec::new(), true), true) } else { destinations(app) }; let mut state = State::default(); state.settings.destination = Destination::Printer( printers.iter().find(|p| p.default).or(printers.first().filter(|_| service)).map_or_else(|| PDF_FILE.to_string(), |p| p.name.clone()), ); state.printers = printers; - let header = if service && cfg!(windows) { + let mut header = if service && cfg!(windows) { vec![ Param::new("directPdf", tl!("Send PDF directly (bypass driver)"), ParamKind::bool(false)) .tooltip(tl!("Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size.")), @@ -306,6 +310,10 @@ fn start( } else { vec![] }; + header.push(Param::custom("__discovery", "", |ui, fields, _| { + let text = if fields.bool("__discovery") == Some(true) { tl!("Finding printers. PDF File and Done are available.") } else { "" }; + Text::new(text).show(ui) + })); let taken: Vec = taken_names(app); let named = editing.clone(); let driver = driver(has_setup(app), &state.settings.destination); @@ -325,13 +333,30 @@ fn start( .json_form(|fields, out| out.extend(nested(form::json_of(&KEYS, fields)))) .check_name(move |name: &str| refusal(&taken, &named, name).map(|_| PresetError::NameTaken)) .held_ok(); + let discovery = (background && mode == PrintMode::Print).then(|| discover(app)); + if discovery.is_some() { + hosted.set_settings_valid(false); + hosted.set_field("__discovery", true.into()); + } // The name row is the dialog's own. if mode == PrintMode::PresetEditor { hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = - Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver, papers: (printer, papers), papers_pending, media }); + app.print_dialog.open = Some(Open { + id, + mode, + document, + preset, + editing, + art: None, + preview: None, + driver, + papers: (printer, papers), + papers_pending, + media, + discovery, + }); Ok(Value::Null) } @@ -394,12 +419,49 @@ fn insert_at(map: &mut Map, path: &[&str], v: Value) { /// and PDF File last; and whether there is a print service. fn destinations(app: &mut VectorcraftApp) -> (Vec, bool) { let service = app.services.print.is_some(); - let mut list: Vec = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default(); + let list: Vec = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default(); + (listed(list, service), service) +} + +/// The Printer list of the system's printers `list`: the default printer by itself when a print `service` names none, +/// and PDF File last. +fn listed(mut list: Vec, service: bool) -> Vec { if service && list.is_empty() { list.push(Printer::new("").label(tl!(DEFAULT_PRINTER))); } list.push(Printer::new(PDF_FILE).label(tl!(PDF_FILE))); - (list, service) + list +} + +/// The print service's background printer discovery, if it has one. +fn shared_printers(app: &VectorcraftApp) -> Option { + app.services.print.as_ref().and_then(|s| s.shared_printers()) +} + +/// The Printer list for the dialog to take ([`HostedPrint::listen`]): found on a background job when the print service +/// has a background discovery, otherwise listed here. +fn discover(app: &mut VectorcraftApp) -> mpsc::Receiver> { + let (tx, rx) = mpsc::channel(); + match shared_printers(app) { + Some(find) => { + let ctx = app.ui_ctx.clone(); + app.jobs().spawn( + "printer-discovery", + Box::new(move || { + // The dialog may have closed and dropped the receiver; nothing waits for the list then. + let _ = tx.send(listed(find(), true)); + if let Some(ctx) = ctx { + ctx.request_repaint(); + } + }), + ); + } + None => { + // The receiver is held by the dialog, so the send cannot fail. + let _ = tx.send(destinations(app).0); + } + } + rx } /// Whether the print service can open a printer's settings (`print.printerSetup`). @@ -456,9 +518,25 @@ fn on(dialogs: &WindowDialogs, f: impl FnOnce(&mut HostedPrint) -> R) -> Opti dialogs.with(|h| h.get_mut::().map(f)) } +pub(crate) fn prepare_confirm(app: &VectorcraftApp, host: &mut craft::ui::dialog::DialogHost, id: DialogId) { + if let Some(open) = &app.print_dialog.open + && open.id == id + && let Some(p) = host.get_mut::() + { + discovery_valid(p, open.mode, open.discovery.is_some()); + } +} + +/// Enables Print unless the dialog prints to a printer while the printer list is still being looked up. +fn discovery_valid(p: &mut HostedPrint, mode: PrintMode, pending: bool) { + let physical = matches!(&p.state().settings.destination, Destination::Printer(name) if name != PDF_FILE); + p.set_settings_valid(mode != PrintMode::Print || !(pending || p.state().discovering()) || !physical); +} + /// One pass of the pump over the open dialog; false once it has closed. fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open: &mut Open) -> bool { - let setup = has_setup(app); + // Setup… looks the printers up again on some systems, so the row shows it once the discovery has ended. + let setup = has_setup(app) && open.discovery.is_none(); let Some(mut d) = on(dialogs, |p| { // The printer row shows Setup… for the printer chosen, and none for PDF File. let driver = driver(setup, &p.state().settings.destination); @@ -576,6 +654,12 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, .collect(); on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()])); } + if d.refresh { + if open.discovery.is_none() { + open.discovery = Some(discover(app)); + } + announce(ctx, tl!("Finding printers. PDF File and Done are available."), Politeness::Polite); + } if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) { let message = tl!("Return to the original drawing to print it"); on(dialogs, |p| { @@ -592,12 +676,31 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open.driver = d.driver; ctx.request_repaint(); } - if d.refresh { - let (list, _) = destinations(app); - let (tx, rx) = mpsc::channel(); - // The receiver is held by the dialog below, so the send cannot fail. - let _ = tx.send(list); - on(dialogs, |p| p.listen(rx)); + let discovery_pending = open.discovery.is_some(); + if let Some(rx) = &open.discovery { + let found = match rx.try_recv() { + Ok(list) => Some(Some(list)), + Err(mpsc::TryRecvError::Disconnected) => Some(None), + Err(mpsc::TryRecvError::Empty) => None, + }; + if let Some(list) = found { + open.discovery = None; + let (tx, rx) = mpsc::channel(); + // A discovery that stopped without a list leaves the default printer and PDF File. + // The receiver is held by the dialog below, so the send cannot fail. + let _ = tx.send(list.unwrap_or_else(|| listed(Vec::new(), true))); + on(dialogs, |p| { + p.listen(rx); + p.state_mut().poll(ctx); + let selected = match &p.state().settings.destination { + Destination::Printer(name) if name.is_empty() => tl!(DEFAULT_PRINTER).to_string(), + Destination::Printer(name) => name.clone(), + _ => tl!(PDF_FILE).to_string(), + }; + let message = crate::i18n::fmt(tl!("Printers are ready. Selected printer: {printer}."), &[("printer", &selected)]); + announce(ctx, message, Politeness::Polite); + }); + } } if let Some(printer) = d.setup && let Err(e) = app.run("print.printerSetup", json!({ "printer": printer })) @@ -630,7 +733,10 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, Err(_) => Some(tl!("Can't print these settings: see the Summary")), }; on(dialogs, |p| { + let pending = open.discovery.is_some() || p.state().discovering(); p.set_sheet(sheet); + discovery_valid(p, open.mode, pending); + p.set_field("__discovery", pending.into()); p.set_message(message.map(Into::into)); }); if changed { @@ -643,7 +749,15 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, p.set_field("__inks", FieldValue::Json(inks)); }); } - if let Some(answer) = d.ok { + // Physical printing waits until the dialog has applied the discovered list. + if open.mode == PrintMode::Print + && discovery_pending + && d.ok.as_ref().is_some_and(|answer| { + matches!(answer.finish, PrintFinish::Print) && matches!(&answer.settings.destination, Destination::Printer(name) if name != PDF_FILE) + }) + { + on(dialogs, HostedPrint::release_ok); + } else if let Some(answer) = d.ok { let result = accept(app, open, &answer, &d.name); on(dialogs, |p| p.answer_ok(result.map_err(Into::into))); } diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ebd7fcb6de..292267fd62 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -66,6 +66,7 @@ use craft::ui::dialog::{ use craft::ui::display::Text; use craft::ui::layout_components::Stack; use craft::ui::runtime::keys; +use craft::ui::runtime::windows::WindowHost; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use egui::Ui; @@ -96,6 +97,8 @@ pub const PRINT_KIND: &str = "scriptPrint"; /// Why Allow Once and Always Allow are refused to automation. pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access"; +/// Why Yes to turning off the external script warning is refused to automation. +pub(crate) const WARNING_BY_PERSON: &str = "Only the person at the keyboard can turn off the external script warning"; /// The note the file dialog shows when the person picked more files than a script is given. const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; @@ -181,6 +184,8 @@ pub(crate) struct ScriptAnswer { pub(crate) answer: &'static str, /// The text of a prompt. pub(crate) value: String, + /// Automation gave the answer: `ui.dialog.confirm`, or a click in a pass automation drove. + pub(crate) automated: bool, } /// What a script's file dialog answers with. @@ -223,11 +228,15 @@ pub(crate) struct ScriptNotice { no_as_default: bool, value: String, answer: Option<&'static str>, + /// The confirm is the app's own question before the external script warning turns off + /// ([`vectorcraft_engine::Session::script_dialog_turns_warning_off`]), not a script's. + warning_off: bool, } impl ScriptNotice { - fn new(d: &ScriptDialog) -> Self { + fn new(d: &ScriptDialog, warning_off: bool) -> Self { Self { + warning_off, kind: d.kind.id().to_string(), message: d.message.clone(), title: d.title.clone(), @@ -273,6 +282,12 @@ impl ScriptNotice { } } +/// The dialog's message: a script's own text as it is, and the question the app asks before a +/// script turns off the external script warning in the current language. +fn notice_message(message: &str, warning_off: bool) -> String { + if warning_off { crate::i18n::msg(message) } else { message.to_string() } +} + impl StackDialog for ScriptNotice { type Result = ScriptAnswer; @@ -286,7 +301,7 @@ impl StackDialog for ScriptNotice { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let (answers, buttons): (Vec<&'static str>, Vec) = self.choices().into_iter().unzip(); - let message = shown_text(&self.message, true); + let message = shown_text(¬ice_message(&self.message, self.warning_off), true); let mut prompt = Prompt::new(self.heading(), message.clone()).answers(buttons); if self.error_icon { prompt = prompt.tone(Tone::Bad, tl!("The script reports an error.")); @@ -307,12 +322,13 @@ impl StackDialog for ScriptNotice { self.value = cut_to(&self.value, MAX_PROMPT_BYTES).to_string(); } let answer = *answers.get(picked?)?; - Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() })) + let automated = WindowHost::of(ui.ctx()).injected_pass(); + Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated })) } fn confirm(&mut self, _: &egui::Context) -> Option { let answer = self.answer.unwrap_or_else(|| self.default_answer()); - Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() }) + Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated: true }) } fn json_fields(&self) -> Option { @@ -344,6 +360,9 @@ impl StackDialog for ScriptNotice { let Some(answer) = answers_for(&self.kind).split(", ").find(|answer| *answer == wanted) else { return Err(format!("`answer` for this {} dialog must be one of: {}", self.kind, answers_for(&self.kind))); }; + if answer == "yes" && self.warning_off { + return Err(WARNING_BY_PERSON.into()); + } self.answer = Some(answer); } _ => return Err(FieldRefusal::Unknown.message(field)), @@ -723,7 +742,7 @@ pub(crate) fn open_growth(app: &VectorcraftApp) { /// Shows the dialog the running script waits at. pub(crate) fn open_notice(app: &VectorcraftApp, d: &ScriptDialog) { - open_over_window(app, ScriptNotice::new(d)); + open_over_window(app, ScriptNotice::new(d, app.session.script_dialog_turns_warning_off())); } /// Shows the file dialog the running script waits at. @@ -878,9 +897,20 @@ pub(crate) fn settle_notice(app: &mut VectorcraftApp, result: DialogResult "no", _ => "stop", }; - ScriptAnswer { kind, answer, value: String::new() } + ScriptAnswer { kind, answer, value: String::new(), automated: false } } }; + // Only the person at the keyboard turns off the external script warning: Yes that automation + // gave, or taken in a pass automation drives, is refused, the warning stays on, and the + // question opens again. + let warning_off = app.session.script_dialog_turns_warning_off(); + if warning_off && answer.answer == "yes" && (answer.automated || app.automation_is_acting()) { + app.status(WARNING_BY_PERSON); + if let Some(d) = app.session.script_dialog() { + open_notice(app, &d); + } + return; + } if let Err(e) = give(app, &answer) { app.status(e); if let Some(d) = app.session.script_dialog() { @@ -1146,3 +1176,29 @@ pub(crate) fn settle_print(app: &mut VectorcraftApp, result: DialogResult Vec { .collect() } +/// A print service with a background printer discovery, which counts the lists made on the UI thread. +struct SlowDiscovery { + /// How many times the dialog listed the printers on the UI thread. + listed_here: Rc>, + jobs: Jobs, + printers: Vec, +} + +impl PrintService for SlowDiscovery { + fn printers(&mut self) -> Vec { + self.listed_here.set(self.listed_here.get() + 1); + MockPrint(Jobs::default()).printers() + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(self.jobs.clone()).print(job) + } + + fn shared_printers(&self) -> Option { + let printers = self.printers.clone(); + Some(std::sync::Arc::new(move || printers.clone())) + } +} + +/// The message the Print dialog shows while the printer discovery runs. +const PENDING_MESSAGE: &str = "Finding printers. PDF File and Done are available."; + +/// Checks the dialog's next frame: whether it shows the discovery message, and whether Print is enabled. Done always +/// is. +fn discovery_controls(app: &mut VectorcraftApp, pending: bool, enabled: bool) { + use egui::accesskit::Role; + let ctx = ctx(app); + let out = crate::testing::app_frame(app, &ctx, Default::default()); + let nodes = out.platform_output.accesskit_update.expect("an accessibility tree").nodes; + let button = |name| nodes.iter().map(|(_, node)| node).find(|node| node.role() == Role::Button && node.label() == Some(name)).unwrap(); + assert_eq!(!button("Print").is_disabled(), enabled, "Print availability follows discovery and destination"); + assert!(!button("Done").is_disabled(), "Done stays available"); + assert_eq!(nodes.iter().any(|(_, node)| node.label() == Some(PENDING_MESSAGE) || node.value() == Some(PENDING_MESSAGE)), pending); +} + +/// An app with a drawing whose print service finds `printers` on a background job that waits until the test runs it, +/// as a slow print server would; with the count of lists made on the UI thread, the jobs printed, and the jobs. +fn discovery_app(printers: Vec) -> (VectorcraftApp, Rc>, Jobs, std::sync::Arc) { + let listed_here = Rc::new(Cell::new(0)); + let printed = Jobs::default(); + let service = SlowDiscovery { listed_here: listed_here.clone(), jobs: printed.clone(), printers }; + let services = Services { print: Some(Box::new(service)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); + app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs.clone()).build()); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + (app, listed_here, printed, jobs) +} + +/// The dialog opens and works while the printer discovery waits on a background job, and shows the system's printers +/// once the job has run. +#[test] +fn printer_discovery_runs_off_the_ui_thread() { + use egui::accesskit::Role; + let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers()); + let pending_message = PENDING_MESSAGE; + let controls = discovery_controls; + app.run("file.print", json!({})).unwrap(); + app.run("file.new", json!({"width": 180, "height": 100})).unwrap(); + let ctx = ctx(&app); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!( + nodes.iter().any(|(_, node)| node.role() == Role::Button && node.label() == Some("Print") && node.is_disabled()), + "physical Print is disabled in the first frame" + ); + assert!( + nodes.iter().any(|(_, node)| { + node.role() == Role::Status + && node.live() == Some(egui::accesskit::Live::Polite) + && node.label().is_some_and(|text| text.contains(pending_message)) + }), + "printer discovery is announced before Print is pressed" + ); + assert_eq!(listed_here.get(), 0, "the printers are not listed on the UI thread"); + assert_eq!(jobs.waiting(), 1, "discovery starts even after switching drawings before the first pump"); + app.run("document.activate", json!({"index": 0})).unwrap(); + pump(&mut app); + controls(&mut app, true, false); + assert_eq!(jobs.waiting(), 1, "the discovery waits on a background job"); + assert_ne!(fields(&app)["printer"], "Proofer", "the list has not arrived"); + set(&mut app, "printer", json!("PDF File")); + pump(&mut app); + controls(&mut app, true, true); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!(nodes.iter().any(|(_, node)| node.label() == Some("Print preview image")), "PDF preview stays available during discovery"); + set(&mut app, "sheet", json!(0)); + pump(&mut app); + assert_eq!(fields(&app)["sheet"], 0, "PDF preview accepts page selection during discovery"); + set(&mut app, "printer", json!("")); + pump(&mut app); + set(&mut app, "section", json!("Graphics")); + pump(&mut app); + assert_eq!(jobs.waiting(), 1, "one discovery at a time"); + confirm(&mut app); + assert!(is_open(&app), "physical printing waits for discovery"); + assert!(printed.borrow().is_empty()); + let (id, _) = top(&app).unwrap(); + app.dialogs().unwrap().with(|host| { + host.get_mut::().unwrap().set_settings_valid(true); + let _ = host.confirm_by_id(&ctx, id); + assert_eq!(host.held_state(id), Some(craft::ui::dialog::HeldOk::Waiting)); + }); + assert_eq!(jobs.run_all(), 1); + // The frame's pump takes the list and announces it. + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "the pump discards the held physical answer"); + assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer"); + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!( + nodes.iter().any(|(_, node)| { + node.role() == Role::Status + && node.live() == Some(egui::accesskit::Live::Polite) + && node.label().is_some_and(|text| text.contains("Printers are ready. Selected printer: Proofer.")) + }), + "the applied printer list and selected queue are announced" + ); + pump(&mut app); + assert!(is_open(&app), "the held Print answer waits for the dialog to apply the list"); + assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer"); + assert_eq!(fields(&app)["printer"], "Proofer", "the system's default printer, once the list arrives"); + assert_eq!(listed_here.get(), 0); + controls(&mut app, false, true); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(printed.borrow().len(), 1); + assert_eq!(printed.borrow()[0].0.as_deref(), Some("Proofer")); + + let picker = crate::tests_picks::scripted(&mut app); + let written: Written = Rc::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { + w.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + })); + app.run("file.print", json!({})).unwrap(); + call(&mut app, "ui.dialog.set", json!({"dialog": "top", "field": "printer", "value": "PDF File", "action": "confirm"})); + picker.answer_saved("/tmp/discovery-combined.pdf", None); + crate::tests_picks::poll(&mut app, &ctx); + assert_eq!(written.borrow().len(), 1, "PDF selection and confirmation work in one call before a frame"); + assert_eq!(printed.borrow().len(), 1, "PDF confirmation does not submit a physical job"); + assert_eq!(jobs.waiting(), 1, "PDF confirmation does not wait for discovery"); + assert_eq!(jobs.run_all(), 1); + assert_eq!(listed_here.get(), 0); +} + +/// While the printer discovery runs, Done keeps the settings and PDF File saves, and a held Print to a printer waits. +#[test] +fn done_and_pdf_file_work_while_printers_are_found() { + let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers()); + let controls = discovery_controls; + let ctx = ctx(&app); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + assert_eq!(jobs.waiting(), 1); + let (id, _) = top(&app).unwrap(); + let _ = app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)); + set(&mut app, "printer", json!("PDF File")); + super::print::pump(&mut app, &ctx); + pump(&mut app); + controls(&mut app, true, true); + assert_eq!(printed.borrow().len(), 0, "the held physical destination is checked even after selecting PDF File"); + set(&mut app, "printer", json!("")); + set(&mut app, "copies", json!(2)); + set(&mut app, "choice", json!("done")); + confirm(&mut app); + assert!(!is_open(&app), "Done can save settings while discovery is pending"); + assert_eq!(app.session.active().unwrap().doc.print_setup.as_ref().unwrap()["copies"], 2); + assert_eq!(printed.borrow().len(), 0, "Done does not submit a print job"); + assert_eq!(jobs.waiting(), 1, "Done did not wait for discovery"); + assert_eq!(jobs.run_all(), 1); + + let picker = crate::tests_picks::scripted(&mut app); + let written: Written = Rc::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| { + w.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + })); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("PDF File")); + pump(&mut app); + controls(&mut app, true, true); + confirm(&mut app); + picker.answer_saved("/tmp/discovery.pdf", None); + crate::tests_picks::poll(&mut app, &ctx); + assert_eq!(written.borrow().len(), 1, "PDF File saves while discovery is pending"); + assert_eq!(pages(&written.borrow()[0].1), 2, "PDF File keeps the copies saved by Done"); + assert_eq!(printed.borrow().len(), 0); + assert_eq!(jobs.waiting(), 1, "PDF File does not wait for discovery"); + assert_eq!(jobs.run_all(), 1); + assert_eq!(listed_here.get(), 0); +} + +/// A discovery that finds no printers leaves Default Printer chosen, and Print goes to it once the list is applied. +#[test] +fn an_empty_discovery_keeps_the_default_printer() { + let (mut app, listed_here, printed, jobs) = discovery_app(vec![]); + let controls = discovery_controls; + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + controls(&mut app, true, false); + confirm(&mut app); + assert!(is_open(&app)); + assert_eq!(fields(&app)["printer"], ""); + assert_eq!(jobs.run_all(), 1); + pump(&mut app); + pump(&mut app); + controls(&mut app, false, true); + assert_eq!(fields(&app)["printer"], "", "an empty result keeps Default Printer selected"); + let (id, _) = top(&app).unwrap(); + assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "a blocked Print leaves no stale refusal"); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(printed.borrow().len(), 1); + assert_eq!(printed.borrow()[0].0, None); + assert_eq!(listed_here.get(), 0); +} + /// Every number and length field of the dialog's sections has a name that tells it from the others in its row. #[test] fn every_number_and_length_field_is_named() { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b7ad3eb99b..f4f97b728c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1319,6 +1319,7 @@ font-technology Variable Променливи @msg a drag or an undo group is open; finish it before running a script има отворено влачене или група за отмяна; завършете го, преди да изпълните скрипт @msg the script left a document that cannot be kept скриптът остави документ, който не може да се запази @msg the script is no longer in the Scripts folder скриптът вече не е в папката Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Скриптът иска да изключи предупреждението, което се показва преди изпълнението на скрипт, избран с Файл › Скриптове › Друг скрипт… След това избраните по-късно скриптове ще се изпълняват без него. Да се изключи ли предупреждението? @msg the script's run is no longer available изпълнението на скрипта вече не е налично @msg a failed command changed undo steps that could not be put back, so the script was stopped неуспешна команда промени стъпки за отмяна, които не можаха да се възстановят, затова скриптът беше спрян @msg a recovery copy could not be written, so the script was not run не можа да се запише копие за възстановяване, затова скриптът не беше изпълнен diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 555080655a..bb4156a036 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6476,6 +6476,7 @@ digits Malayalam Malaiàlam @msg a drag or an undo group is open; finish it before running a script hi ha un arrossegament o un grup de desfer obert; acabeu-lo abans d'executar un script @msg the script left a document that cannot be kept l'script ha deixat un document que no es pot conservar @msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? L'script demana desactivar l'avís que es mostra abans que s'executi un script triat amb Fitxer › Scripts › Un altre script… Els scripts triats després s'executarien sense l'avís. Voleu desactivar l'avís? Some scripts were not listed Alguns scripts no s'han llistat The Scripts folder cannot be read No es pot llegir la carpeta Scripts Loading scripts… S’estan carregant els scripts… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8d11266cdd..f5f44e308f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5283,6 +5283,7 @@ imageTrace Outline Obrys @msg a drag or an undo group is open; finish it before running a script je otevřené tažení nebo skupina kroků zpět; před spuštěním skriptu ji dokončete @msg the script left a document that cannot be kept skript zanechal dokument, který nelze zachovat @msg the script is no longer in the Scripts folder skript už není ve složce Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skript žádá o vypnutí upozornění, které se zobrazí před spuštěním skriptu vybraného příkazem Soubor › Skripty › Jiný skript… Později vybrané skripty by se pak spouštěly bez něj. Vypnout upozornění? Some scripts were not listed Některé skripty nebyly uvedeny The Scripts folder cannot be read Složku Scripts nelze přečíst Loading scripts… Načítání skriptů… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9820804ff0..cfc7dd75f4 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -64,6 +64,7 @@ @msg a drag or an undo group is open; finish it before running a script en trækning eller en fortrydelsesgruppe er åben; afslut den, før du kører et script @msg the script left a document that cannot be kept scriptet efterlod et dokument, der ikke kan beholdes @msg the script is no longer in the Scripts folder scriptet ligger ikke længere i mappen Scripter +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Scriptet beder om at slå advarslen fra, som vises, før et script, der er valgt med Filer › Scripter › Andet script…, køres. Scripter, der vælges senere, ville så køre uden den. Vil du slå advarslen fra? @msg the script's run is no longer available scriptets kørsel er ikke længere tilgængelig @msg a failed command changed undo steps that could not be put back, so the script was stopped en mislykket kommando ændrede fortrydelsestrin, der ikke kunne genskabes, så scriptet blev stoppet @msg a recovery copy could not be written, so the script was not run en gendannelseskopi kunne ikke skrives, så scriptet blev ikke kørt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d29f3c46c0..2bd23256bb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4869,6 +4869,7 @@ theme Appearance Erscheinungsbild @msg a drag or an undo group is open; finish it before running a script ein Ziehvorgang oder eine Rückgängig-Gruppe ist offen; schließen Sie sie ab, bevor Sie ein Skript ausführen @msg the script left a document that cannot be kept das Skript hat ein Dokument hinterlassen, das nicht behalten werden kann @msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Das Skript möchte die Warnung ausschalten, die angezeigt wird, bevor ein mit „Datei › Skripte › Anderes Skript…“ gewähltes Skript ausgeführt wird. Später gewählte Skripte würden dann ohne sie ausgeführt. Warnung ausschalten? Some scripts were not listed Einige Skripte wurden nicht aufgeführt The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden Loading scripts… Skripte werden geladen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e4a651342a..c2044cfd3e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2666,6 +2666,7 @@ axis Both Και τα δύο @msg a drag or an undo group is open; finish it before running a script είναι ανοιχτή μια μεταφορά ή ομάδα αναίρεσης· ολοκληρώστε την πριν εκτελέσετε σενάριο @msg the script left a document that cannot be kept το σενάριο άφησε ένα έγγραφο που δεν μπορεί να διατηρηθεί @msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Το σενάριο ζητά να απενεργοποιηθεί η προειδοποίηση που εμφανίζεται πριν εκτελεστεί ένα σενάριο που επιλέχθηκε με Αρχείο › Δέσμες ενεργειών › Άλλο σενάριο… Τα σενάρια που θα επιλεγούν αργότερα θα εκτελούνται τότε χωρίς αυτήν. Να απενεργοποιηθεί η προειδοποίηση; Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts Loading scripts… Φόρτωση σεναρίων… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 008a0b6483..58ed9b8a5b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4945,6 +4945,7 @@ axis Both Ambos @msg a drag or an undo group is open; finish it before running a script hay un arrastre o un grupo de deshacer abierto; termínelo antes de ejecutar un script @msg the script left a document that cannot be kept el script dejó un documento que no se puede conservar @msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? El script pide desactivar la advertencia que se muestra antes de que se ejecute un script elegido con Archivo › Scripts › Otro script… Los scripts elegidos después se ejecutarían sin ella. ¿Desactivar la advertencia? Some scripts were not listed Algunos scripts no se han incluido en la lista The Scripts folder cannot be read No se puede leer la carpeta Scripts Loading scripts… Cargando scripts… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ffbeb6f49b..47a1158f51 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5188,6 +5188,7 @@ imageTrace Outline Ääriviiva @msg a drag or an undo group is open; finish it before running a script vetäminen tai kumousryhmä on kesken; viimeistele se ennen komentosarjan suorittamista @msg the script left a document that cannot be kept komentosarja jätti asiakirjan, jota ei voi säilyttää @msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Komentosarja pyytää poistamaan käytöstä varoituksen, joka näytetään ennen kuin komennolla Tiedosto › Komentosarjat › Muu komentosarja… valittu komentosarja suoritetaan. Myöhemmin valitut komentosarjat suoritettaisiin silloin ilman sitä. Poistetaanko varoitus käytöstä? Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu The Scripts folder cannot be read Scripts-kansiota ei voi lukea Loading scripts… Ladataan komentosarjoja… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7e03e3b7c4..57f6132977 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4927,6 +4927,7 @@ axis Both Les deux @msg a drag or an undo group is open; finish it before running a script un glissement ou un groupe d’annulation est ouvert ; terminez-le avant d’exécuter un script @msg the script left a document that cannot be kept le script a laissé un document qui ne peut pas être conservé @msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Le script demande à désactiver l’avertissement affiché avant l’exécution d’un script choisi avec Fichier › Scripts › Autre script… Les scripts choisis ensuite s’exécuteraient alors sans lui. Désactiver l’avertissement ? Some scripts were not listed Certains scripts ne sont pas répertoriés The Scripts folder cannot be read Impossible de lire le dossier Scripts Loading scripts… Chargement des scripts… diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 8ad28968c5..1dcabb8251 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7684,6 +7684,7 @@ arrowhead Feather पंख @msg a drag or an undo group is open; finish it before running a script कोई ड्रैग या पूर्ववत समूह खुला है; स्क्रिप्ट चलाने से पहले उसे पूरा करें @msg the script left a document that cannot be kept स्क्रिप्ट ने ऐसा दस्तावेज़ छोड़ा है जिसे रखा नहीं जा सकता @msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? स्क्रिप्ट उस चेतावनी को बंद करना चाहती है जो फ़ाइल › स्क्रिप्ट्स › अन्य स्क्रिप्ट… से चुनी गई स्क्रिप्ट चलने से पहले दिखाई जाती है। इसके बाद चुनी गई स्क्रिप्ट्स उसके बिना चलेंगी। चेतावनी बंद करें? Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता Loading scripts… स्क्रिप्ट लोड हो रही हैं… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3116815efa..0879de9fda 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5804,6 +5804,7 @@ imageTrace Outline Körvonal @msg a drag or an undo group is open; finish it before running a script húzás vagy visszavonási csoport van folyamatban; fejezze be a parancsfájl futtatása előtt @msg the script left a document that cannot be kept a parancsfájl olyan dokumentumot hagyott hátra, amely nem tartható meg @msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? A parancsfájl ki szeretné kapcsolni azt a figyelmeztetést, amely a Fájl › Szkriptek › Másik szkript… paranccsal kiválasztott parancsfájl futása előtt jelenik meg. A később kiválasztott parancsfájlok ezután nélküle futnának. Kikapcsolja a figyelmeztetést? Some scripts were not listed Néhány szkript nem szerepel a listában The Scripts folder cannot be read A Scripts mappa nem olvasható Loading scripts… Szkriptek betöltése… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b159d2bfb7..7ac37a8366 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -64,6 +64,7 @@ @msg a drag or an undo group is open; finish it before running a script seretan atau grup urungkan sedang terbuka; selesaikan sebelum menjalankan skrip @msg the script left a document that cannot be kept skrip meninggalkan dokumen yang tidak dapat dipertahankan @msg the script is no longer in the Scripts folder skrip tidak lagi berada di folder Skrip +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skrip meminta untuk mematikan peringatan yang ditampilkan sebelum skrip yang dipilih dengan Berkas › Skrip › Skrip lain… dijalankan. Skrip yang dipilih kemudian akan berjalan tanpa peringatan itu. Matikan peringatan? @msg the script's run is no longer available proses skrip tidak lagi tersedia @msg a failed command changed undo steps that could not be put back, so the script was stopped perintah yang gagal mengubah langkah urungkan yang tidak dapat dikembalikan, sehingga skrip dihentikan @msg a recovery copy could not be written, so the script was not run salinan pemulihan tidak dapat ditulis, sehingga skrip tidak dijalankan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d6b341a367..27e3c7d150 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5007,6 +5007,7 @@ axis Both Entrambi @msg a drag or an undo group is open; finish it before running a script è aperto un trascinamento o un gruppo di annullamento; completalo prima di eseguire uno script @msg the script left a document that cannot be kept lo script ha lasciato un documento che non può essere conservato @msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Lo script chiede di disattivare l'avviso mostrato prima che venga eseguito uno script scelto con File › Script › Altro script… Gli script scelti in seguito verrebbero quindi eseguiti senza avviso. Disattivare l'avviso? Some scripts were not listed Alcuni script non sono stati elencati The Scripts folder cannot be read Impossibile leggere la cartella Scripts Loading scripts… Caricamento degli script… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 48f6dd36cf..e64afd70a4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5834,6 +5834,7 @@ variable-list-end {0}, {1} {0}、{1} @msg a drag or an undo group is open; finish it before running a script ドラッグまたは取り消しグループが開いています。スクリプトを実行する前に完了してください @msg the script left a document that cannot be kept スクリプトが保持できないドキュメントを残しました @msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? スクリプトが、ファイル › スクリプト › その他のスクリプト… で選んだスクリプトを実行する前に表示される警告をオフにしようとしています。オフにすると、以後に選んだスクリプトは警告なしで実行されます。警告をオフにしますか? Some scripts were not listed 一部のスクリプトは一覧に表示されていません The Scripts folder cannot be read Scripts フォルダーを読み込めません Loading scripts… スクリプトを読み込み中… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cbb58ee5ab..6df54defaf 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8515,6 +8515,7 @@ imageTrace Outline კონტური @msg a drag or an undo group is open; finish it before running a script ღიაა გადათრევა ან გაუქმების ჯგუფი; დაასრულეთ სკრიპტის გაშვებამდე @msg the script left a document that cannot be kept სკრიპტმა დატოვა დოკუმენტი, რომლის შენახვა შეუძლებელია @msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? სკრიპტი ითხოვს იმ გაფრთხილების გამორთვას, რომელიც ჩანს ბრძანებით ფაილი › სკრიპტები › სხვა სკრიპტი… არჩეული სკრიპტის გაშვებამდე. შემდეგ არჩეული სკრიპტები მის გარეშე გაეშვება. გამოირთოს გაფრთხილება? Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია Loading scripts… სკრიპტების ჩატვირთვა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bd430d2fc1..35e6a09881 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5763,6 +5763,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg a drag or an undo group is open; finish it before running a script 드래그 또는 실행 취소 그룹이 열려 있습니다. 스크립트를 실행하기 전에 완료하세요 @msg the script left a document that cannot be kept 스크립트가 유지할 수 없는 문서를 남겼습니다 @msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? 스크립트가 파일 › 스크립트 › 다른 스크립트…로 선택한 스크립트를 실행하기 전에 표시되는 경고를 끄려고 합니다. 그러면 이후에 선택한 스크립트는 경고 없이 실행됩니다. 경고를 끌까요? Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 Loading scripts… 스크립트 불러오는 중… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 20365f1488..698f0a3f0f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -64,6 +64,7 @@ @msg a drag or an undo group is open; finish it before running a script er is nog een sleepbeweging of een groep voor ongedaan maken open; rond die af voordat je een script uitvoert @msg the script left a document that cannot be kept het script heeft een document achtergelaten dat niet kan worden behouden @msg the script is no longer in the Scripts folder het script staat niet meer in de map Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Het script vraagt de waarschuwing uit te zetten die wordt getoond voordat een script wordt uitgevoerd dat is gekozen met Bestand › Scripts › Ander script… Scripts die later worden gekozen, worden dan zonder waarschuwing uitgevoerd. Waarschuwing uitzetten? @msg the script's run is no longer available de uitvoering van het script is niet meer beschikbaar @msg a failed command changed undo steps that could not be put back, so the script was stopped een mislukte opdracht heeft stappen voor ongedaan maken gewijzigd die niet konden worden teruggezet, dus is het script gestopt @msg a recovery copy could not be written, so the script was not run er kon geen herstelkopie worden geschreven, dus is het script niet uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4a22a1dd93..8ae2ebecf9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5109,6 +5109,7 @@ imageTrace Outline Kontur @msg a drag or an undo group is open; finish it before running a script otwarte jest przeciąganie lub grupa cofania; zakończ je przed uruchomieniem skryptu @msg the script left a document that cannot be kept skrypt pozostawił dokument, którego nie można zachować @msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skrypt prosi o wyłączenie ostrzeżenia wyświetlanego przed uruchomieniem skryptu wybranego poleceniem Plik › Skrypty › Inny skrypt… Skrypty wybrane później byłyby wtedy uruchamiane bez niego. Wyłączyć ostrzeżenie? Some scripts were not listed Niektóre skrypty nie zostały wyświetlone The Scripts folder cannot be read Nie można odczytać folderu Scripts Loading scripts… Wczytywanie skryptów… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6d910ce85f..c7772edf6b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6154,6 +6154,7 @@ variable-list-end {0}, {1} {0} e {1} @msg a drag or an undo group is open; finish it before running a script há um arraste ou um grupo de desfazer aberto; conclua-o antes de executar um script @msg the script left a document that cannot be kept o script deixou um documento que não pode ser mantido @msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? O script pede para desativar o aviso mostrado antes de executar um script escolhido em Arquivo › Scripts › Outro Script… Os scripts escolhidos depois seriam executados sem ele. Desativar o aviso? Some scripts were not listed Alguns scripts não foram listados The Scripts folder cannot be read Não é possível ler a pasta Scripts Loading scripts… Carregando scripts… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 60906af64a..10583bf9e8 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2767,7 +2767,7 @@ file-filter Templates Шаблоны Other Layers Другие слои Other Libraries Другие библиотеки Other Library… Другая библиотека… - Other Script… Другая письменность… + Other Script… Другой скрипт… Out of Gamut Warning Предупреждение о выходе из цветового охвата Out of Web Color Warning Предупреждение о цвете, не поддерживаемом web Out Tangent Handles Маркеры исходящей касательной @@ -4983,6 +4983,7 @@ axis Both Оба @msg a drag or an undo group is open; finish it before running a script открыто перетаскивание или группа отмены; завершите их перед запуском скрипта @msg the script left a document that cannot be kept скрипт оставил документ, который нельзя сохранить @msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Скрипт просит отключить предупреждение, которое показывается перед запуском скрипта, выбранного командой Файл › Сценарии › Другой скрипт… Выбранные позже скрипты будут запускаться без него. Отключить предупреждение? Some scripts were not listed Некоторые сценарии не показаны The Scripts folder cannot be read Не удалось прочитать папку Scripts Loading scripts… Загрузка сценариев… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index bf7420d255..9093d1abdd 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4842,6 +4842,7 @@ axis Both Båda @msg a drag or an undo group is open; finish it before running a script en dragning eller ångragrupp är öppen; avsluta den innan du kör ett skript @msg the script left a document that cannot be kept skriptet lämnade ett dokument som inte kan behållas @msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skriptet vill stänga av varningen som visas innan ett skript som valts med Fil › Skript › Annat skript… körs. Skript som väljs senare skulle då köras utan den. Stänga av varningen? Some scripts were not listed Vissa skript visas inte i listan The Scripts folder cannot be read Mappen Scripts kan inte läsas Loading scripts… Läser in skript… diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 3dca49857f..e77c4bae56 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -423,6 +423,17 @@ pub fn undo_labels() -> std::collections::BTreeSet { undo_scan().labels } +/// The confirm a run shows before a script turns off the external script warning, which the message +/// scan doesn't read, is translated in each language of [`COMPLETE_MESSAGES`]. +#[test] +fn script_warning_off_question_is_translated() { + let question = vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION; + for code in COMPLETE_MESSAGES { + let lang = lang(code); + assert_ne!(message(lang, question), question, "{code}"); + } +} + /// What [`undo_scan`] finds in [`UNDO_CRATES`]. struct UndoScan { /// The step names written as literals ([`undo_labels`]). diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 830b60e56b..d17c9ba3bf 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4696,6 +4696,7 @@ axis Both Her İkisi @msg a drag or an undo group is open; finish it before running a script bir sürükleme veya geri alma grubu açık; betiği çalıştırmadan önce tamamlayın @msg the script left a document that cannot be kept betik, saklanamayan bir belge bıraktı @msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Komut dosyası, Dosya › Komut dosyaları › Diğer Komut Dosyası… ile seçilen bir komut dosyası çalışmadan önce gösterilen uyarıyı kapatmak istiyor. Daha sonra seçilen komut dosyaları bu durumda uyarı olmadan çalışır. Uyarı kapatılsın mı? Some scripts were not listed Bazı komut dosyaları listelenmedi The Scripts folder cannot be read Scripts klasörü okunamıyor Loading scripts… Betikler yükleniyor… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 09a9e4bf6d..8317055f65 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2775,7 +2775,7 @@ file-filter Templates Шаблони Other Layers Інші шари Other Libraries Інші бібліотеки Other Library… Інша бібліотека… - Other Script… Інша писемність… + Other Script… Інший скрипт… Out of Gamut Warning Попередження про вихід із колірного охоплення Out of Web Color Warning Попередження про колір, що не підтримується web Out Tangent Handles Маркери вихідної дотичної @@ -4991,6 +4991,7 @@ axis Both Обидві @msg a drag or an undo group is open; finish it before running a script відкрито перетягування або групу скасування; завершіть їх перед запуском скрипта @msg the script left a document that cannot be kept скрипт залишив документ, який не можна зберегти @msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Скрипт просить вимкнути попередження, яке показується перед запуском скрипту, вибраного командою Файл › Сценарії › Інший скрипт… Вибрані пізніше скрипти тоді запускатимуться без нього. Вимкнути попередження? Some scripts were not listed Деякі сценарії не показано The Scripts folder cannot be read Не вдалося прочитати папку Scripts Loading scripts… Завантаження сценаріїв… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index bc63725d0f..5ce16f684a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5470,6 +5470,7 @@ theme Appearance Giao diện @msg a drag or an undo group is open; finish it before running a script đang có thao tác kéo hoặc nhóm hoàn tác; hãy hoàn thành trước khi chạy tập lệnh @msg the script left a document that cannot be kept tập lệnh để lại một tài liệu không thể giữ @msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Tập lệnh yêu cầu tắt cảnh báo hiển thị trước khi chạy một tập lệnh được chọn bằng Tệp › Script › Script khác… Các tập lệnh được chọn sau đó sẽ chạy mà không có cảnh báo. Tắt cảnh báo? Some scripts were not listed Một số tập lệnh không được liệt kê The Scripts folder cannot be read Không thể đọc thư mục Scripts Loading scripts… Đang tải tập lệnh… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9b7e1c7bbc..5e05c98008 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5499,6 +5499,7 @@ imageTrace Outline 轮廓 @msg a drag or an undo group is open; finish it before running a script 拖动或撤销组尚未结束;请在运行脚本前完成 @msg the script left a document that cannot be kept 脚本留下了无法保留的文档 @msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? 脚本请求关闭在运行通过“文件 › 脚本 › 其他脚本…”选择的脚本前显示的警告。关闭后,之后选择的脚本将在没有警告的情况下运行。要关闭警告吗? Some scripts were not listed 部分脚本未列出 The Scripts folder cannot be read 无法读取 Scripts 文件夹 Loading scripts… 正在载入脚本… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2e3bae2d60..52a09f56b4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2831,6 +2831,7 @@ file-filter Templates 範本 @msg a drag or an undo group is open; finish it before running a script 拖曳或還原群組尚未結束;請在執行指令碼前完成 @msg the script left a document that cannot be kept 指令碼留下了無法保留的文件 @msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? 指令碼要求關閉在執行透過 檔案 › 指令碼 › 其他指令碼… 選擇的指令碼前顯示的警告。關閉後,之後選擇的指令碼將在沒有警告的情況下執行。要關閉警告嗎? Some scripts were not listed 部分指令碼未列出 The Scripts folder cannot be read 無法讀取 Scripts 資料夾 Loading scripts… 正在載入指令碼… diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d5fe92f798..20fed52f59 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", ), ( "print.printers", diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index d69c73116f..a27c14f5b3 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -33,6 +33,9 @@ pub struct PrintJob<'a> { /// Submission callable from the desktop background worker. pub type SharedPrintFn = std::sync::Arc) -> Result + Send + Sync>; +/// Printer discovery callable from a background job. +pub type SharedPrintersFn = std::sync::Arc Vec + Send + Sync>; + /// The platform's printing ([`crate::Services::print`]). pub trait PrintService { /// The printers the system knows (none: only the default one, or the browser's dialog). @@ -44,6 +47,11 @@ pub trait PrintService { fn shared_print(&self) -> Option { None } + /// The printer discovery the Print dialog runs on a background job. Without one, the dialog lists + /// [`PrintService::printers`] on the UI thread. + fn shared_printers(&self) -> Option { + None + } /// Whether the system turns a landscape page to fit the paper. macOS's print queues put /// each page on the paper as it is, so their jobs are written upright (`file.print`'s /// `forPrinter`); Windows and the browser's print dialog turn them themselves. diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 9f52b7a4a6..74ceaab6b6 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -63,10 +63,25 @@ pub fn poll(app: &mut VectorcraftApp) { let boards = result.as_ref().ok().and_then(|r| r["activeArtboards"].as_array().cloned()).unwrap_or_default(); match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. - Ok(_) => { - if !crate::panels::actions::after_journaled_edit(app) { + Ok(report) => { + let limited = crate::panels::actions::after_journaled_edit(app); + if !limited { app.status(format!("Ran {name}")); } + // What the script's Copy or Cut left on the clipboard is offered to other apps, as + // Edit › Copy does. + if report["copied"] == true { + let limit = limited.then(|| app.ui.status.clone()); + app.publish_clipboard(false); + // The limit's message is set again, so the notes of the Copy's formats do not + // replace it. A write failure reported at once stays on the status bar. + if let Some(limit) = limit + && app.ui.status == limit + { + app.status(limit); + app.ui.status_notes = None; + } + } // The jobs it prepared for a printer wait for the person's answer. script_run::ask_print(app); } diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 7e90dba636..29b439050d 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -317,3 +317,47 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { assert_eq!(framed["dialogs"], headless["dialogs"]); assert_eq!(framed["log"], json!([true, "p", "done"])); } + +/// Only the person at the keyboard turns off the external script warning: Yes from automation, set +/// as the answer or given in a pass automation drives, is refused, the warning stays on and the +/// question opens again; No is taken from automation. +#[test] +fn only_the_person_turns_off_the_external_script_warning() { + let mut app = app(); + app.session.prefs.show_external_script_warning = true; + // The warning before the run itself is answered by the person. + start(&mut app, "app.preferences.setBooleanPreference('ShowExternalJSXWarning', false); vc.log('done');"); + if is_open::(&app) { + let id = open_id(&app, script_run::KIND); + script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap(); + pump(&mut app); + } + assert!(until_dialog(&mut app)); + assert_eq!(set(&app, NOTICE_KIND, "answer", json!("yes")).unwrap_err(), script_run::WARNING_BY_PERSON); + assert!(is_open::(&app), "the question stays open"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + + script_run::forget::(&app); + app.ui.answering_control = true; + let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new(), automated: false }; + script_run::settle_notice(&mut app, craft::ui::dialog::DialogResult::Ok(yes)); + app.ui.answering_control = false; + assert_eq!(app.ui.status, script_run::WARNING_BY_PERSON); + assert!(is_open::(&app), "the question opens again"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + + // Yes that automation gave is refused in a later frame that automation does not drive. + script_run::forget::(&app); + app.ui.status = String::new(); + let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new(), automated: true }; + script_run::settle_notice(&mut app, craft::ui::dialog::DialogResult::Ok(yes)); + assert_eq!(app.ui.status, script_run::WARNING_BY_PERSON); + assert!(is_open::(&app), "the question opens again"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + assert!(app.session.prefs.show_external_script_warning, "the warning stays on"); + + set(&app, NOTICE_KIND, "answer", json!("no")).unwrap(); + assert!(confirm(&mut app, NOTICE_KIND), "No is taken from automation"); + assert!(!until_dialog(&mut app)); + assert!(app.session.prefs.show_external_script_warning, "the warning stays on"); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 05a6e6fa14..8eadbbaf70 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -1,15 +1,19 @@ //! File › Scripts › Other Script… (`ui.runScript`): the chooser, the warning and its preference, //! a run advanced frame by frame, Stop, and the questions a run and quitting ask. +use std::sync::{Arc, Mutex}; + use craft::host::{PickKind, Picked}; use craft::ui::dialog::{DialogResult, StackDialog}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use vectorcraft_engine::cmd::clipboard::SVG; use vectorcraft_engine::cmd::scripts::TOO_LARGE; use vectorcraft_engine::script::MAX_SOURCE_BYTES; use vectorcraft_engine::script::folder::Clock; use super::script_dialogs::{cancel, confirm, fields, frame, is_open, key, open_id, pump, set}; +use super::sysclip::{Board, fake, writes, written}; use crate::dialogs::script_check; use crate::dialogs::script_run::{ self, BY_PERSON, CLOSE_KIND, FilesAnswer, GROWTH_KIND, GrowthQuestion, KIND, PICKER_KIND, RunQuestion, ScriptFiles, @@ -699,6 +703,76 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { finish(&mut app); } +/// Whether the app wrote the fake system clipboard since `seen` writes, once the formats it is making +/// are written. `seen` becomes the new count. +fn offered(app: &mut VectorcraftApp, board: &Arc>, seen: &mut usize) -> bool { + let _ = app.written_clipboard_text(); + let now = writes(board); + std::mem::replace(seen, now) != now +} + +#[test] +fn a_scripts_copy_is_offered_to_other_apps_when_the_run_ends() { + let (fake, board) = fake(); + let services = crate::Services { clipboard: Some(Box::new(fake)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let mut seen = writes(&board); + let draw = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": draw })).unwrap().unwrap(); + finish(&mut app); + assert!(!offered(&mut app, &board, &mut seen), "a run without a Copy offers nothing"); + let copy = "vc.run('select.all', {}); app.copy();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": copy })).unwrap().unwrap(); + finish(&mut app); + assert!(offered(&mut app, &board, &mut seen)); + assert!(written(&board).contains(&SVG), "{:?}", written(&board)); + // A Copy of what the clipboard already holds is offered again. + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": copy })).unwrap().unwrap(); + finish(&mut app); + assert!(offered(&mut app, &board, &mut seen)); + // A Copy inside a batch of commands counts too, also of what the clipboard already holds. + let batch = "vc.run('select.all', {}); vc.run('command.batch', {commands: [{command: 'edit.copy', params: {}}]});"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": batch })).unwrap().unwrap(); + finish(&mut app); + assert!(offered(&mut app, &board, &mut seen)); + assert!(written(&board).contains(&SVG), "{:?}", written(&board)); + // A clipboard an import replaced after the Copy is not offered. + let import = + "app.copy(); vc.run('clipboard.importSvg', {svg: ''});"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": import })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "Ran script"); + assert!(!offered(&mut app, &board, &mut seen)); + // An import in a batch that fails and is rolled back leaves the copied clipboard to be offered. + let rolled_back = "app.copy(); try { vc.run('command.batch', {commands: [{command: 'clipboard.importSvg', params: {svg: ''}}, {command: 'no.such', params: {}}]}); } \ + catch (e) {}"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": rolled_back })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "Ran script"); + assert!(offered(&mut app, &board, &mut seen)); + // A run that copies and then fails leaves the clipboard and what other apps were offered alone. + let fails = "app.cut(); throw new Error('stop');"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": fails })).unwrap().unwrap(); + finish(&mut app); + assert!(!offered(&mut app, &board, &mut seen)); + assert_eq!(objects(&app), 1); + // A Copy with nothing selected copies nothing, and other apps keep what they were offered. + let empty = "vc.run('select.none', {}); app.copy();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": empty })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "Ran script"); + assert!(!offered(&mut app, &board, &mut seen)); + // A run that automation takes to its end at once offers its Copy too. + app.session.script_frames = false; + let reply = app.run("script.run", json!({ "source": copy, "name": "t.js" })).unwrap(); + assert_eq!(reply["copied"], true); + assert!(offered(&mut app, &board, &mut seen)); + assert!(written(&board).contains(&SVG), "{:?}", written(&board)); +} + /// The texts the open warning draws, after a few frames of the whole app. fn dialog_texts(app: &mut VectorcraftApp) -> Vec { let ctx = app.ui_ctx.clone().unwrap(); diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 38efb55e1f..87ac38b1d1 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -628,6 +628,33 @@ fn copy_notes_are_counted_and_kept_in_order() { assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None)); } +/// A script whose Copy leaves a note and whose commands take a recording past its limit keeps the +/// limit on the status bar once the Copy's formats are written. +#[test] +fn a_copy_note_does_not_replace_a_scripts_recording_limit() { + let (mut app, board) = app_with_worker(); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, crate::panels::actions::START_RECORDING, json!({})); + for _ in 0..vectorcraft_engine::script::actions::MAX_ACTION_STEPS - 1 { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + app.session.script_frames = true; + let source = "vc.run('edit.copy', {}); vc.run('object.move', {dx: 1, dy: 0}); vc.run('object.move', {dx: 1, dy: 0});"; + run(&mut app, "script.run", json!({"source": source, "name": "t.js"})); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(&mut app); + } + assert!(!app.session.script_running(), "the script ends"); + let limit = "the action already has 10,000 steps"; + assert_eq!(app.ui.status, limit, "the status bar names the limit as the run ends"); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the Copy's note does not replace the limit"); +} + /// A message shown while a Copy's formats are made on the worker stays: the formats are written /// once they are ready, and their note does not replace the newer message. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f52e523833..add7b485ef 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3072,7 +3072,7 @@ through `$`: `add` throws a `RangeError`), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset - `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` + `file.newPresets` lists for that profile (a saved preset of the same name is not used), and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` starts with the defaults that page gives. Assigning one of its settings checks the value's kind: a value of the setting's enumeration, a finite number, a `title` string, `true` or `false` for `documentBleedLink`, or an array @@ -3128,13 +3128,13 @@ through `$`: or placed document already has is not applied, and its document stays in the back), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, - `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` - (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is already in - the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move` on the - copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same + `move(relativeObject, insertionLocation?)`, `remove()`, `zOrder(method)`, `translate`, `rotate`, `resize` and + `transform` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is + already in the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move` + on the copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's, a group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` - directly above the relative object and `PLACEAFTER` directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the + directly above the relative object and `PLACEAFTER` directly below it. A move that leaves the object where it is runs no command. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the @@ -3169,8 +3169,37 @@ through `$`: `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. When a placed image is embedded, an object a script holds for it is stale, and the next read gives a new `RasterItem` object. The enumerations `ElementPlacement`, `ZOrderMethod`, `BlendModes`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, - `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and + `Transformation`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. + `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?, + transformStrokePatterns?)` moves the object by the offsets in points, `rotate(angle, changePositions?, + changeFillPatterns?, changeFillGradients?, changeStrokePattern?, rotateAbout?)` turns it by `angle` degrees, + `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?, + changeLineWidths?, scaleAbout?)` scales it by the percentages, and `transform(transformationMatrix, changePositions?, + changeFillPatterns?, changeFillGradients?, changeStrokePattern?, changeLineWidths?, transformAbout?)` applies a + `Matrix` record (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each one runs `object.transform` on the + object. VectorCraft's own rules for them: offsets, angles and matrices have Y up whatever `app.coordinateSystem` is, + so `translate(0, 10)` moves the object up and a positive angle turns it counterclockwise. `rotate`, `resize` and + `transform` act about the center of the geometric bounds unless a `Transformation` value names another point of + them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. Positions and gradients + default to `true` and patterns to the Transform Pattern Tiles preference. Fill and stroke patterns with different + values, and gradients different from positions, counting the defaults of arguments left out, throw an error that + says they are not available yet. + `changeLineWidths` is 100 (the default; stroke weights stay) or the transformation's own scale in percent, the + square root of the area it scales by (stroke weights and effects scale with it). `resize` on a path also takes any + other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`, + at most 1000 points). On a member of a compound path or compound shape, the compound's stroke weight follows the + percent through `stroke.set`; when the percent is the resize's own scale, the member's own strokes and effects also + scale with it. `transform` with `changeLineWidths` at the matrix's own scale sets the compound's stroke weight the + same way, which changes the stroke every member of the compound shows. Another value throws the same + error. A locked object, one inside a locked layer or group, a + group that holds one, a hidden object or one inside a hidden layer or group, and an object on a locked artboard + throw `cannot transform locked objects`, `cannot transform hidden objects` or + `cannot transform objects on a locked artboard`. A scale of 0, a + matrix whose determinant is 0 and a transformation that would take the object past the canvas also throw an error. + In each of these cases the document does not change. A call that changes nothing runs no command. `rotate`, + `resize` and `transform` on a path with no points leave its geometry as it is and set only the stroke weight the + call asks for. `pageItems` lists the art topmost first, as the example on [CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`, and a document's `selection` lists the selected objects in the same order, whatever order they were selected or @@ -3226,7 +3255,7 @@ through `$`: `..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined` and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the run until the run ends, with or without the call. Some members the Application, - Document and PageItem pages list, such as `Document.swatches`, `PageItem.isIsolated`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.swatches`, `PageItem.isIsolated`, `PageItem.bringInPerspective` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the @@ -3307,6 +3336,45 @@ through `$`: gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel alignment. +- `app.preferences` (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/) has `getBooleanPreference(key)`, + `getIntegerPreference(key)`, `getRealPreference(key)`, `getStringPreference(key)`, the four matching `set…(key, + value)` and `removePreference(key)`. The key `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`. + Setting it to `true` or removing it turns the warning on. VectorCraft's own rule: setting it to `false` while the + warning is on shows a confirm, with No as its default, and turns the warning off only after Yes; with nobody to ask + (a run with `script.run` outside the app, or a call from a callback of a built-in function) it throws an error that + names `ShowExternalJSXWarning` and changes nothing, and `answers` cannot answer that confirm. Other keys are + stored with the preferences under `scriptPreferences`, with the type they were set as, and are kept across runs and restarts; a run that fails or is stopped puts them back. + VectorCraft's own rules: a key that was never set reads as `false`, `0`, `0` or `""`; a getter of another type + converts the value as `Boolean`, `Number` and `String` do, and `getIntegerPreference` drops the fraction and gives + `0` for a value that is not a number. A key has a `length` of 1 to 256 UTF-16 code units (a character outside + the Basic Multilingual Plane, such as an emoji, counts 2) and no control characters, a string value at most + 65,536 bytes, and the store at most 4,096 keys and 1,048,576 bytes (each value that is not a string counts 8); + `setIntegerPreference` takes a whole number within ±2^53 and `setRealPreference` a finite number. A value of the + wrong type or past a limit throws an error and stores nothing, and removing a key that is not stored does nothing. +- `app.getIdentityMatrix()`, `getTranslationMatrix(deltaX?, deltaY?)` (points), `getScaleMatrix(scaleX?, scaleY?)` + (percent), `getRotationMatrix(angle?)` (degrees, counterclockwise), `concatenateMatrix(matrix, secondMatrix)`, + `concatenateTranslationMatrix(matrix, deltaX?, deltaY?)`, `concatenateScaleMatrix(matrix, scaleX?, scaleY?)`, + `concatenateRotationMatrix(matrix, angle?)`, `invertMatrix(matrix)`, `isEqualMatrix(matrix, secondMatrix)` and + `isSingularMatrix(matrix)` work on `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/): plain + objects with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX`, `mValueTY` and `typename` `"Matrix"`. Each + function other than `isEqualMatrix` and `isSingularMatrix` gives a new record; those two give `true` or `false`. + No function changes the records passed to it. A record maps `(x, y)` to + `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own + rules: `concatenateMatrix(m, n)` applies `m` and then `n`, and the other `concatenate…` functions apply the record + and then the transformation they make; a left-out move or angle is 0, a left-out `scaleX` is 100 and a left-out + `scaleY` is `scaleX`; quarter turns are exact; each value `concatenateMatrix` gives is its exact sum of products + rounded once; a matrix whose determinant is 0 is singular, and `invertMatrix` of one + throws; `isEqualMatrix` compares the six values exactly. A value that is not a finite number throws a `TypeError`, + and a result too large for a number throws a `RangeError`. +- `app.copy()`, `app.cut()` and `app.paste()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) run + `edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. With nothing selected + `copy` and `cut` do nothing, and with the clipboard empty `paste` does nothing; `paste` with no document open throws + `No active document`. VectorCraft's own rules: `paste` takes what VectorCraft's clipboard holds (a Copy or Cut in + VectorCraft, or what the last Paste took from another app), not art another app copied since. A run that finishes + after a Copy or Cut (these functions, or `edit.copy`, `edit.cut`, `artboard.copy` or `artboard.cut` through + `vc.run`, also inside `command.batch` or an action), with the clipboard still holding what the Copy or Cut put + there and not what a `clipboard.import…` command put there since, has `copied: true` in its report, and the desktop + app then offers the clipboard to other apps as Edit › Copy does. - `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. When the format is selected by a `.vctemplate` path, `saveAs` writes a template copy and leaves the document's file and saved state unchanged. @@ -3561,11 +3629,10 @@ through `$`: members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to - 500), `strokeDashes`, `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)` - (counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The + 500), `strokeDashes` and `strokeDashOffset`, and takes the page item transforms above. The geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through - `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the + `object.setOverprint`. Changes to the points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, edits the points of another path, or reads the points of another path in the same Objects on Path group, and when the script ends; @@ -4035,7 +4102,9 @@ while the run went on keeps that change. On an uncaught error, a limit or `scrip session go back to their state before the run. A script can write files through the commands it runs, such as export commands. A file written before the run failed stays on disk, and the error names it. A run from the menu shows a warning first, unless you ticked Do not show this warning again or set the preference -`showExternalScriptWarning` to false. +`showExternalScriptWarning` to false. A script asks for it with +`app.preferences.setBooleanPreference("ShowExternalJSXWarning", false)`, which turns the warning off only after you +answer Yes. While a script runs, every other command that changes anything ends with the error `a script is running: stop it or wait for it to finish`. MCP reports that error as JSON-RPC error `-32003`. `script.stop {}` stops the run and @@ -4120,7 +4189,8 @@ In the app, a script past the growth limit stops at a question to continue or to `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`, with -`unhandledRejections` and `unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In +`copied: true` after a Copy or Cut whose art the clipboard still holds, and `unhandledRejections` and +`unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`, with `prints`, the number of jobs the run prepared for a printer, when it prepared any. The report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when @@ -11015,7 +11085,9 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes ## New Document -`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` +`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`, a saved preset before a +built-in one of the same name; with `presetCategory`, a category of `file.newPresets`, the preset of that name in +that category), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are @@ -13438,6 +13510,9 @@ prints at most that many pages, copies counted; with more, `file.print` composes its raster effects are rendered. In the app, `file.print` with no params opens the Print dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. +In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has +applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. +The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b0ecf56b44..a83f1b25e6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1115,7 +1115,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`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`, `crates/engine/src/tests/script_dom.rs`. + - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.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: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `Document.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`.