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.
This commit is contained in:
dotCooCoo
2026-11-22 08:04:21 -08:00
parent bb311d3c4d
commit 9b2bfcd50f
4 changed files with 116 additions and 21 deletions
+45 -9
View File
@@ -2,8 +2,8 @@
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> 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<f64, HostEr
}
}
/// The matrix that applies `m` and then `n`.
/// The matrix that applies `m` and then `n`. Adding 0 turns -0 into 0.
fn then(m: Matrix, n: Matrix) -> Matrix {
let [a, b, c, d, e, f] = m;
let [a2, b2, c2, d2, e2, f2] = n;
[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);
+14 -11
View File
@@ -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<Vec<Value>>,
log_bytes: Cell<usize>,
written: RefCell<Written>,
/// 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<bool>,
/// 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<crate::Document>, 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, &params)
(s.copies, step(&mut s, host, &id, &params))
};
// Only commands that exist are timed, so the table holds at most one row per command.
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
@@ -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))
}
@@ -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());
}
+2 -1
View File
@@ -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