From 483bf2363dfa63be319cac792e5b9ccf947cff10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:25:11 -0800 Subject: [PATCH 1/5] Scripts: invertMatrix decides overflow from the exact quotient The determinant and the translation numerators are rounded before the division, so a value whose exact quotient is below the overflow midpoint could round to infinity and throw a RangeError, and one at or past it could come out finite. When the rounded quotient overflows or lies within eight steps of Number.MAX_VALUE, the exact quotient is now compared with the midpoint between Number.MAX_VALUE and 2^1024 from exact product parts. An infinite rounded quotient below it is replaced by the number the exact quotient rounds to. --- crates/engine/src/script/dom/matrix.rs | 101 +++++++++++++++++--- crates/engine/src/tests/script_dom_prefs.rs | 25 +++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 119 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 467a5fc10e..e9fd55e70b 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -125,26 +125,29 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { // Each product is split into its rounded value and the part that rounding drops, both exact. // The five parts are added one at a time into a list of values that do not overlap, smallest // first, whose sum is exact (Shewchuk's expansion). - let product = |a: f64, b: f64| { - let (a, b) = (Wide::of(a), Wide::of(b)); - let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); - [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] - }; let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w)); let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow); nearest(exact) } +/// `a·b` as its rounded value and the part that rounding drops, both exact. +fn product(a: f64, b: f64) -> [Wide; 2] { + 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)] +} + /// 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. +/// most one more, so the five parts of a sum, the two of a comparison and the sixteen of an +/// inverse's rounding test fit. #[derive(Clone, Copy)] struct Parts { - v: [Wide; 8], + v: [Wide; 16], n: usize, } impl Parts { - const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 }; + const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 16], n: 0 }; fn as_slice(&self) -> &[Wide] { &self.v[..self.n] @@ -404,9 +407,85 @@ fn invert(_: &Host, a: &[Data]) -> Answer { // 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))]) + let exact_det = || difference_parts(a, d, b, c); + let zero = Wide::of(0.0); + let plain = |v: f64| quotient(Wide::of(v), || [Wide::of(v), zero, zero, zero], det, exact_det); + record([ + plain(d), + plain(0.0 - b), + plain(0.0 - c), + plain(a), + quotient(products_difference(c, f, d, e), || difference_parts(c, f, d, e), det, exact_det), + quotient(products_difference(b, e, a, f), || difference_parts(b, e, a, f), det, exact_det), + ]) +} + +/// `a·d − b·c` as four exact parts. +fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] { + let neg = |w: Wide| Wide { m: 0.0 - w.m, e: w.e }; + let ([p, p_lost], [q, q_lost]) = (product(a, d), product(b, c)); + [p, p_lost, neg(q), neg(q_lost)] +} + +/// The quotient of `num` by `det`, from their rounded values `num` and `det` and their exact parts. +/// The result is the rounded quotient, which is within a few steps of the exact one, except where +/// that would decide overflow wrongly. When the rounded quotient overflows or lies within eight +/// steps of the largest number, the exact quotient is compared with 2^1024 − 2^970, the halfway +/// point between the largest number and 2^1024: at it or past it the result is infinite. Below it +/// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact +/// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the +/// even one. The exact parts are worked out only then. Adding 0 turns -0 into 0. +fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 { + let v = num.div(det).value() + 0.0; + // 2^1024 − 9·2^971, eight steps below the largest number. + let near_top = f64::MAX - 8.0 * pow2(971); + if v.is_finite() && v.abs() < near_top { + return v; + } + let (exact_num, exact_det) = (exact_num(), exact_det()); + let sign = |parts: &[Wide]| match parts.iter().copied().fold(Parts::EMPTY, grow).as_slice().last() { + Some(w) if w.m < 0.0 => -1.0, + _ => 1.0, + }; + let (sn, sd) = (sign(&exact_num), sign(&exact_det)); + // The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each + // `j·m` is split into its rounded value and the part that rounding drops. + let past = |j: f64| { + let scaled = |w: Wide, s: f64, e: i32| Wide { m: w.m * s, e: w.e.saturating_add(e) }; + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(hi, w.e.saturating_add(970)), Wide::new(lo, w.e.saturating_add(970))] + }; + let sum = exact_num + .iter() + .map(|&w| scaled(w, sn, 0)) + .chain(exact_det.iter().map(|&w| scaled(w, 0.0 - sd, 1024))) + .chain(exact_det.iter().flat_map(|&w| times_j(w))) + .fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + if past(1.0) >= 0 { + return f64::INFINITY; + } + if v.is_finite() { + return v; + } + let even = |x: f64| x.to_bits() & 1 == 0; + let mut top = f64::MAX; + for k in 1..16u8 { + let below = top.next_down(); + match past(f64::from(2 * k + 1)) { + 1 => return top * sn * sd, + 0 => return if even(top) { top } else { below } * sn * sd, + _ => top = below, + } + } + top * sn * sd } fn is_equal(_: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index c56542973e..5cb7acb4b2 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -466,6 +466,31 @@ fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() { 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 an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is MAX + 2^970, the overflow midpoint. With b = 2^-53 the + // determinant is 1 + 2^-53, so the exact quotient is MAX - 2^970 + about 2^917, which rounds + // to MAX, while the rounded determinant 1 gives infinity. With b = 0 the quotient is the + // midpoint itself, which rounds to infinity. With a = 1 + 2^-51 and the numerator + // 2^1024 + 3·2^971, the rounded quotient overflows while the exact one is MAX - 2^971 and a + // little more, which rounds to the number below MAX. With b = -2^-54 and ty = -2^969 the rounded + // quotient is MAX, while the exact one is past the overflow midpoint. + 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 i = app.invertMatrix(mat([1, Math.pow(2, -53), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)]));\ + vc.log(i.mValueTX === Number.MAX_VALUE);\ + try { app.invertMatrix(mat([1, 0, -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + var j = app.invertMatrix(mat([1 + Math.pow(2, -51), Math.pow(2, -53), -1, 1, -Math.pow(2, 1023), -(Math.pow(2, 1023) + 3 * Math.pow(2, 971))]));\ + vc.log(j.mValueTX === Number.MAX_VALUE - Math.pow(2, 971));\ + try { app.invertMatrix(mat([1, -Math.pow(2, -54), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 969)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }", + ); + assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]); +} + #[test] fn inverse_singular_and_equal_matrices() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index a09de47c27..ae84f1361b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3153,7 +3153,9 @@ through `$`: `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`. + and a result too large for a number throws a `RangeError`. `invertMatrix` decides overflow from each value's exact + quotient: when its magnitude is below the halfway point between `Number.MAX_VALUE` and 2^1024 the value is a finite + number, and at that point or past it the call 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 407734ce80..fabc5554ee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1112,7 +1112,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/), 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: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). 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: 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`. From efdaa06fd260c32545364dac795d2f2e402cd3b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:10:26 -0800 Subject: [PATCH 2/5] Scripts: reflect reports matrix defaults; copy notes keep the recording limit - app.reflect now reports the defaults of the matrix functions' number arguments: 0 for deltaX, deltaY and angle, and 100 for scaleX, in the get and concatenate variants. scaleY has no fixed default, since a left-out vertical scale is the horizontal one; its description says so. - When a script's commands take a recording past its limit and the script also copied, the notes of the Copy's formats no longer replace the limit message in the status bar. The limit is named only once, so the message is kept while it shows. The same applies to a script run that automation takes to its end at once. --- crates/engine/src/script/dom/matrix.rs | 20 ++++++++++++- crates/engine/src/tests/script_dom_prefs.rs | 20 +++++++++++++ .../ui-egui/src/panels/actions/recording.rs | 2 ++ .../src/panels/actions/tests_limits.rs | 29 +++++++++++++++++++ crates/ui-egui/src/sysclip.rs | 11 ++++++- 5 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index e9fd55e70b..0887168db8 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -19,7 +19,7 @@ //! - An argument that is not a finite number, or a matrix with a value that is not one, throws a //! `TypeError`; a result with a value too large for a number throws a `RangeError`. -use vectorcraft_js::{Data, HostError}; +use vectorcraft_js::{Data, HostError, MemberInfo}; use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text}; @@ -54,6 +54,24 @@ pub(super) fn app_members(link: &Link) -> Vec { ("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])), ("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])), ]) + .into_iter() + .map(|(name, member, info)| (name, member, with_defaults(info))) + .collect() +} + +/// `info` with the defaults of its left-out number arguments, which `reflect` reports: 0 for a +/// translation and an angle, 100 for a horizontal scale. A left-out vertical scale is the +/// horizontal one, so it has no fixed default and its description says so. +fn with_defaults(mut info: MemberInfo) -> MemberInfo { + for a in &mut info.arguments { + match a.name.as_str() { + "deltaX" | "deltaY" | "angle" => a.default = Some(num(0.0)), + "scaleX" => a.default = Some(num(100.0)), + "scaleY" => a.description = Some("The vertical scale; when it is left out, the horizontal scale.".into()), + _ => {} + } + } + info } /// The record for `m`, or a `RangeError` when a value is not finite. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 5cb7acb4b2..624ff8a7f8 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -342,6 +342,26 @@ fn matrix_functions_give_new_records() { assert_eq!(r, vec![json!([c, sn, -sn, c])]); } +#[test] +fn reflect_reports_the_matrix_argument_defaults() { + let mut s = Session::new(); + let out = log( + &mut s, + "function d(f, a) { return String(app.reflect.find(f).arguments[a].defaultValue); }\ + vc.log([d('getScaleMatrix', 'scaleX'), d('concatenateScaleMatrix', 'scaleX'), d('getTranslationMatrix', 'deltaX'),\ + d('concatenateTranslationMatrix', 'deltaY'), d('getRotationMatrix', 'angle'), d('concatenateRotationMatrix', 'angle'),\ + d('getScaleMatrix', 'scaleY'), d('concatenateMatrix', 'matrix')]);\ + vc.log(app.reflect.find('getScaleMatrix').arguments.scaleY.description);", + ); + assert_eq!( + out, + vec![ + json!(["100", "100", "0", "0", "0", "0", "undefined", "undefined"]), + json!("The vertical scale; when it is left out, the horizontal scale."), + ] + ); +} + #[test] fn concatenation_applies_the_first_matrix_first() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/panels/actions/recording.rs b/crates/ui-egui/src/panels/actions/recording.rs index bf0d4440f8..13ce1bf3bf 100644 --- a/crates/ui-egui/src/panels/actions/recording.rs +++ b/crates/ui-egui/src/panels/actions/recording.rs @@ -172,6 +172,8 @@ pub(crate) fn after_journaled_edit(app: &mut VectorcraftApp) -> bool { Ok(()) => false, Err(e) => { app.status(e); + // The limit is named once: the notes of the edit's Copy or Cut do not replace it. + app.clipboard_publishing.keep_status(&app.ui); true } } diff --git a/crates/ui-egui/src/panels/actions/tests_limits.rs b/crates/ui-egui/src/panels/actions/tests_limits.rs index a4b22246fd..5ecd1c718b 100644 --- a/crates/ui-egui/src/panels/actions/tests_limits.rs +++ b/crates/ui-egui/src/panels/actions/tests_limits.rs @@ -295,6 +295,35 @@ fn script_run_checks_recording_step_limit_on_completion() { } } +/// A script that copies type in a family that is not installed, whose Copy's formats therefore +/// have notes, and whose commands take a recording past 10,000 steps: the status bar keeps naming +/// the limit once the formats are written. Without the recording the notes show. +#[test] +fn a_scripts_copy_notes_do_not_replace_the_recording_limit() { + let steps = "the action already has 10,000 steps"; + let copy = "var t = vc.run('text.create', {x: 5, y: 20, text: 'Ab', font: 'Nonexistent Sans Probe'});\ + vc.run('select.set', {ids: [t.id]}); app.copy();"; + for frames in [false, true] { + for recording in [true, false] { + let services = crate::tests::sysclip::fake_clipboard_services(); + let app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); + let (mut app, _) = three_moves_in(app); + if recording { + recording_with(&mut app, files::MAX_ACTION_STEPS - 1); + } + app.ui.status.clear(); + run_script(&mut app, copy, frames); + let _ = app.written_clipboard_text(); + let what = format!("frames {frames}, recording {recording}"); + if recording { + assert_eq!(app.ui.status, steps, "{what}: the limit stays in the status bar"); + } else { + assert!(app.ui.status.starts_with("Copied with "), "{what}: {}", app.ui.status); + } + } + } +} + /// A script whose commands give the recording's set a file larger than 8 MiB keeps its edit, /// the status bar names the limit as the run ends, and Stop Playing/Recording keeps the steps /// that fit in a set that Load Actions… reads. One that fills the file exactly names no limit. diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 9371e118fd..8c54822d2f 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -94,6 +94,9 @@ pub(crate) struct Publishing { /// The status bar's message the latest Copy or Cut with notes left, with /// [`crate::state::UiState::status_sets`] then. notes_status: Option<(String, u64)>, + /// A message that no Copy or Cut's notes replace while the status bar shows it (a recording's + /// limit, which is named once), with [`crate::state::UiState::status_sets`] then. + kept: Option<(String, u64)>, } impl Publishing { @@ -118,7 +121,13 @@ impl Publishing { /// Does `ui`'s status bar still show the message the latest Copy or Cut left, with nothing /// setting the status since? fn shows_status(&self, ui: &crate::state::UiState) -> bool { - ui.status == self.status.0 && ui.status_sets == self.status.1 + let kept = self.kept.as_ref().is_some_and(|(s, sets)| ui.status == *s && ui.status_sets == *sets); + !kept && ui.status == self.status.0 && ui.status_sets == self.status.1 + } + + /// `ui`'s status bar message stays while it shows: no Copy or Cut's notes replace it. + pub(crate) fn keep_status(&mut self, ui: &crate::state::UiState) { + self.kept = Some((ui.status.clone(), ui.status_sets)); } /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing From 61770864ecdf8c48c10c53549398178a8b1ef487 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:49:28 -0800 Subject: [PATCH 3/5] Scripts: an inverse below half the smallest number rounds once app.invertMatrix divided the rounded numerator by the determinant and rounded again, so an x-translation whose exact quotient is just past half the smallest number (numerator 2^-1021 + 2^-1075, determinant 2^54) came back as 0 instead of Number.MIN_VALUE. When the rounded quotient is below 2^-1023, the result is now found from the exact numerator and determinant: the multiple of the smallest number whose halfway points hold the exact quotient, ties to the even one. A quotient exactly at the halfway point still rounds to 0. --- crates/engine/src/script/dom/matrix.rs | 62 ++++++++++++++++++++- crates/engine/src/tests/script_dom_prefs.rs | 22 ++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 0887168db8..bf5c325295 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -452,12 +452,19 @@ fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] { /// point between the largest number and 2^1024: at it or past it the result is infinite. Below it /// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact /// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the -/// even one. The exact parts are worked out only then. Adding 0 turns -0 into 0. +/// even one. When the rounded quotient is below 2^-1023, where every number is a multiple of the +/// smallest number, the result is the multiple whose halfway points to its neighbors hold the exact +/// quotient, ties to the even one, so a quotient just past half the smallest number is not rounded +/// to 0. The exact parts are worked out only then. Adding 0 turns -0 into 0. fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 { + if num.m == 0.0 { + return 0.0; + } let v = num.div(det).value() + 0.0; // 2^1024 − 9·2^971, eight steps below the largest number. let near_top = f64::MAX - 8.0 * pow2(971); - if v.is_finite() && v.abs() < near_top { + let tiny = f64::MIN_POSITIVE / 2.0; + if v.is_finite() && v.abs() < near_top && v.abs() >= tiny { return v; } let (exact_num, exact_det) = (exact_num(), exact_det()); @@ -466,6 +473,9 @@ fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: _ => 1.0, }; let (sn, sd) = (sign(&exact_num), sign(&exact_det)); + if v.abs() < tiny { + return small_quotient(v, &exact_num, &exact_det, sn, sd); + } // The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each // `j·m` is split into its rounded value and the part that rounding drops. let past = |j: f64| { @@ -506,6 +516,54 @@ fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: top * sn * sd } +/// The exact quotient of `exact_num` by `exact_det`, whose signs are `sn` and `sd`, rounded to a +/// multiple of the smallest number, ties to the even multiple, starting from the rounded quotient +/// `v`, which is below 2^-1023 and within a few steps of it. +fn small_quotient(v: f64, exact_num: &[Wide; 4], exact_det: &[Wide; 4], sn: f64, sd: f64) -> f64 { + let step = f64::from_bits(1); + // The sign of |num| − j·2^-1075·|det|, with each `j·m` split into its rounded value and the + // part that rounding drops. `j` is odd and below 2^53, so it is exact. + let past = |j: f64| { + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(0.0 - hi, w.e.saturating_sub(1075)), Wide::new(0.0 - lo, w.e.saturating_sub(1075))] + }; + let sum = exact_num.iter().map(|&w| Wide { m: w.m * sn, e: w.e }).chain(exact_det.iter().flat_map(|&w| times_j(w))).fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + // `k` steps; dividing by the smallest number is exact. + let mut k = v.abs() / step; + let even = |k: f64| k % 2.0 == 0.0; + for _ in 0..8 { + match past(2.0 * k + 1.0) { + 1 => k += 1.0, + 0 => { + k = if even(k) { k } else { k + 1.0 }; + break; + } + _ => { + if k == 0.0 { + break; + } + match past(2.0 * k - 1.0) { + -1 => k -= 1.0, + 0 => { + k = if even(k) { k } else { k - 1.0 }; + break; + } + _ => break, + } + } + } + } + k * step * sn * sd + 0.0 +} + fn is_equal(_: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(matrix(arg(a, 1), "matrix")? == matrix(arg(a, 2), "secondMatrix")?)) } diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 624ff8a7f8..2f14af0357 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -511,6 +511,28 @@ fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() { assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]); } +#[test] +fn an_inverse_translation_next_to_half_the_smallest_number_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is 2^-1021 + 2^-1075 and the determinant 2^54, so the exact + // quotient is 2^-1075 + 2^-1129, just past half the smallest number, which rounds to it. The + // rounded numerator 2^-1021 gives 2^-1075, which rounds to 0. With c = 0 the quotient is 2^-1075 + // itself, which rounds to 0. With both translations negated, the x-translation rounds to minus + // the smallest number. + 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 t = Math.pow(2, -1021), big = Math.pow(2, 54), small = Math.pow(2, -54);\ + var i = app.invertMatrix(mat([big, 0, small, 1, -t, t]));\ + vc.log([i.mValueTX === Number.MIN_VALUE, i.mValueTY === -t]);\ + var j = app.invertMatrix(mat([big, 0, 0, 1, -t, t]));\ + vc.log([j.mValueTX, 1 / j.mValueTX > 0]);\ + var k = app.invertMatrix(mat([big, 0, small, 1, t, -t]));\ + vc.log([k.mValueTX === -Number.MIN_VALUE, k.mValueTY === t]);", + ); + assert_eq!(out, vec![json!([true, true]), json!([0, true]), json!([true, true])]); +} + #[test] fn inverse_singular_and_equal_matrices() { let mut s = Session::new(); From 4ca2683571a441cf7d3973d30d4ba9ec578a70a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:22:43 -0800 Subject: [PATCH 4/5] Scripts: preference tests check the run result and the quiet level The merge test now requires the run to succeed instead of accepting any result, through the bounded pump helper. The confirm test sets UserInteractionLevel.DONTDISPLAYALERTS without a try/catch, so the run really asks for no dialogs before the confirm. --- crates/engine/src/tests/script_dom_prefs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 2f14af0357..bfdcd5a376 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -151,7 +151,7 @@ fn no_to_the_confirm_or_stop_leaves_the_warning_on() { #[test] fn the_confirm_cannot_be_skipped() { let mut s = Session::new(); - framed(&mut s, &format!("try {{ app.userInteractionLevel = 'DONTDISPLAYALERTS'; }} catch (e) {{}} {ASK_OFF}")); + framed(&mut s, &format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; {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()); @@ -305,7 +305,7 @@ fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() { 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() {} + pump(&mut s).unwrap().unwrap(); let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect(); assert_eq!( keys, From dc94ae977c4f425e5a5da1900d4d0cd1a621993e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:10:05 -0800 Subject: [PATCH 5/5] Docs: matrix records passed in need only the six mValue fields The matrix functions read only mValueA to mValueTY from a record passed in. The typename "Matrix" is on the records they give back. --- crates/engine/src/script/dom/matrix.rs | 7 ++++--- docs/mcp.md | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index aeccf78c95..4de0a9efe4 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -1,9 +1,10 @@ //! The matrix functions of `app`, as the help pages //! and //! describe them. A matrix is a plain -//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the -//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a -//! new record, those two give a boolean, and none changes the records passed to it. +//! record with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and +//! `mValueTY`; a record passed in needs only those six, and each record a function gives also has +//! the `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives +//! a new record, those two give a boolean, and none changes the records passed to it. //! //! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix //! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. diff --git a/docs/mcp.md b/docs/mcp.md index 3f6d406c90..2a2578895e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3278,7 +3278,8 @@ through `$`: `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 + objects with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY`. A record + passed in needs only those six fields; each record a function gives also has `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives a new record; those two give `true` or `false`. No function changes the records passed to it. A record maps `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own