From 1b13f0ad1eb4fece1a5910fd6d7f8469ebc6c10f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:36:01 -0800 Subject: [PATCH 01/24] Scripts: app gives scripts preferences, matrices and the clipboard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `app.preferences` reads, stores and removes values by key with the type they were set as. Keys that are not VectorCraft preferences are kept with the preferences under `scriptPreferences`, so they last across runs and restarts, and a failed or stopped run puts them back. Keys, values and the store have size limits, a setter refuses a value of the wrong type, and two windows that set different keys keep both when the preferences file is saved. - `ShowExternalJSXWarning` is the warning before a picked script runs. Setting it to true, or removing it, turns the warning on. Setting it to false opens a confirm with No as its default and turns the warning off only after Yes; a run that cannot show a dialog throws and changes nothing. This confirm is VectorCraft's own rule. - `app.getIdentityMatrix`, the `get…Matrix` and `concatenate…Matrix` functions, `invertMatrix`, `isEqualMatrix` and `isSingularMatrix` work on plain `Matrix` records and never change the records passed in. - `app.copy`, `app.cut` and `app.paste` run `edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. Docs: docs/mcp.md, docs/target-app-parity.md. --- apps/vectorcraft/src/prefs.rs | 107 ++++- crates/engine/src/lib.rs | 2 +- crates/engine/src/prefs.rs | 16 + crates/engine/src/script/dialogs.rs | 40 +- crates/engine/src/script/dom.rs | 8 + crates/engine/src/script/dom/clipboard.rs | 49 +++ crates/engine/src/script/dom/matrix.rs | 269 ++++++++++++ crates/engine/src/script/dom/preferences.rs | 258 +++++++++++ crates/engine/src/script/mod.rs | 39 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom_prefs.rs | 452 ++++++++++++++++++++ crates/ui-egui/src/dialogs/script_run.rs | 10 +- docs/mcp.md | 35 +- docs/target-app-parity.md | 1 + 14 files changed, 1264 insertions(+), 23 deletions(-) create mode 100644 crates/engine/src/script/dom/clipboard.rs create mode 100644 crates/engine/src/script/dom/matrix.rs create mode 100644 crates/engine/src/script/dom/preferences.rs create mode 100644 crates/engine/src/tests/script_dom_prefs.rs diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index c57ab6b582..ae440e87dc 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -201,18 +201,7 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se if key == "engine_prefs" && let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key)) { - let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect(); - for name in names { - match (was.get(name), now.get(name)) { - (a, b) if a == b => {} - (_, Some(v)) => { - theirs.insert(name.clone(), v.clone()); - } - (_, None) => { - theirs.remove(name); - } - } - } + put_changes(was, now, theirs, MERGED_BY_KEY); continue; } match now { @@ -245,6 +234,61 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se Value::Object(out) } +/// Engine preferences that hold values set one key at a time (`app.preferences` in scripts): a +/// save merges them key by key, so two windows that set different keys keep both. +const MERGED_BY_KEY: &[&str] = &["scriptPreferences"]; + +/// Whether `store`, a saved `scriptPreferences`, reads as a store within the limits +/// `app.preferences` keeps; one that does not read is not within them. +fn script_store_fits(store: &serde_json::Map) -> bool { + serde_json::from_value::>(serde_json::Value::Object(store.clone())) + .is_ok_and(|s| vectorcraft_engine::script::dom::preferences::within_limits(&s)) +} + +/// `theirs` with each entry that changed from `was` to `now` set to `now`'s value, or removed when +/// `now` lacks it. The entries named in `by_key` that are maps (or missing) are merged key by key. +fn put_changes( + was: &serde_json::Map, + now: &serde_json::Map, + theirs: &mut serde_json::Map, + by_key: &[&str], +) { + use serde_json::{Map, Value}; + let empty = Map::new(); + let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect(); + for name in names { + let (a, b) = (was.get(name), now.get(name)); + if a == b { + continue; + } + if by_key.contains(&name.as_str()) + && let (Some(a), Some(b)) = (a.map_or(Some(&empty), Value::as_object), b.map_or(Some(&empty), Value::as_object)) + { + let mut inner = match theirs.remove(name) { + Some(Value::Object(m)) => m, + _ => Map::new(), + }; + put_changes(a, b, &mut inner, &[]); + // A merge past the store's limits saves this window's store as it is. + if !script_store_fits(&inner) { + inner = b.clone(); + } + if !inner.is_empty() { + theirs.insert(name.clone(), Value::Object(inner)); + } + continue; + } + match b { + Some(v) => { + theirs.insert(name.clone(), v.clone()); + } + None => { + theirs.remove(name); + } + } + } +} + /// Point the saved current Actions set (`action_set`) at the same set in the merged /// `action_sets` when the merge took the index from one window and the list from another /// ([`find_action_set`]). With no such set, no set is current. @@ -365,6 +409,45 @@ mod tests { assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}})); } + #[test] + fn script_preference_keys_from_two_windows_are_both_saved() { + let base = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": true}, "gone": {"integer": 1}}}}); + // The other window set `b`; this one set `c`, changed `a` and removed `gone`. + let on_disk = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": true}, "b": {"string": "x"}, "gone": {"integer": 1}}}}); + let mine = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": false}, "c": {"real": 0.5}}}}); + let want = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": false}, "b": {"string": "x"}, "c": {"real": 0.5}}}}); + assert_eq!(merge_changes(&base, &mine, on_disk), want); + // A window that started with no keys and removed none keeps the other window's. + let base = json!({"engine_prefs": {}}); + let on_disk = json!({"engine_prefs": {"scriptPreferences": {"b": {"string": "x"}}}}); + let mine = json!({"engine_prefs": {"scriptPreferences": {"c": {"real": 0.5}}}}); + let want = json!({"engine_prefs": {"scriptPreferences": {"b": {"string": "x"}, "c": {"real": 0.5}}}}); + assert_eq!(merge_changes(&base, &mine, on_disk), want); + // Removing the last key of either window leaves the field out. + let base = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": true}}}}); + let on_disk = base.clone(); + let mine = json!({"engine_prefs": {}}); + assert_eq!(merge_changes(&base, &mine, on_disk), json!({"engine_prefs": {}})); + } + + #[test] + fn script_preference_keys_merged_past_the_limits_save_this_windows_keys() { + use vectorcraft_engine::script::dom::preferences::MAX_KEYS; + let keys = |prefix: &str| -> serde_json::Map { + (0..MAX_KEYS).map(|i| (format!("{prefix}{i}"), json!({"boolean": true}))).collect() + }; + // Each window added a full store of its own keys. + let base = json!({"engine_prefs": {}}); + let on_disk = json!({"engine_prefs": {"scriptPreferences": keys("theirs")}}); + let mine = json!({"engine_prefs": {"scriptPreferences": keys("mine")}}); + assert_eq!(merge_changes(&base, &mine, on_disk), mine); + // A merge within the limits keeps both windows' keys. + let on_disk = json!({"engine_prefs": {"scriptPreferences": {"theirs": {"boolean": true}}}}); + let mine = json!({"engine_prefs": {"scriptPreferences": {"mine": {"integer": 2}}}}); + let want = json!({"engine_prefs": {"scriptPreferences": {"mine": {"integer": 2}, "theirs": {"boolean": true}}}}); + assert_eq!(merge_changes(&base, &mine, on_disk), want); + } + #[test] fn a_setting_both_windows_changed_takes_the_last_saved() { let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}}); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..089b33a038 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -439,7 +439,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::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 2e0d0f9fe4..439560dfef 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -438,6 +438,21 @@ 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. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScriptPreference { + Boolean(bool), + Integer(i64), + Real(f64), + String(String), } /// The default Hold Shortcut Delay, in seconds (VectorCraft's own value). @@ -642,6 +657,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 a674396f4b..1687d1c11a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -184,6 +184,13 @@ fn answer(a: &Value) -> 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 { @@ -193,6 +200,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>, @@ -208,6 +219,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), @@ -246,14 +259,39 @@ 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 + } + + /// 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 55073e70ec..dd7619ee63 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,10 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod clipboard; +mod matrix; +pub mod preferences; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -1713,6 +1717,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getIsFileOpen", method(l, app_is_open)), ]); application.push(later(l, "Application", "beep")); + application.extend(preferences::app_members()); + application.extend(matrix::app_members(l)); + application.extend(clipboard::app_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -1723,6 +1730,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), }; let mut classes = vec![ class("Application", None, application, None), + preferences::class(l), preset, class( "Documents", diff --git a/crates/engine/src/script/dom/clipboard.rs b/crates/engine/src/script/dom/clipboard.rs new file mode 100644 index 0000000000..7b07587999 --- /dev/null +++ b/crates/engine/src/script/dom/clipboard.rs @@ -0,0 +1,49 @@ +//! `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`. + +use serde_json::json; +use vectorcraft_js::{Data, HostError, HostMember}; + +use super::{Answer, Host, Link, NO_ACTIVE_DOCUMENT, command, method, named}; + +/// The clipboard functions of `Application`. +pub(super) fn app_members(link: &Link) -> Vec<(String, HostMember)> { + named(vec![("copy", method(link, copy)), ("cut", method(link, cut)), ("paste", method(link, paste))]) +} + +/// 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..71065256fb --- /dev/null +++ b/crates/engine/src/script/dom/matrix.rs @@ -0,0 +1,269 @@ +//! 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 gives a new record and leaves the records passed to it as +//! they were. +//! +//! 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, HostMember}; + +use super::{Answer, Host, Link, arg, method, named, num, text}; + +/// A matrix's six values: `[a, b, c, d, tx, ty]`. +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<(String, HostMember)> { + let l = link; + named(vec![ + ("getIdentityMatrix", method(l, identity)), + ("getTranslationMatrix", method(l, translation)), + ("getScaleMatrix", method(l, scale)), + ("getRotationMatrix", method(l, rotation)), + ("concatenateMatrix", method(l, concatenate)), + ("concatenateTranslationMatrix", method(l, concatenate_translation)), + ("concatenateScaleMatrix", method(l, concatenate_scale)), + ("concatenateRotationMatrix", method(l, concatenate_rotation)), + ("invertMatrix", method(l, invert)), + ("isEqualMatrix", method(l, is_equal)), + ("isSingularMatrix", method(l, is_singular)), + ]) +} + +/// 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`. +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`. +fn then(m: Matrix, n: Matrix) -> Matrix { + let [a, b, c, d, e, f] = m; + let [a2, b2, c2, d2, e2, f2] = n; + [a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2] +} + +fn translate(dx: f64, dy: f64) -> Matrix { + [1.0, 0.0, 0.0, 1.0, dx, dy] +} + +/// A scale by `sx` and `sy` percent. +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. +fn rotate(degrees: f64) -> Matrix { + let turn = degrees.rem_euclid(360.0); + let (sin, cos) = match turn { + 0.0 => (0.0, 1.0), + 90.0 => (1.0, 0.0), + 180.0 => (0.0, -1.0), + 270.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 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]) +} + +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/preferences.rs b/crates/engine/src/script/dom/preferences.rs new file mode 100644 index 0000000000..064f4fa39d --- /dev/null +++ b/crates/engine/src/script/dom/preferences.rs @@ -0,0 +1,258 @@ +//! `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, Host, Link, arg, method, named, num, text, 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<(String, HostMember)> { + named(vec![("preferences", HostMember::Get(std::rc::Rc::new(|_| Ok(host_ref("Preferences", &[])))))]) +} + +/// The `Preferences` class. +pub(super) fn class(link: &Link) -> HostClass { + let l = link; + HostClass { + name: "Preferences".into(), + parent: None, + members: named(vec![ + ("typename", typename_of("Preferences")), + ("getBooleanPreference", method(l, |h, a| get(h, a, Kind::Boolean))), + ("getIntegerPreference", method(l, |h, a| get(h, a, Kind::Integer))), + ("getRealPreference", method(l, |h, a| get(h, a, Kind::Real))), + ("getStringPreference", method(l, |h, a| get(h, a, Kind::String))), + ("setBooleanPreference", method(l, |h, a| set(h, a, Kind::Boolean))), + ("setIntegerPreference", method(l, |h, a| set(h, a, Kind::Integer))), + ("setRealPreference", method(l, |h, a| set(h, a, Kind::Real))), + ("setStringPreference", method(l, |h, a| set(h, a, Kind::String))), + ("removePreference", method(l, remove)), + ]), + index: None, + construct: 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 1 to {MAX_KEY_UNITS} characters"))); + } + 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. +fn text_number(t: &str) -> f64 { + let t = t.trim_matches(|c: char| c.is_whitespace() || 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 { + let digits = t.get(2..).unwrap_or(""); + let whole = digits.chars().try_fold(0.0_f64, |n, c| c.to_digit(radix).map(|d| n * f64::from(radix) + f64::from(d))); + return whole.filter(|_| !digits.is_empty()).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, + } +} + +#[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/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..33b19dd046 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -542,19 +542,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 { @@ -1840,10 +1856,19 @@ impl Session { /// 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 file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..d52d8ae202 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_prefs; mod script_engines; mod script_folder; mod script_include; 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..12edc6d3c8 --- /dev/null +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -0,0 +1,452 @@ +//! 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.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 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(' '));", + ); + 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 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"), + ("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 characters 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)))); +} + +#[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 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()); +} diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..9f3d94535d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -28,6 +28,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; @@ -259,10 +260,17 @@ fn answer_button(ui: &mut egui::Ui, label: &str, default: bool) -> bool { if default { widgets::primary_button_enabled(ui, label, true).clicked() } else { widgets::secondary_button(ui, label).clicked() } } +/// 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(d: &Dialog) -> String { + let message = d.str("message"); + if message == WARNING_OFF_QUESTION { crate::i18n::msg(&message) } else { message } +} + fn notice_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { let t = Tokens::get(ui.ctx()); let kind = d.str("kind"); - let message = shown_text(&d.str("message"), true); + let message = shown_text(¬ice_message(d), true); ui.horizontal_top(|ui| { if d.bool("errorIcon") { ui.label(egui::RichText::new("!").font(theme::semibold(22.0)).color(t.error)); diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..b4d8fc9c05 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2676,6 +2676,37 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `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 1 to 256 characters 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 gives a new record and leaves the ones passed to it unchanged. 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; 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`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -2790,7 +2821,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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..837e8ef276 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,7 @@ 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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/), 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: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 88a6ed5fe8815c439f8e0e4e0b50e49d59a82d26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:48:12 -0800 Subject: [PATCH 02/24] Scripts: a run's Copy or Cut is offered to other apps when the run ends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A script that copies with app.copy() or app.cut(), or with edit.copy, edit.cut, artboard.copy or artboard.cut through vc.run (also inside command.batch or an action), and ends with the clipboard still holding what it copied, now has copied: true in its report. The desktop app then offers the clipboard to other apps as Edit › Copy does, for runs in the app and for runs automation takes to their end at once. - Session counts each Copy or Cut that fills the clipboard and marks the clipboard as holding a copy; a clipboard.import... command clears the mark. A Copy that leaves the clipboard empty is not counted. - command.batch, a plugin call and a script command that fails put the count and the mark back with the clipboard, so a rolled-back Copy is not reported. - docs/mcp.md and the script.run params text describe copied. --- crates/engine/src/cmd/clipboard/flavours.rs | 11 ++++ crates/engine/src/cmd/edit.rs | 1 + crates/engine/src/cmd/fileio/batch.rs | 2 + crates/engine/src/cmd/panelcmds.rs | 1 + crates/engine/src/cmd/plugin_call.rs | 6 +++ crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/lib.rs | 4 ++ crates/engine/src/script/dom/clipboard.rs | 5 +- crates/engine/src/script/mod.rs | 26 +++++++-- crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests/script_dom_prefs.rs | 22 ++++++++ crates/ui-egui/src/app/commands.rs | 11 ++-- crates/ui-egui/src/script_runs.rs | 7 ++- crates/ui-egui/src/tests/script_run.rs | 60 +++++++++++++++++++++ docs/mcp.md | 10 +++- 15 files changed, 157 insertions(+), 13 deletions(-) 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 bf9ff59c14..973330320b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1129,6 +1129,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 93670cefd9..e517f69ca4 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -21,6 +21,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { super::super::edit::settle_interaction(s)?; } 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(); @@ -43,6 +44,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/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 13f7051223..4db890c297 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -380,6 +380,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, @@ -553,6 +555,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(), @@ -577,6 +581,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/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..22608a78dc 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 .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's 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; setting hidden, createAlias and execute return 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, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (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 .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's 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; setting hidden, createAlias and execute return 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, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (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 089b33a038..35730579e1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -61,6 +61,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 diff --git a/crates/engine/src/script/dom/clipboard.rs b/crates/engine/src/script/dom/clipboard.rs index 7b07587999..874660a623 100644 --- a/crates/engine/src/script/dom/clipboard.rs +++ b/crates/engine/src/script/dom/clipboard.rs @@ -5,7 +5,10 @@ //! //! 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` 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, HostMember}; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 33b19dd046..54a114068b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -466,6 +466,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, @@ -590,6 +591,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, @@ -613,6 +615,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); @@ -650,7 +653,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, @@ -684,7 +688,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, @@ -734,8 +738,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; @@ -771,6 +777,8 @@ 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. + copied: Cell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, name: Arc, @@ -1257,6 +1265,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let save = (mutating && !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() }; + let copies = s.copies; crate::file_access::start_recording_writes(); // The command reads and writes only where the script's own files may, and the open documents' files. let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); @@ -1270,6 +1279,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value match r { Ok(v) => { note_ids(s); + if s.copies != copies { + host.copied.set(true); + } let (mut objects, mut bytes) = (0, 0); for st in &s.docs { match before.iter().find(|(uid, ..)| *uid == st.uid) { @@ -2054,6 +2066,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(), @@ -2315,6 +2328,13 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + // 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)); + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..6abd2a88dd 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -50,6 +50,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/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 12edc6d3c8..548f0cee07 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -450,3 +450,25 @@ fn copy_and_paste_run_as_one_undo_step() { 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); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..3bc5ecc26f 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -262,7 +262,7 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } - 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/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..64c8198d2e 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -35,10 +35,15 @@ pub fn poll(app: &mut VectorcraftApp) { script_run::settle_close(app); match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. - Ok(_) => { + Ok(report) => { if !crate::panels::actions::after_journaled_edit(app) { 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 { + app.publish_clipboard(false); + } } Err(e) => failed(app, e.to_string()), } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..d08e3bb4bb 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -640,6 +640,66 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { finish(&mut app); } +#[test] +fn a_scripts_copy_is_offered_to_other_apps_when_the_run_ends() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.clipboard_out = None; + 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!(app.clipboard_out.is_none(), "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!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains("'});"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": import })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "Ran script"); + assert!(app.clipboard_out.is_none()); + // 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!(app.clipboard_out.is_some()); + // A run that copies and then fails leaves the clipboard and what other apps were offered alone. + app.clipboard_out = None; + 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!(app.clipboard_out.is_none()); + 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!(app.clipboard_out.is_none()); + // 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!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains(" Date: Sat, 21 Nov 2026 20:03:34 -0800 Subject: [PATCH 03/24] Scripts: the confirm before the external script warning turns off is translated MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The question a run asks before a script sets ShowExternalJSXWarning to false has a row in every complete-message catalog, with a test that each of them translates it. - Russian and Ukrainian name File › Scripts › Other Script… as another script rather than another writing system. - A preference key's limit is stated as a length of 1 to 256 UTF-16 code units, the count the code checks, in the error and in docs/mcp.md; a test covers keys of characters outside the Basic Multilingual Plane. - The host name check lists Preferences, the matrix functions and app.copy, cut and paste; the preference setters and removePreference carry the checker's preferences id. --- crates/engine/src/script/dom/preferences.rs | 4 +++- crates/engine/src/tests/script_dom_prefs.rs | 6 +++++- .../tests/it/script_host_vs_scriptcheck.rs | 19 +++++++++++++++---- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 3 ++- crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 11 +++++++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 3 ++- crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 5 +++-- 30 files changed, 64 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs index 064f4fa39d..e1c25e387e 100644 --- a/crates/engine/src/script/dom/preferences.rs +++ b/crates/engine/src/script/dom/preferences.rs @@ -90,7 +90,9 @@ fn key_of(a: &[Data]) -> std::result::Result<&str, HostError> { } 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 1 to {MAX_KEY_UNITS} characters"))); + 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())); diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 548f0cee07..d8bb4dd77d 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -226,6 +226,8 @@ fn bad_arguments_throw_and_store_nothing() { ("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"), @@ -238,9 +240,11 @@ fn bad_arguments_throw_and_store_nothing() { } assert!(wrong.is_empty(), "{wrong:#?}"); assert!(s.prefs.script_preferences.is_empty()); - // A key of exactly 256 characters and a value of exactly the limit are taken. + // 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] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..df796262af 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,12 +37,19 @@ 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"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.saveAs` and `close` throw "not available yet". +/// documents; `Document.saveAs` and `close` throw "not available yet". 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 alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -75,14 +82,18 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + PageItems Preferences RulerUnits ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + "activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \ + concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents getIdentityMatrix \ + getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix invertMatrix isEqualMatrix isSingularMatrix paste \ + preferences selection typename", ), + ("Preferences.", "prototype"), + ("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"), ("DocumentPreset.", "prototype"), ( "DocumentPreset.prototype.", diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..88452d82bc 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6437,6 +6437,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 488df173c3..d9f3c1fa55 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5245,6 +5245,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 302ab6aa69..cd7f60bfcc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -63,6 +63,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 9482345f18..eed3f358c7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4830,6 +4830,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 434d0cc0b8..cd7b98a516 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2634,6 +2634,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 3f83e928e4..a22748a73d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4909,6 +4909,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 a4d85b23e8..e35bc338b3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5150,6 +5150,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 8f56486157..cf94949ece 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4891,6 +4891,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 e9509d9202..053d291e17 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7583,6 +7583,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 87f050ef0d..0253ef4aa3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5762,6 +5762,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 924d3d80b5..a5ef5115d8 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -63,6 +63,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 5f47e3f117..c3404d2489 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4968,6 +4968,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 9a1b5f6354..713ec6687d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5794,6 +5794,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 8eeacee621..ba497492da 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8463,6 +8463,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 57e0b8be10..d408d91cd9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5723,6 +5723,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 5ed5cdc3e0..b048ba2e6b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -63,6 +63,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 74029133dc..3e6d6901df 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5073,6 +5073,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 a1747af0b2..9c58266b69 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6112,6 +6112,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 ca0c8d5145..26be93af2d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2740,7 +2740,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 Маркеры исходящей касательной @@ -4944,6 +4944,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 c26474cf93..539e4538df 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4806,6 +4806,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 2ca2c76e03..d0495d9cdb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -717,6 +717,17 @@ fn compound_shape_no_area_warning_is_translated() { } } +/// 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::from_code(code).expect("registered"); + assert_ne!(message(lang, question), question, "{code}"); + } +} + /// The Save PDF dialog's Save Summary… button and `ui.pdfSummary.save`'s error when no such /// dialog is open. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..daf4e1c36e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4666,6 +4666,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 de3329ef10..5cbd4ef024 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2748,7 +2748,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 Маркери вихідної дотичної @@ -4952,6 +4952,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 675143a8d6..f2def46d53 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5430,6 +5430,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 57f6a4403b..a90fa539c6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5459,6 +5459,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 9834c17ea6..6df3af8b96 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2805,6 +2805,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/docs/mcp.md b/docs/mcp.md index b7ac4fd981..6ce10d6a50 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2697,8 +2697,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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 1 to 256 characters 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); + `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?)` From 9b2bfcd50f933fbf8a3dd7cea2aab3afa4b35175 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:04:21 -0800 Subject: [PATCH 04/24] Scripts: a Copy or Cut the run puts back is not reported, and matrices keep finite values - A command whose result cannot reach the script is put back, and the run counts its Copy or Cut only when the clipboard keeps it. Before, a put-back command.batch left its copy on the clipboard, and a put-back Cut after an earlier copy still gave the report copied: true. command.batch now has the clipboard saved before it, as edit.cut and action.batch do. - concatenateMatrix and the other concatenate functions sum each value past the range of a number when a product overflows or falls below the normal range next to another product, so [2^600, 2^600, 0, 1] then [2^600, 0, -2^600, 1] gives [0, 2^600, -2^600, 1] instead of a RangeError, and two products of 2^-1075 sum to 2^-1074. - getRotationMatrix and concatenateRotationMatrix reduce the angle with a remainder that keeps its sign, so -89.99999999999999 is not rounded to the quarter turn 270; -90, -180 and -270 stay exact. - docs/mcp.md says isEqualMatrix and isSingularMatrix give true or false, not a new record. --- crates/engine/src/script/dom/matrix.rs | 54 ++++++++++++++++---- crates/engine/src/script/mod.rs | 25 +++++----- crates/engine/src/tests/script_dom_prefs.rs | 55 +++++++++++++++++++++ docs/mcp.md | 3 +- 4 files changed, 116 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 71065256fb..9ee2fda4e6 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -2,8 +2,8 @@ //! and //! describe them. A matrix is a plain //! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the -//! `typename` `"Matrix"`; each function gives a new record and leaves the records passed to it as -//! they were. +//! `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. @@ -81,11 +81,33 @@ fn number(d: &Data, what: &str, default: f64) -> std::result::Result Matrix { let [a, b, c, d, e, f] = m; let [a2, b2, c2, d2, e2, f2] = n; - [a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2] + [ + 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 both products and their sum are finite, and a product below the range of +/// normal numbers is the only one that is not 0, the sum is taken as numbers are. 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. +fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { + let (p, q) = (x * y, z * w); + let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; + let alone = |a: f64, b: f64| a == 0.0 || b == 0.0; + let plain = p + q; + if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + return plain + t; + } + products_difference(x, y, 0.0 - z, w).add(Wide::of(t)).value() } fn translate(dx: f64, dy: f64) -> Matrix { @@ -97,14 +119,15 @@ 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. +/// 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. fn rotate(degrees: f64) -> Matrix { - let turn = degrees.rem_euclid(360.0); + let turn = degrees % 360.0; let (sin, cos) = match turn { 0.0 => (0.0, 1.0), - 90.0 => (1.0, 0.0), - 180.0 => (0.0, -1.0), - 270.0 => (-1.0, 0.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. @@ -194,6 +217,19 @@ impl Wide { Self::new(self.m / o.m, self.e.saturating_sub(o.e)) } + /// The sum. A number more than 2^60 times smaller than the other is past its precision. + fn add(self, o: Self) -> Self { + let (big, small) = if self.m == 0.0 || (o.m != 0.0 && o.e > self.e) { (o, self) } else { (self, o) }; + if small.m == 0.0 { + return big; + } + let gap = small.e.saturating_sub(big.e); + if gap < -60 { + return big; + } + Self::new(big.m + small.m * pow2(gap), 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); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index b914d3d57f..61f4f9d2ba 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -627,9 +627,10 @@ 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", "command.batch", "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 @@ -777,7 +778,8 @@ 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. + /// 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, @@ -1265,7 +1267,6 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let save = (mutating && !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() }; - let copies = s.copies; crate::file_access::start_recording_writes(); // The command reads and writes only where the script's own files may, and the open documents' files. let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); @@ -1279,9 +1280,6 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value match r { Ok(v) => { note_ids(s); - if s.copies != copies { - host.copied.set(true); - } let (mut objects, mut bytes) = (0, 0); for st in &s.docs { match before.iter().find(|(uid, ..)| *uid == st.uid) { @@ -1341,9 +1339,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); - let r = { + let (copies, r) = { let mut s = session.borrow_mut(); - step(&mut s, host, &id, ¶ms) + (s.copies, step(&mut s, host, &id, ¶ms)) }; // 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)) { @@ -1366,14 +1364,19 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( Ok(data) }); // A command whose result does not reach the script is put back, like one that failed. + 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); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index d8bb4dd77d..bac0981ccc 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -371,6 +371,36 @@ fn concatenation_applies_the_first_matrix_first() { ); } +#[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]))));", + ); + assert_eq!(out, vec![json!([0, true, true, 1, 0, true]), json!(true), json!(true), json!([0, -2, 3, 0, 0, 0])]); +} + +#[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(); @@ -476,3 +506,28 @@ fn only_copies_that_fill_the_clipboard_and_are_kept_are_counted() { 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); }", + ); + crate::script::TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["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/docs/mcp.md b/docs/mcp.md index 602e8187ab..aa65793760 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2715,7 +2715,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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 gives a new record and leaves the ones passed to it unchanged. A record maps `(x, y)` to + 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 From 41625f2c88c3b9d9d481e9182448a6ef80588886 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:36:31 -0800 Subject: [PATCH 05/24] Scripts: controlBounds takes in direction points, and a profile is read from the file checked - controlBounds gives the visible bounds together with the anchors and direction points of the paths in the object, taking the members its geometric bounds take. A blend, envelope or other live object gives its visible bounds. Before, every object gave its visible bounds. - A New Document profile is opened once. After the open, the roots in force must still allow its path and the path must still name the plain file that was opened, so a file put in its place between the checks and the open is not read. - Array methods visit every index of an object of a host class with an indexer, also past 4,096 indices. Before, a long range was listed from the object's properties, and its indexed elements were skipped. - An assignment to a document's selection checks each item against a set of the ids taken, so a long list is not searched once for each item. - A test shows that a failed selection assignment leaves the selection within the same run, and the link test removes its files when an assertion fails. --- crates/engine/src/cmd/newdoc.rs | 21 ++++++++++++++- crates/engine/src/cmd/recovery.rs | 2 +- crates/engine/src/script/dom.rs | 37 +++++++++++++++++++++++++-- crates/engine/src/store.rs | 10 ++++++++ crates/engine/src/tests/newdoc.rs | 13 +++++++--- crates/engine/src/tests/script_dom.rs | 30 ++++++++++++++++++++++ crates/js/src/builtins/array.rs | 4 ++- crates/js/src/host_tests.rs | 21 +++++++++++++++ docs/mcp.md | 3 ++- 9 files changed, 132 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 073de104cc..617a4f8b16 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -996,8 +996,15 @@ impl Session { Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), _ => {} } + // The file is opened once and checked after it is open: the roots in force must allow + // its path then, and the path must still name the plain file that was opened, so a file + // put in its place between the checks and the open is not read. + let opened = std::fs::File::open(&path).map_err(|e| e.to_string())?; crate::file_access::check_read(&file).map_err(denied)?; - crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + if !opened.metadata().is_ok_and(|m| m.is_file()) || !still_names(&opened, &path) { + return Err("not a plain file".to_string()); + } + crate::store::read_open_capped(opened, MAX_PROFILE_BYTES).map(Some) })?; let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs @@ -1010,6 +1017,18 @@ impl Session { } } +/// Whether `path` still names `file` ([`super::recovery::FolderStore::still_named`]). +#[cfg(not(target_arch = "wasm32"))] +fn still_names(file: &std::fs::File, path: &std::path::Path) -> bool { + super::recovery::FolderStore::still_named(file, path) +} + +/// The web build has no profile folder. +#[cfg(target_arch = "wasm32")] +fn still_names(_: &std::fs::File, _: &std::path::Path) -> bool { + false +} + /// The shipped profile of category `name`: the defaults, as a document of the category's first /// preset. fn shipped_profile(s: &Session, name: &str) -> Document { diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 193e86b600..7719496fac 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -420,7 +420,7 @@ 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 { + pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { #[cfg(unix)] { use std::os::unix::fs::MetadataExt as _; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9063f4d868..feb87f1a4c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1155,6 +1155,8 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + // The ids taken so far, so a long list is not searched once for each item. + let mut taken: std::collections::HashSet = std::collections::HashSet::with_capacity(list.len()); for d in list { let item = item_of(h, d)?; let ok = item.doc.uid == doc.uid @@ -1163,7 +1165,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { bounds(h, a, true) } +/// The visible bounds with the control points of the item's paths, or of the paths in it. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = with_doc(h, item.doc, |_, st| { + let controls = st.doc.node(item.id).and_then(control_points_box); + let r = vectorcraft_geom::union_opt(st.doc.bounds_of(&[item.id], true), controls) + .ok_or_else(|| HostError::Error("the object has no bounds".into()))?; + Ok((r, frame(st)?)) + })?; + Ok(f.bounds(h.dom.coords.get(), r)) +} + +/// The box of the anchors and direction points of every path in `n`, taking the members its +/// geometric bounds take: a clipping group or layer counts its clipping path only, a group or +/// compound path its editing children (not a Shaper group's source shapes), and a layer its +/// visible ones. +fn control_points_box(n: &vectorcraft_doc::Node) -> Option { + let union = |nodes: &mut dyn Iterator>| { + nodes.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, control_points_box(c))) + }; + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => union(&mut children.iter().take(1)), + NodeKind::Layer { .. } => union(&mut n.editing_children().iter().filter(|c| c.visible)), + NodeKind::Group { .. } | NodeKind::Compound { .. } => union(&mut n.editing_children().iter()), + // A live object (a blend, envelope, repeat and the like) draws other paths than the ones it + // holds, so it adds its visible bounds only. + _ => None, + } +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1908,7 +1941,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 9c555d82f7..784a7ae2d8 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -179,6 +179,16 @@ pub(crate) fn read_capped(path: &Path, max: u64) -> Result, String> { Ok(bytes) } +/// [`read_capped`] of a file already open. +pub(crate) fn read_open_capped(file: std::fs::File, max: u64) -> Result, String> { + let mut bytes = vec![]; + file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > max { + return Err(too_large(max)); + } + Ok(bytes) +} + /// The first `max + 1` bytes of `path` at most, so that a result longer than `max` shows the file is /// over its cap. fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 11330bac10..a5718deb1b 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -909,17 +909,24 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { #[cfg(unix)] #[test] fn a_profile_that_is_a_link_is_not_followed() { + /// Removes the folder and the file when dropped, also when an assertion fails. + struct Removed(std::path::PathBuf, std::path::PathBuf); + impl Drop for Removed { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + let _ = std::fs::remove_file(&self.1); + } + } let (mut s, dir) = with_profiles("link"); - s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); // A profile the folder held, moved out and linked back in. let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + let _removed = Removed(dir.clone(), outside.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); assert!(r.get("profile").is_none(), "{r}"); - let _ = std::fs::remove_file(&outside); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bb283e7dab..6d64b4a123 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,18 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +#[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(); @@ -229,6 +241,24 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +#[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 an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..3b6806ea20 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -113,7 +113,9 @@ fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { impl Indices { fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec) -> JsResult { let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None }; - if hi.saturating_sub(lo) > DENSE_SPAN { + // An object of a host class with an indexer has elements that are not properties, so each + // index of its range is visited. + if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() { let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add); if hi - lo > (present as u64).saturating_mul(8) { it.sparse = Some(it.gather(interp)?); diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..be840c6ddc 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -676,6 +676,27 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[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, 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 a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/docs/mcp.md b/docs/mcp.md index aa65793760..07ca7284f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2655,7 +2655,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds together with the anchors and direction points of the paths in the object; a clipping group counts + its clipping path only, and a blend, envelope or other live object gives its visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same From dc569257e1515b9bd36b167d858bbcf2fdb4afe4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:58:38 -0800 Subject: [PATCH 06/24] Scripts: a Copy the run puts back leaves the clipboard as it was edit.copy, artboard.copy and artboard.cut now have the clipboard saved before them, as edit.cut and command.batch do. Before, a Copy whose result could not reach the script was put back without its clipboard, so the copy stayed on the clipboard and the run reported copied: true. --- crates/engine/src/script/mod.rs | 2 +- crates/engine/src/tests/script_dom_prefs.rs | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 61f4f9d2ba..a6162b8b3c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -630,7 +630,7 @@ impl World { /// 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", "command.batch", "edit.cut"]; +const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "artboard.copy", "artboard.cut", "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 diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index bac0981ccc..dc2bacdff0 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -521,11 +521,13 @@ fn a_copy_or_cut_the_run_puts_back_is_not_reported() { 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.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); }", ); crate::script::TEST_RESULT_BYTES.with(|b| b.set(None)); let r = r.unwrap(); - assert_eq!(r["log"], json!(["RangeError", "RangeError"]), "{r}"); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", "RangeError"]), "{r}"); assert_eq!(r.get("copied"), None, "{r}"); assert_eq!(s.copies, copies); assert!(s.clipboard_copied); From 64e7f4e893fecf67946a9fa753073b46e76bb6df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:36:23 -0800 Subject: [PATCH 07/24] Scripts: move leaves art on a locked artboard, and a move to the same place runs nothing - move() on an object on a locked artboard throws "cannot move objects on a locked artboard", as remove() refuses to delete such an object. - move() works out the index node.move puts the object at, with art kept below the layer's ruler guides, before it decides whether the object moves. Before, moving the topmost art to the top of a layer with ruler guides ran node.move and added an undo step that changed nothing. --- crates/engine/src/script/dom.rs | 13 ++++++++++- crates/engine/src/tests/script_dom.rs | 31 +++++++++++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index feb87f1a4c..73f00536a2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1588,6 +1588,9 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { /// The error of `remove()` and `removeAll()` for an object on a locked artboard. const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +/// The error of `move` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD_MOVE: &str = "cannot move objects on a locked artboard"; + /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; @@ -1670,6 +1673,9 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let name = d.node(item.id).and_then(typename).unwrap_or("page item"); return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); } + if !copy && d.on_locked_artboard(item.id) { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD_MOVE}: {}", item.id.0))); + } Ok(Destination { parent, beside, how }) }) } @@ -1696,7 +1702,12 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul } (_, None) => count, }; - Ok::<_, HostError>(if clips { at.max(1) } else { at }) + let at = if clips { at.max(1) } else { at }; + // The index `node.move` puts the object at: art stays below the ruler guides. + let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let rest: Vec> = + d.children(Some(to.parent)).map(|c| c.iter().filter(|n| n.id != id).cloned().collect()).unwrap_or_default(); + Ok::<_, HostError>(crate::doc::Node::insert_index(&rest, at, node)) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 6d64b4a123..a1ea190b57 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1051,6 +1051,37 @@ fn remove_and_remove_all_refuse_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 objects on a locked artboard"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1].parent, ElementPlacement.PLACEATEND);"); + assert!(e.contains("cannot move objects on a locked artboard"), "{e}"); + assert_eq!(order(&s), before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 07ca7284f5..c480155de3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2662,7 +2662,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `edit.duplicate` and then `node.move` on the copy. 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 or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` - directly below it. An object of another document throws `Cross-document placement is not available`, and when + directly below it. `move` on an object on a locked artboard throws `cannot move objects on a locked artboard`, and a + move that leaves the object where it is runs no command. An object of another document throws `Cross-document + placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws From 0ce36a1b79aca3b8dff3d98fda51e634a22492c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:08:26 -0800 Subject: [PATCH 08/24] Scripts: a concatenated coefficient is rounded once, past a product's rounding When a product leaves the range of a number, concatenateMatrix now adds both products, the parts their rounding drops and the translation into an exact sum, and rounds that sum to the nearest number once. A coefficient just past the largest number gives RangeError, and a sum in the range of subnormal numbers rounds as the exact value does. --- crates/engine/src/script/dom/matrix.rs | 102 +++++++++++++++++--- crates/engine/src/tests/script_dom_prefs.rs | 32 +++++- 2 files changed, 121 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 9ee2fda4e6..2e8a4d7df7 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -96,18 +96,95 @@ fn then(m: Matrix, n: Matrix) -> Matrix { } /// `x·y + z·w + t`. When both products and their sum are finite, and a product below the range of -/// normal numbers is the only one that is not 0, the sum is taken as numbers are. Otherwise the +/// normal numbers is the only term that is not 0, the sum is taken as numbers are. 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. fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let (p, q) = (x * y, z * w); let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; - let alone = |a: f64, b: f64| a == 0.0 || b == 0.0; + let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { return plain + t; } - products_difference(x, y, 0.0 - z, w).add(Wide::of(t)).value() + // 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(Vec::with_capacity(10), grow); + nearest(&exact) +} + +/// `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: Vec, part: Wide) -> Vec { + let mut carry = part; + let mut kept = Vec::with_capacity(sums.len() + 1); + for h in sums { + let (sum, rest) = carry.two_sum(h); + if rest.m != 0.0 { + kept.push(rest); + } + carry = sum; + } + if carry.m != 0.0 { + kept.push(carry); + } + kept +} + +/// The sign of the exact sum of `sums`, `0.0 - v` and `offset`: 1, -1 or 0. +fn sign_past(sums: &[Wide], v: f64, offset: Wide) -> i32 { + let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums.to_vec(), grow); + match rest.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: &[Wide]) -> f64 { + let even = |v: f64| v.to_bits() & 1 == 0; + let mut v = sums.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 } fn translate(dx: f64, dy: f64) -> Matrix { @@ -217,17 +294,20 @@ impl Wide { Self::new(self.m / o.m, self.e.saturating_sub(o.e)) } - /// The sum. A number more than 2^60 times smaller than the other is past its precision. - fn add(self, o: Self) -> Self { + /// 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) }; - if small.m == 0.0 { - return big; - } let gap = small.e.saturating_sub(big.e); - if gap < -60 { - return big; + if small.m == 0.0 || gap < -110 { + return (big, small); } - Self::new(big.m + small.m * pow2(gap), big.e) + // 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. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index dc2bacdff0..fa01766d63 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -384,9 +384,37 @@ fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_numbe 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]))));", + 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) + ] ); - assert_eq!(out, vec![json!([0, true, true, 1, 0, true]), json!(true), json!(true), json!([0, -2, 3, 0, 0, 0])]); } #[test] From 35e27e2224040c5147f3d7f934d76c4e458c47a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 01:40:38 -0800 Subject: [PATCH 09/24] Scripts: PageItem translate, rotate, resize and transform move and reshape objects A page item's translate(deltaX, deltaY, ...), rotate(angle, ...), resize(scaleX, scaleY, ...) and transform(matrix, ...) run object.transform on the object inside the run's transaction, so the run keeps one undo step and the selection stays as it was. Offsets, angles and matrices have Y up, rotate, resize and transform act about the center of the geometric bounds or a Transformation point, and positions, patterns, gradients and line widths follow their arguments. Locked art, art on a locked artboard, a scale of 0, a singular matrix and a result past the canvas throw an error and change nothing, and a call that changes nothing runs no command. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 10 +- crates/engine/src/script/dom/matrix.rs | 12 +- crates/engine/src/script/dom/transform.rs | 216 +++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom.rs | 8 +- .../engine/src/tests/script_dom_transform.rs | 220 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 7 +- docs/mcp.md | 30 ++- docs/target-app-parity.md | 1 + 9 files changed, 484 insertions(+), 21 deletions(-) create mode 100644 crates/engine/src/script/dom/transform.rs create mode 100644 crates/engine/src/tests/script_dom_transform.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 73f00536a2..27a95eb321 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -41,6 +41,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod clipboard; mod matrix; pub mod preferences; +mod transform; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -1834,6 +1835,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"]), ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), @@ -1959,6 +1961,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("move", method(l, item_move)), ("remove", method(l, item_remove)), ("zOrder", method(l, item_z_order)), + ("translate", method(l, transform::translate)), + ("rotate", method(l, transform::rotate)), + ("resize", method(l, transform::resize)), + ("transform", method(l, transform::transform)), ]); page_item.extend( [ @@ -1976,10 +1982,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "wrapOffset", "wrapped", "bringInPerspective", - "resize", - "rotate", - "transform", - "translate", ] .into_iter() .map(|m| later(l, "PageItem", m)), diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 2e8a4d7df7..99b0a9aa05 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -24,7 +24,7 @@ use vectorcraft_js::{Data, HostError, HostMember}; use super::{Answer, Host, Link, arg, method, named, num, text}; /// A matrix's six values: `[a, b, c, d, tx, ty]`. -type Matrix = [f64; 6]; +pub(super) type Matrix = [f64; 6]; const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; @@ -59,7 +59,7 @@ fn record(m: Matrix) -> Answer { } /// The matrix argument `d`. -fn matrix(d: &Data, what: &str) -> std::result::Result { +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]; @@ -187,18 +187,18 @@ fn nearest(sums: &[Wide]) -> f64 { v } -fn translate(dx: f64, dy: f64) -> Matrix { +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. -fn scaled(sx: f64, sy: f64) -> Matrix { +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. -fn rotate(degrees: f64) -> Matrix { +pub(super) fn rotate(degrees: f64) -> Matrix { let turn = degrees % 360.0; let (sin, cos) = match turn { 0.0 => (0.0, 1.0), @@ -357,7 +357,7 @@ fn determinant(m: Matrix) -> Wide { products_difference(m[0], m[3], m[1], m[2]) } -fn singular(m: Matrix) -> bool { +pub(super) fn singular(m: Matrix) -> bool { determinant(m).m == 0.0 } diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs new file mode 100644 index 0000000000..2a3ff3ec6e --- /dev/null +++ b/crates/engine/src/script/dom/transform.rs @@ -0,0 +1,216 @@ +//! 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. +//! +//! 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. +//! - 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); any other value throws an error that says so. +//! - A locked object, one inside a locked layer or group, a group that holds one, 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, coordinate, edit_item, frame, number, 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"; + +/// 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 {} with different values are not available yet", 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`) scales stroke weights for the linear part `m` of a matrix. +fn line_widths(d: &Data, m: Matrix) -> std::result::Result { + let lw = match d { + Data::Undefined => return Ok(false), + d => number(d, "changeLineWidths")?, + }; + let own = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() * 100.0; + if (lw - own).abs() <= 1e-9 * own.max(1.0) { + return Ok((own - 100.0).abs() > 1e-9); + } + if (lw - 100.0).abs() <= 1e-9 { + return Ok(false); + } + Err(HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet"))) +} + +/// The point of `r` (document coordinates, Y down) that the `Transformation` value `d` names. +fn anchor(h: &Host, item: Item, r: Rect, d: &Data) -> std::result::Result { + let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + let name = match d { + Data::Undefined => return Ok(Point::new(cx, cy)), + Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""), + _ => "", + }; + Ok(match name { + "CENTER" => Point::new(cx, cy), + "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])))?, + _ => return Err(HostError::Type("the point to transform about must be a Transformation value".into())), + }) +} + +/// 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 page = Affine::new([a, 0.0 - b, 0.0 - c, d, tx, 0.0 - ty]); + Affine::translate(o.to_vec2()) * page * Affine::translate(-o.to_vec2()) +} + +/// Applies `m` (Y up) to the item `this` names, about the point `about` names (`None`: the matrix +/// acts as a move, which needs no point), with `opts`. +fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) -> Answer { + let item = this_item(h, a)?; + 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, on_locked, bounds, uses_pattern) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let mut locked = d.ancestry(item.id).is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); + let mut uses = false; + if let Some(n) = d.node(item.id) { + n.walk(&mut |c| { + locked |= c.locked; + uses |= vectorcraft_doc::pattern::uses_pattern(c, None); + }); + } + (locked, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses) + }); + if locked { + return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } + let o = match (about, bounds) { + (Some(d), Some(r)) => anchor(h, item, r, d)?, + (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), + (None, _) => Point::ORIGIN, + }; + let xf = on_page(m, o); + if let Some(r) = bounds.filter(|_| opts.objects) { + 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)]; + if corners.iter().map(|p| xf * *p).any(|p| !(p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD)) { + return Err(HostError::Range("the transformation would take the object past the canvas".into())); + } + } + let c = xf.as_coeffs(); + let identity = c.iter().zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]).all(|(v, i)| (v - i).abs() <= 1e-12); + let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; + 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)?; + } + 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 => coordinate(d, what), + }; + let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?); + let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"]; + let opts = options(h, a, 3, names)?; + apply(h, a, matrix::translate(dx, dy), None, &opts) +} + +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, a, matrix::rotate(angle), Some(arg(a, 6)), &opts) +} + +/// `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)?; + opts.strokes = line_widths(arg(a, 7), m)?; + apply(h, a, m, Some(arg(a, 8)), &opts) +} + +/// `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)?; + opts.strokes = line_widths(arg(a, 6), m)?; + apply(h, a, m, Some(arg(a, 7)), &opts) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c66897c70b..600e82a7be 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -174,6 +174,7 @@ mod script_dialogs; mod script_dollar; mod script_dom; mod script_dom_prefs; +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 a1ea190b57..10de309e4d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -700,9 +700,11 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].bringInPerspective(0, 0);", + ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); 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..1be3046209 --- /dev/null +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -0,0 +1,220 @@ +//! 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 and a 50 × 50 pt one above it. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + (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:?}"); + // A line width that is neither 100 nor the scale itself is refused. + 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);", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[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"), + ("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"), + ] { + 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 df796262af..9250be140c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -82,7 +82,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems Preferences RulerUnits ZOrderMethod", + PageItems Preferences RulerUnits Transformation ZOrderMethod", ), ("Application.", "prototype"), ( @@ -122,8 +122,8 @@ const INSIDE: &[(&str, &str)] = &[ "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer 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 tags= top top= transform \ - transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + position= remove resize rotate selected selected= sliced sliced= tags tags= top top= transform translate \ + typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), @@ -139,6 +139,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; diff --git a/docs/mcp.md b/docs/mcp.md index c480155de3..86737f7fdb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2657,8 +2657,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds together with the anchors and direction points of the paths in the object; a clipping group counts its clipping path only, and a blend, envelope or other live object gives its visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, - `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` - (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs + `move(relativeObject, insertionLocation?)`, `remove()`, `zOrder(method)`, `translate`, `rotate`, `resize` and + `transform` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. 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 or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` @@ -2671,8 +2671,28 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, - `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and - `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. + `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); another value throws the same + error. A locked object, one inside a locked layer or group, a group that holds one, and an object on a locked + artboard throw `cannot transform locked 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. VectorCraft's own rules: documents are listed in tab order, and page items in paint order from the bottom, with the objects inside groups and compound paths after their group and without layers and ruler guides. Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with @@ -2693,7 +2713,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.bringInPerspective` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 82cbdd078a..30df978ebe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,6 +1029,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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/), 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: 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 runs `object.transform` inside the run's transaction; 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: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 8330a6d8f0045d6b27ea6ee2b529658599ac3feb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:53:14 -0800 Subject: [PATCH 10/24] Scripts: transforms keep stroke-only and tiny changes, and edits keep the current layer - translate, rotate, resize and transform: a move of any size other than 0 runs; a changeLineWidths scale with changePositions false throws an error that says it is not available yet instead of changing nothing; the scale a matrix gives for changeLineWidths is taken past the range of a number; a transformation whose bounds reach past the canvas is kept when the transformed object itself stays inside it. - An edit of a page item puts back the current layer that selecting the item changed (layer.setCurrent), and an edit whose selection cannot be put back is undone with it. - addDocument starts from the built-in preset of the profile's category, not a saved preset with the same name (file.new and file.newPresets.save take presetCategory), and refuses previewMode OverprintPreview before it makes a document. - The values assigned to a run's DocumentPresets hold at most 64 MiB. - zOrder leaves out the ruler guides at the top of a layer when it checks whether the item is already at the front. - concatenateMatrix rounds a sum next to the largest number once, and getRealPreference rounds a 0x, 0o or 0b number once. - On Windows, the check that a New Document profile or recovery lock is still the file that was opened does not follow a link at its path. - JavaScript: new on a host constructor that gives a value other than an object throws a TypeError, and an array method on a host object that takes a class with an indexer during the call visits the rest of its elements. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 22 ++++-- crates/engine/src/cmd/recovery.rs | 16 +++- crates/engine/src/script/dom.rs | 78 ++++++++++++++++--- crates/engine/src/script/dom/matrix.rs | 24 +++++- crates/engine/src/script/dom/preferences.rs | 42 +++++++++- crates/engine/src/script/dom/transform.rs | 29 +++++-- crates/engine/src/tests/script_dom.rs | 53 +++++++++++++ crates/engine/src/tests/script_dom_prefs.rs | 25 +++++- .../engine/src/tests/script_dom_transform.rs | 48 +++++++++++- crates/js/src/builtins/array.rs | 4 +- crates/js/src/host_classes.rs | 5 +- crates/js/src/host_tests.rs | 33 ++++++++ crates/js/src/interp.rs | 5 ++ docs/mcp.md | 9 ++- 15 files changed, 356 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 99fdba20bc..c62ce14531 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 (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (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 (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (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 ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 617a4f8b16..8749fdfbdf 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -799,6 +799,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 { @@ -812,10 +824,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)); @@ -900,10 +909,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(p, C)?; preset.name = name.to_string(); let saved = &mut s.prefs.new_doc_presets; diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 7719496fac..c55ad05ca3 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -419,7 +419,8 @@ 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. + /// 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)] { @@ -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/script/dom.rs b/crates/engine/src/script/dom.rs index 27a95eb321..3ab67b8942 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -91,13 +91,16 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's /// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made with the bytes +/// they hold. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, presets: RefCell>>, + /// The bytes the values assigned to `presets` hold ([`MAX_PRESET_BYTES`]). + preset_bytes: Cell, } impl State { @@ -541,17 +544,31 @@ fn done_unless_refused(r: std::result::Result) -> std::result:: /// 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. +/// hidden or locked; the current layer, which selecting art changes, is put back too while it is +/// still a layer that can be edited. With `keep_selection`, `f`'s commands and the putting back are +/// kept together or put back together ([`atomically`]), so an error in putting the selection back +/// leaves the document as it was. fn on_doc( h: &Host, uid: u64, keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before) = { + if keep_selection { atomically(h, |h| on_doc_once(h, uid, true, f)) } else { on_doc_once(h, uid, false, f) } +} + +/// [`on_doc`] without its savepoint. +fn on_doc_once( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + let (index, active, before, layer) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - (index, s.active_index(), s.documents()[index].selection.clone()) + let st = &s.documents()[index]; + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.layer_rows.clone())) }; let switch = active != Some(index); if switch { @@ -567,6 +584,7 @@ fn on_doc( if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); } + restored = restored.and(restore_layer(h, uid, layer)); } // The document that was active is active again before any error is given: `f`'s error first, // then the selection's, then the switch back's. @@ -580,6 +598,30 @@ fn on_doc( Ok(v) } +/// Makes the layer `layer` gives (the current layer and the highlighted Layers panel rows before an +/// edit) current in the active document `uid` again, when selecting art made another layer current +/// and that layer is still one that can be edited. It runs `layer.setCurrent`, and `layer.highlight` +/// for rows that keep that layer current, so a replay of the run's commands ends with the same +/// current layer. A refused command changes nothing ([`done_unless_refused`]). +fn restore_layer(h: &Host, uid: u64, layer: (Option, Vec)) -> std::result::Result<(), HostError> { + let (was, rows) = layer; + let (back, keeps) = { + let s = h.session.borrow(); + let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) }; + let back = was.filter(|l| st.active_layer != Some(*l) && st.doc.node(*l).is_some_and(|n| n.is_layer()) && st.doc.is_editable(*l)); + let keeps = rows.last().is_some_and(|r| back.is_some() && st.doc.layer_containing(*r) == back); + (back, keeps) + }; + let Some(back) = back else { return Ok(()) }; + if !done_unless_refused(command(h, "layer.setCurrent", &json!({"id": back.0})))? { + return Ok(()); + } + if keeps && rows != [back] { + done_unless_refused(command(h, "layer.highlight", &json!({"ids": rows.iter().map(|r| r.0).collect::>()})))?; + } + Ok(()) +} + /// Runs `id` with `params` on the item's document, its selection kept. fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { on_doc(h, item.doc.uid, true, |h| command(h, id, params)) @@ -808,7 +850,10 @@ impl NewDoc<'_> { let mode = match d { Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel", - Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", + // Overprint Preview is a view of the whole app, which a script cannot turn on. + Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => { + return Err(HostError::Error("previewMode OverprintPreview is not available yet".into())); + } _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), }; p.insert("previewMode".into(), json!(mode)); @@ -917,9 +962,11 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())), } // The document starts from the first preset of the profile's category (Print: Letter). + // It is looked up in that category, so a saved preset of the same name is not used instead. let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); - if let Some(first) = first { + if let (Some(first), Some(category)) = (first, profile) { p.insert("preset".into(), json!(first.name)); + p.insert("presetCategory".into(), json!(category)); } p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); if let Some(m) = mode { @@ -964,6 +1011,9 @@ fn new_preset(h: &Host) -> Answer { /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; +/// The most bytes the values assigned to one run's `DocumentPreset` objects can hold together. +const MAX_PRESET_BYTES: u64 = 64 << 20; + /// The settings a `DocumentPreset` has, each a property a script reads and assigns. const PRESET_FIELDS: &[&str] = &[ "artboardLayout", @@ -1011,11 +1061,20 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let l = link.clone(); let set: HostFunction = Rc::new(move |a: Vec| { let h = current(&l)?; - let value = arg(&a, 1).clone(); - h.charge_call(16 + data_size(&value))?; + let size = data_size(arg(&a, 1)); + h.charge_call(16 + size)?; let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; + // The run's presets keep their values outside the script's heap: the value replaced is + // taken off what they hold before the new one is counted. + let old = fields.iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v)); + let held = h.dom.preset_bytes.get().saturating_sub(old).saturating_add(size); + if held > MAX_PRESET_BYTES { + return Err(HostError::Range(format!("a script's DocumentPresets can hold at most {} MiB of settings", MAX_PRESET_BYTES >> 20))); + } + h.dom.preset_bytes.set(held); + let value = arg(&a, 1).clone(); match fields.iter_mut().find(|(k, _)| k == key) { Some((_, v)) => *v = value, None => fields.push((key.to_string(), value)), @@ -1786,9 +1845,10 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } + // The ruler guides at the top of a layer stay above its art, as Arrange keeps them. let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); - let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); + let count = at.and_then(|(p, ..)| st.doc.children(p).map(|c| vectorcraft_doc::Node::guide_run_start(c))).unwrap_or(0); (at.map(|(_, i, _)| i), count) }); let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 99b0a9aa05..d2ca769913 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -96,15 +96,19 @@ fn then(m: Matrix, n: Matrix) -> Matrix { } /// `x·y + z·w + t`. When both products and their sum are finite, and a product below the range of -/// normal numbers is the only term that is not 0, the sum is taken as numbers are. 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. +/// normal numbers is the only term that is not 0, the sum is taken as numbers are, unless adding +/// `t` to the rounded sum of the products can come within a step of 2^1024. 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, and a sum is not taken past the largest number, +/// or kept below it, by a rounding on the way. fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let (p, q) = (x * y, z * w); let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; - if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + let near_overflow = |v: f64| v.abs() >= pow2(1023); + let overflow_safe = t == 0.0 || !(near_overflow(plain) || near_overflow(plain + t)); + if plain.is_finite() && overflow_safe && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { return plain + t; } // Each product is split into its rounded value and the part that rounding drops, both exact. @@ -357,6 +361,18 @@ 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 } diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs index e1c25e387e..31fa78682b 100644 --- a/crates/engine/src/script/dom/preferences.rs +++ b/crates/engine/src/script/dom/preferences.rs @@ -123,9 +123,7 @@ fn text_number(t: &str) -> f64 { _ => 0, }; if radix != 0 { - let digits = t.get(2..).unwrap_or(""); - let whole = digits.chars().try_fold(0.0_f64, |n, c| c.to_digit(radix).map(|d| n * f64::from(radix) + f64::from(d))); - return whole.filter(|_| !digits.is_empty()).unwrap_or(f64::NAN); + return radix_number(t.get(2..).unwrap_or(""), radix).unwrap_or(f64::NAN); } match t.strip_prefix(['+', '-']).unwrap_or(t) { "Infinity" => { @@ -140,6 +138,44 @@ fn text_number(t: &str) -> f64 { } } +/// 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 { diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 2a3ff3ec6e..3f056589b1 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -18,7 +18,8 @@ //! 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); any other value throws an error that says so. +//! with it, as Scale Strokes & Effects does); any other value, and a scale other than 100 with +//! positions left as they are, throws an error that says so. //! - A locked object, one inside a locked layer or group, a group that holds one, 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. @@ -78,8 +79,10 @@ fn line_widths(d: &Data, m: Matrix) -> std::result::Result { Data::Undefined => return Ok(false), d => number(d, "changeLineWidths")?, }; - let own = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() * 100.0; - if (lw - own).abs() <= 1e-9 * own.max(1.0) { + // 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. + let own = matrix::area_scale(m) * 100.0; + if own.is_finite() && (lw - own).abs() <= 1e-9 * own.max(1.0) { return Ok((own - 100.0).abs() > 1e-9); } if (lw - 100.0).abs() <= 1e-9 { @@ -118,6 +121,16 @@ fn on_page(m: Matrix, o: Point) -> Affine { Affine::translate(o.to_vec2()) * page * Affine::translate(-o.to_vec2()) } +/// 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. +fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool { + d.node(id).is_some_and(|n| { + let mut n = n.clone(); + n.transform(xf, false); + n.geometric_bounds_with(&d.symbol_boxes()).is_none_or(crate::sanity::rect_in_range) + }) +} + /// Applies `m` (Y up) to the item `this` names, about the point `about` names (`None`: the matrix /// acts as a move, which needs no point), with `opts`. fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) -> Answer { @@ -152,14 +165,20 @@ fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) (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 let Some(r) = bounds.filter(|_| opts.objects) { + // The transformed corners of the bounds hold the transformed object. When one of them is + // past the canvas, the transformed object itself is measured. 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)]; - if corners.iter().map(|p| xf * *p).any(|p| !(p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD)) { + let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD; + if !corners.iter().all(|p| inside(xf * *p)) && !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 = c.iter().zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]).all(|(v, i)| (v - i).abs() <= 1e-12); + let identity = xf == Affine::IDENTITY; let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; if changes { let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes}); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 10de309e4d..4603599578 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -856,6 +856,59 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "a refused preset makes 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 overprint_preview_is_refused_before_a_document_is_made() { + let mut s = Session::new(); + let e = + failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.OverprintPreview; app.documents.addDocument('Print', p);"); + assert!(e.contains("OverprintPreview is not available yet"), "{e}"); + assert!(s.documents().is_empty()); +} + +#[test] +fn document_presets_hold_a_limited_amount_of_data() { + let mut s = Session::new(); + // A 4 MiB string: replacing one preset's value does not add up, 17 presets holding it do. + let out = log( + &mut s, + "var t = 'x'; for (var k = 0; k < 22; 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!(4 << 20)]); + let e = failure( + &mut s, + "var t = 'x'; for (var k = 0; k < 22; k++) t += t;\ + for (var k = 0; k < 17; k++) { var p = new DocumentPreset(); p.title = t; }", + ); + assert!(e.contains("DocumentPresets can hold at most"), "{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(); diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index fa01766d63..d51b66336d 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -201,8 +201,15 @@ fn missing_keys_read_as_empty_values_and_getters_convert() { 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', 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, @@ -417,6 +424,22 @@ fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_numbe ); } +#[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(); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index 1be3046209..b861716b35 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -146,11 +146,55 @@ fn transforms_that_change_nothing_add_no_undo_step() { &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.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_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_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(); @@ -208,6 +252,8 @@ fn bad_arguments_throw_and_change_nothing() { ("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}"); diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 3b6806ea20..54b74464b9 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -174,8 +174,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 = Some(self.gather(interp)?); + self.sparse = if interp.host_indexer(self.obj)?.is_some() { None } else { Some(self.gather(interp)?) }; } let k = match &mut self.sparse { None if self.ascending => self.lo, diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..320207b958 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -145,13 +145,16 @@ impl Interp { if let Some(&id) = self.host_objects.get(&made) && is_made(&self.heap, &self.host_classes, id, &made) { - // An object of another class of the family becomes one of `class`. + // An object of another class of the family becomes one of `class`. Its indexer and the + // indices its prototypes hold can change with it, 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 be840c6ddc..b61e037171 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -676,6 +676,39 @@ 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, 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(), 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); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 63e6251dd7..fdfd0d5d79 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2407,6 +2407,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 (Some(callee), Value::Object(o)) = (f.as_object(), &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/docs/mcp.md b/docs/mcp.md index 86737f7fdb..b23b0eb569 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2636,11 +2636,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot columns for the other layouts), 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. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when - the preset it is given holds one of them with a value other than `null`, and makes no document. A + the preset it is given holds one of them with a value other than `null`, and makes no document; it does the same + for a `previewMode` of `DocumentPreviewMode.OverprintPreview`. A `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the @@ -9005,7 +9006,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}` (`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 From cd1d1c0b340032038e336bb9fa262ac2a4e13083 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:26:10 -0800 Subject: [PATCH 11/24] i18n: Bulgarian asks before a script turns off the external script warning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bulgarian joined the complete-message languages on main, and the confirm a script shows before it turns off the warning for scripts picked with File › Scripts › Other Script… had no Bulgarian row, so script_warning_off_question_is_translated failed for bg. --- crates/ui-egui/src/i18n/bg.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fe6dc33df5..1bbdb83729 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 не можа да се запише копие за възстановяване, затова скриптът не беше изпълнен From f4aeabaddab8e88f8cdf13d330237225b852d55b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:44:50 -0800 Subject: [PATCH 12/24] Scripts: the Copy test reads what the run wrote to the system clipboard a_scripts_copy_is_offered_to_other_apps_when_the_run_ends checked app.clipboard_out, which only the panels' text copies set. A Copy's formats go to the clipboard backend, so the test failed at its first Copy. It now installs the fake clipboard from tests/sysclip.rs and counts the app's writes, and checks that the formats include SVG. CI did not report it because its test shard stopped at the first failure. --- crates/ui-egui/src/tests/script_run.rs | 44 +++++++++++++++++--------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 18ae9854c6..fef7526658 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, frame, is_open, key, open_id, pump, set}; +use super::sysclip::{Board, fake, writes, written}; use crate::dialogs::script_run::{ self, BY_PERSON, CLOSE_KIND, FilesAnswer, GROWTH_KIND, GrowthQuestion, KIND, PICKER_KIND, RunQuestion, ScriptFiles, }; @@ -612,38 +616,48 @@ 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 mut app = app(); + 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; - app.clipboard_out = None; + 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!(app.clipboard_out.is_none(), "a run without a Copy offers nothing"); + 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!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains("'});"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": import })).unwrap().unwrap(); finish(&mut app); assert_eq!(app.ui.status, "Ran script"); - assert!(app.clipboard_out.is_none()); + 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: {}}]}); } \ @@ -651,25 +665,25 @@ fn a_scripts_copy_is_offered_to_other_apps_when_the_run_ends() { 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!(app.clipboard_out.is_some()); + assert!(offered(&mut app, &board, &mut seen)); // A run that copies and then fails leaves the clipboard and what other apps were offered alone. - app.clipboard_out = None; 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!(app.clipboard_out.is_none()); + 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!(app.clipboard_out.is_none()); + 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!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains(" Date: Sat, 28 Nov 2026 03:32:28 -0800 Subject: [PATCH 13/24] Scripts: only the person turns off the external script warning Automation could answer Yes to the question a script asks before it turns off the external script warning, through the dialog's answer field or a pass it drives, and the warning was turned off. Setting Yes as the answer now fails with "Only the person at the keyboard can turn off the external script warning", and a Yes given while automation is acting is refused: the warning stays on and the question opens again. No is still taken from anyone, as Deny is in a script's file dialog. --- crates/ui-egui/src/dialogs/script_run.rs | 15 ++++++++++ crates/ui-egui/src/tests/script_dialogs.rs | 34 ++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 5bb70e52ad..744fae0aa6 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -67,6 +67,8 @@ pub const PICKER_KIND: &str = "scriptFiles"; /// 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"; @@ -273,6 +275,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.message == WARNING_OFF_QUESTION { + return Err(WARNING_BY_PERSON.into()); + } self.answer = Some(answer); } _ => return Err(FieldRefusal::Unknown.message(field)), @@ -663,6 +668,16 @@ pub(crate) fn settle_notice(app: &mut VectorcraftApp, result: DialogResult(&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() }; + 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"); + + 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"); +} From 6b7e9f01a23831494c1416af7b500c4f3fc68c32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:26:06 -0800 Subject: [PATCH 14/24] Scripts: concatenateMatrix rounds once at the edges of the number range The quick path in products_sum took a product that rounded up to the smallest normal number as exact, so a sum that needed the dropped part rounded twice: [N, N+S, 0, 1, 0, 0] then [1-2^-53, 0, -1, 1, 0, 0] gave mValueA = -S instead of -2S. A product at the smallest normal number now goes through the exact sum. The quick path also returned p + q + t when p + q was finite but adding t overflowed, although the exact sum was finite (MAX + 2^969); such a sum now goes through the exact sum too, and one that really overflows still throws a RangeError. --- crates/engine/src/script/dom/matrix.rs | 17 ++++++++++------- crates/engine/src/tests/script_dom_prefs.rs | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 7e93d4832a..bae77602cc 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -103,17 +103,20 @@ fn then(m: Matrix, n: Matrix) -> Matrix { ] } -/// `x·y + z·w + t`. When both products and their sum are finite, and a product below the range of -/// normal numbers is the only term that is not 0, the sum is taken as numbers are. 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. +/// `x·y + z·w + t`. When both products and the whole sum are finite, and a product at or below the +/// smallest normal number is the only term that is not 0, the sum is taken as numbers are. +/// 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, or to a sum that +/// rounds twice. A product that rounds up to the smallest normal number can have dropped part of a +/// step below it, so it counts as one too small. fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let (p, q) = (x * y, z * w); - let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; + let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() <= f64::MIN_POSITIVE; let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; - if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { - return plain + t; + let total = plain + t; + if total.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + 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 diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index fa01766d63..fae628e3c5 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -371,6 +371,25 @@ fn concatenation_applies_the_first_matrix_first() { ); } +#[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. + 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); }", + ); + assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError")]); +} + #[test] fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_number() { let mut s = Session::new(); From b32b14dc573234679bdc0c7052aa77b713c49dfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:00:37 -0800 Subject: [PATCH 15/24] Scripts: concatenateMatrix takes the exact sum near the overflow point The quick path in products_sum returned a finite coefficient whenever the rounded sum was finite. Rounding a product first can drop the part that puts the exact sum past the overflow midpoint, so a coefficient that should throw a RangeError came back as Number.MAX_VALUE. The quick path now runs only when the rounded sum is below half the largest number; every larger sum goes through the exact expansion and rounds once. --- crates/engine/src/script/dom/matrix.rs | 4 ++-- crates/engine/src/tests/script_dom_prefs.rs | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index bae77602cc..211ff9e8b0 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -103,7 +103,7 @@ fn then(m: Matrix, n: Matrix) -> Matrix { ] } -/// `x·y + z·w + t`. When both products and the whole sum are finite, and a product at or below the +/// `x·y + z·w + t`. When the whole sum is below half the largest number, and a product at or below the /// smallest normal number is the only term that is not 0, the sum is taken as numbers are. /// 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, or to a sum that @@ -115,7 +115,7 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; let total = plain + t; - if total.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + if total.abs() < f64::MAX / 2.0 && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { return total; } // Each product is split into its rounded value and the part that rounding drops, both exact. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index fae628e3c5..e41bb319a5 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -376,6 +376,8 @@ fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_numbe 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]}; }\ @@ -385,9 +387,12 @@ fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_numbe 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")]); + assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError"), json!("RangeError")]); } #[test] From bac470decb57aea5ec4dc54a4685afbf479a2bcc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:47:58 -0800 Subject: [PATCH 16/24] Scripts: concatenateMatrix keeps a value that a later term cancels down to products_sum added the rounded products and then the translation, so a rounding error that the translation cancels came back as the result: joining a move by (2^53, 1) with x + y - 2^53 gave an X move of 0 instead of 1. A sum now takes the quick path only when it has one term that is not 0, or when both products and their sum are exact. Every other sum goes through the exact expansion and rounds once. The expansion is held in a fixed array, so a composition does not allocate. Docs: docs/mcp.md and the scripting line in docs/target-app-parity.md state that each joined value is rounded once. --- crates/engine/src/script/dom/matrix.rs | 74 +++++++++++++-------- crates/engine/src/tests/script_dom_prefs.rs | 13 ++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 64 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 211ff9e8b0..467a5fc10e 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -103,19 +103,23 @@ fn then(m: Matrix, n: Matrix) -> Matrix { ] } -/// `x·y + z·w + t`. When the whole sum is below half the largest number, and a product at or below the -/// smallest normal number is the only term that is not 0, the sum is taken as numbers are. -/// 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, or to a sum that -/// rounds twice. A product that rounds up to the smallest normal number can have dropped part of a -/// step below it, so it counts as one too small. +/// `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 lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() <= f64::MIN_POSITIVE; - let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; + 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; - let total = plain + t; - if total.abs() < f64::MAX / 2.0 && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + 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. @@ -127,32 +131,50 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { [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(Vec::with_capacity(10), grow); - nearest(&exact) + 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: Vec, part: Wide) -> Vec { +fn grow(sums: Parts, part: Wide) -> Parts { let mut carry = part; - let mut kept = Vec::with_capacity(sums.len() + 1); - for h in sums { - let (sum, rest) = carry.two_sum(h); - if rest.m != 0.0 { - kept.push(rest); + 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; } - if carry.m != 0.0 { - kept.push(carry); - } + keep(carry); kept } /// The sign of the exact sum of `sums`, `0.0 - v` and `offset`: 1, -1 or 0. -fn sign_past(sums: &[Wide], v: f64, offset: Wide) -> i32 { - let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums.to_vec(), grow); - match rest.last() { +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, @@ -163,9 +185,9 @@ fn sign_past(sums: &[Wide], v: f64, offset: Wide) -> i32 { /// 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: &[Wide]) -> f64 { +fn nearest(sums: Parts) -> f64 { let even = |v: f64| v.to_bits() & 1 == 0; - let mut v = sums.iter().fold(Wide::of(0.0), |total, &h| total.two_sum(h).0).value().clamp(f64::MIN, f64::MAX); + 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. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index e41bb319a5..c56542973e 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -395,6 +395,19 @@ fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_numbe 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(); diff --git a/docs/mcp.md b/docs/mcp.md index 129e7e53a8..bc273c29ed 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2992,7 +2992,8 @@ other files through `$`: `(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; a matrix whose determinant is 0 is singular, and `invertMatrix` of one + `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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4ac11713c..bff1400bb4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1109,7 +1109,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: `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/), 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: `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: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. From 20f06e95866127f9177a2c350f9199f4f9dd1f8f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:37:43 -0800 Subject: [PATCH 17/24] Scripts: transforms measure clipped art against the canvas and keep tiny moves A transform of a clipping group or clipped layer now measures each object inside it against the canvas limit, as the native file's canvas check does, so a clipped object cannot be moved past the canvas while its clipping path stays inside. A pure move is applied as a translation, so a move far smaller than the pivot's coordinates still moves the object, and a transform that changes nothing is not measured. The transform tests build the 30 x 40 pt rectangle on top, since pageItems lists art topmost first, and the tests from main that named rotate as a member not available yet, the overprint preview error and the preset title limit follow main's current behavior. --- crates/engine/src/script/dom/transform.rs | 41 ++++++++++++----- crates/engine/src/tests/script_dom.rs | 18 +++----- .../engine/src/tests/script_dom_transform.rs | 46 ++++++++++++++++++- 3 files changed, 81 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 3f056589b1..7515fe42e3 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -117,17 +117,30 @@ fn anchor(h: &Host, item: Item, r: Rect, d: &Data) -> std::result::Result Affine { let [a, b, c, d, tx, ty] = m; - let page = Affine::new([a, 0.0 - b, 0.0 - c, d, tx, 0.0 - ty]); - Affine::translate(o.to_vec2()) * page * Affine::translate(-o.to_vec2()) + 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. +/// 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); - n.geometric_bounds_with(&d.symbol_boxes()).is_none_or(crate::sanity::rect_in_range) + within(&n, &d.symbol_boxes()) }) } @@ -141,17 +154,19 @@ fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) if matrix::singular(m) { return Err(HostError::Error("the transformation is singular and would flatten the object".into())); } - let (locked, on_locked, bounds, uses_pattern) = with_doc(h, item.doc, |_, st| { + let (locked, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| { let d = &st.doc; let mut locked = d.ancestry(item.id).is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); - let mut uses = false; + 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, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses) + (locked, 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))); @@ -168,12 +183,16 @@ fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) if opts.strokes && !opts.objects { return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); } - if let Some(r) = bounds.filter(|_| opts.objects) { + if opts.objects && xf != Affine::IDENTITY { // The transformed corners of the bounds hold the transformed object. When one of them is - // past the canvas, the transformed object itself is measured. - 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)]; + // 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; - if !corners.iter().all(|p| inside(xf * *p)) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) { + 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())); } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index d4ffe2523a..196f29bafd 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1495,26 +1495,22 @@ fn overprint_preview_is_refused_before_a_document_is_made() { let mut s = Session::new(); let e = failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.OverprintPreview; app.documents.addDocument('Print', p);"); - assert!(e.contains("OverprintPreview is not available yet"), "{e}"); + assert!(e.contains("overprintPreview"), "{e}"); assert!(s.documents().is_empty()); } #[test] fn document_presets_hold_a_limited_amount_of_data() { let mut s = Session::new(); - // A 4 MiB string: replacing one preset's value does not add up, 17 presets holding it do. + // 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 < 22; k++) t += t; var p = new DocumentPreset();\ + "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!(4 << 20)]); - let e = failure( - &mut s, - "var t = 'x'; for (var k = 0; k < 22; k++) t += t;\ - for (var k = 0; k < 17; k++) { var p = new DocumentPreset(); p.title = t; }", - ); - assert!(e.contains("DocumentPresets can hold at most"), "{e}"); + 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] @@ -2217,7 +2213,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('rotate'), 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_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index b861716b35..e5f1fad0c3 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -23,12 +23,13 @@ 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 and a 50 × 50 pt one above it. +/// 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 a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); (s, a, b) } @@ -169,6 +170,47 @@ fn a_move_too_small_to_round_away_moves_the_object() { 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(); From ea8951536d587c66eee6b4c2d46244182fa4c23a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:39:36 -0800 Subject: [PATCH 18/24] Scripts: resize scales a compound member's stroke and refuses negative line widths A path inside a compound path or compound shape takes its visible stroke from the compound, so resize with changeLineWidths sets the compound's stroke weight through stroke.set, in the same savepoint as the transform. A negative changeLineWidths throws. The PathItem progress line now says paths take the page item transforms. --- crates/engine/src/script/dom/paths.rs | 13 ++++++-- crates/engine/src/script/dom/transform.rs | 32 +++++++++++++------ crates/engine/src/tests/script_dom_paths.rs | 13 ++++++++ .../engine/src/tests/script_dom_transform.rs | 1 + docs/mcp.md | 5 ++- docs/target-app-parity.md | 2 +- 6 files changed, 51 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 2a9f69ec04..3b91756c91 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1096,9 +1096,10 @@ fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { // ---- PathItem stroke weights for `resize` ---- /// The stroke weight `resize`'s `changeLineWidths` of `percent` gives the path `item`, or `None` -/// when the path is not a path (the caller refuses the value) or the weight stays. -pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64) -> std::result::Result, HostError> { - if !(0.0..=100_000.0).contains(&percent) { +/// 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 width = look(h, item)?.width; @@ -1114,6 +1115,12 @@ 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(|_| ()) diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 9cda64e60f..89e601a0ac 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -33,7 +33,7 @@ use vectorcraft_geom::{Affine, Point, Rect}; use vectorcraft_js::{Data, HostError}; use super::matrix::{self, Matrix}; -use super::{Answer, Coords, Host, Item, arg, coordinate, edit_item, frame, number, paths, this_item, with_doc}; +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"; @@ -91,6 +91,9 @@ fn own_line_widths(d: &Data, m: Matrix) -> std::result::Result<(Option, f6 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. let own = matrix::area_scale(m) * 100.0; @@ -239,14 +242,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, let c = xf.as_coeffs(); let identity = xf == Affine::IDENTITY; let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; - 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) + // 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?, @@ -284,11 +290,17 @@ pub(super) fn resize(h: &Host, a: &[Data]) -> Answer { 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. + (Some(true), lw, _) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { + opts.strokes = true; + paths::resized_stroke_weight(h, item, lw, false)? + } (Some(strokes), _, _) => { opts.strokes = strokes; None } - (None, lw, _) if paths::is_path(h, item) => paths::resized_stroke_weight(h, item, lw)?, + (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) diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index a30279c12a..2c616a88c5 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -676,6 +676,19 @@ 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 set_anchors_reads_smooth_false_as_a_corner() { let (mut s, a, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index 383053c0c2..0172fa8d86 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -287,6 +287,7 @@ fn bad_arguments_throw_and_change_nothing() { ("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"), diff --git a/docs/mcp.md b/docs/mcp.md index 832c2ba0f1..f69f7ea552 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3057,7 +3057,10 @@ through `$`: `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); another value throws the same error. A locked object, one inside a locked layer or group, a + 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. 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dfaf0b07c7..dadab8ec2e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1122,7 +1122,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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 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 runs `object.transform` inside the run's transaction; 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.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). 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`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. From 75d4c949d23757949c62aefee9956d213cfcc650 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:14:06 -0800 Subject: [PATCH 19/24] Scripts: transform scales a compound member's stroke, and the warning confirm is known by its origin - PageItem.transform with changeLineWidths at the matrix's own scale sets the stroke weight of a path whose paint the compound holds, as resize does. resize and transform set that weight by the scale itself, and an explicit 100 keeps the weights even for a scale within the tolerance of 100%. - A changeLineWidths of 0 no longer matches a tiny scale; a positive value is compared with the scale relative to its size. - translate refuses an offset past the canvas only when the call moves the object or a pattern it uses; a non-finite offset is still refused. - Number conversion of preference text no longer trims U+0085, as JavaScript does not. - A real preference changes between 0 and -0: values are compared by their bits in the setter and when the run's keys are merged. - A clipboard.importSvg whose result cannot reach the script puts the clipboard back. - Moving an object works out its index without copying the list of its siblings. - The app's question before the external script warning turns off is known by the confirm the app opened, not by its text, so a script's confirm with the same text answers Yes through automation and is not translated. - docs: only calls that move or reshape the object run object.transform, and transform sets a compound member's stroke. --- crates/engine/src/prefs.rs | 17 ++++++- crates/engine/src/script/dialogs.rs | 6 +++ crates/engine/src/script/dom.rs | 9 ++-- crates/engine/src/script/dom/preferences.rs | 5 +- crates/engine/src/script/dom/transform.rs | 51 +++++++++++++++---- crates/engine/src/script/mod.rs | 15 ++++-- crates/engine/src/tests/script_dom_paths.rs | 20 ++++++++ crates/engine/src/tests/script_dom_prefs.rs | 43 +++++++++++++++- .../engine/src/tests/script_dom_transform.rs | 24 +++++++++ crates/ui-egui/src/dialogs/script_run.rs | 45 +++++++++++++--- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 12 files changed, 208 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index fd5481549f..3ae1683e84 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -464,8 +464,9 @@ pub struct Prefs { pub script_preferences: std::collections::BTreeMap, } -/// A value a script stored with `app.preferences`, with the type it was stored as. -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +/// 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), @@ -474,6 +475,18 @@ pub enum ScriptPreference { 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). pub const KEY_HOLD_DELAY: f64 = 0.35; /// The range of the Hold Shortcut Delay, in seconds. diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 598c62a04e..3067361727 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -482,6 +482,12 @@ impl Dialogs { 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() diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c48fa3e1b8..c1901ce038 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2634,10 +2634,13 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul }; 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: Vec> = - d.children(Some(to.parent)).map(|c| c.iter().filter(|n| n.id != id).cloned().collect()).unwrap_or_default(); - Ok::<_, HostError>(crate::doc::Node::insert_index(&rest, at, node)) + 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()); + Ok::<_, HostError>(if node.is_ruler_guide() { i.max(start) } else { i.min(start) }) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs index fa17a8bbdc..c4308efba2 100644 --- a/crates/engine/src/script/dom/preferences.rs +++ b/crates/engine/src/script/dom/preferences.rs @@ -110,9 +110,10 @@ fn stored(h: &Host, key: &str) -> Option { } /// `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. +/// 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{feff}'); + let t = t.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'); if t.is_empty() { return 0.0; } diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 89e601a0ac..6c07a070e1 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -96,13 +96,14 @@ fn own_line_widths(d: &Data, m: Matrix) -> std::result::Result<(Option, f6 } // 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 own.is_finite() && (lw - own).abs() <= 1e-9 * own.max(1.0) { - return Ok((Some((own - 100.0).abs() > 1e-9), lw, own)); - } 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)) } @@ -260,12 +261,30 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, 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 => coordinate(d, what), + 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)?; - apply(h, this_item(h, a)?, matrix::translate(dx, dy), None, &opts, None) + 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"]; @@ -291,10 +310,10 @@ pub(super) fn resize(h: &Host, a: &[Data]) -> Answer { 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. - (Some(true), lw, _) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { + // 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, lw, false)? + paths::resized_stroke_weight(h, item, own, false)? } (Some(strokes), _, _) => { opts.strokes = strokes; @@ -312,6 +331,18 @@ pub(super) fn resize(h: &Host, a: &[Data]) -> Answer { 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)?; - opts.strokes = line_widths(arg(a, 6), m)?; - apply(h, this_item(h, a)?, m, Some(arg(a, 7)), &opts, None) + 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 5ae3ca7a08..d96e5f60f8 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -641,7 +641,8 @@ impl World { /// 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", "command.batch", "edit.copy", "edit.cut"]; +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 @@ -1348,8 +1349,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(); @@ -2068,6 +2070,13 @@ 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`]. Yes to a confirm the diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 2c616a88c5..92b19d1d38 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -689,6 +689,26 @@ fn resizing_a_compound_member_with_its_own_line_width_scales_the_compound_stroke 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(); diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 25419360ad..edd718ec46 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -106,6 +106,7 @@ fn yes_to_the_confirm_turns_the_warning_off() { 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(); @@ -114,6 +115,17 @@ fn yes_to_the_confirm_turns_the_warning_off() { 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(); @@ -217,6 +229,31 @@ fn missing_keys_read_as_empty_values_and_getters_convert() { ); } +#[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(); @@ -611,11 +648,13 @@ fn a_copy_or_cut_the_run_puts_back_is_not_reported() { "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('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"]), "{r}"); + 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); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index 0172fa8d86..d57d4570d5 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -169,6 +169,30 @@ fn a_scale_whose_square_is_too_large_for_a_number_keeps_its_own_line_width() { 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(); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 1ecac1bc5f..4f47e7a244 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -59,7 +59,6 @@ use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; -use vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; @@ -209,11 +208,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(), @@ -261,8 +264,8 @@ 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) -> String { - if message == WARNING_OFF_QUESTION { crate::i18n::msg(message) } else { message.to_string() } +fn notice_message(message: &str, warning_off: bool) -> String { + if warning_off { crate::i18n::msg(message) } else { message.to_string() } } impl StackDialog for ScriptNotice { @@ -278,7 +281,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(¬ice_message(&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.")); @@ -336,7 +339,7 @@ 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.message == WARNING_OFF_QUESTION { + if answer == "yes" && self.warning_off { return Err(WARNING_BY_PERSON.into()); } self.answer = Some(answer); @@ -713,7 +716,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. @@ -869,7 +872,7 @@ pub(crate) fn settle_notice(app: &mut VectorcraftApp, result: DialogResult