Scripts: stale placed items are refused as relative objects; exact image matrix checks

- move() and duplicate() resolve a page-item relative object, an add()
  result included, through item_of, so a PlacedItem object made stale by
  embed() throws "Stale page item" instead of acting as a target.
- Assigning matrix compares each requested coefficient exactly with the
  value the getter reports. A coefficient left as reported keeps the
  image's own value, so a change of 5e-10 still moves the image and an
  untouched axis does not shift. A move alone is applied as an offset.
  A matrix that a nearly singular image cannot reach within 1e-6 pt at
  its corners, or that would leave it with no area, throws an error with
  nothing changed, and a change that rounds away runs no command.
- The RasterItem.embedded test calls the getter itself on 1 and on a
  live raster item.
- docs/mcp.md states when assigning matrix runs no command and when it
  is refused.
This commit is contained in:
dotCooCoo committed 2026-12-01 02:32:07 -08:00
1 parent 8e682687ce
commit ec4a813fa3
4 files changed
+109 -9

No files matched your search

+9 -1
View File
@@ -2635,6 +2635,7 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
let how = placement_of(how)?;
let beside = matches!(how, Placement::Above | Placement::Below);
let pending = images::pending_as_item(h, target)?.map(|p| p.to_vec());
let is_pending = pending.is_some();
let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer"));
let Some(handle) = handle.filter(|parts| parts.len() == 5) else {
if handle_of(target, "Document").is_some() {
@@ -2642,7 +2643,14 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
}
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
};
let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let (doc, target) = if is_pending || handle_of(target, "PageItem").is_some() {
// A page item, an `add()` result included, must still be of its class: an embedded
// `PlacedItem`'s old object is stale.
let it = item_of(h, target)?;
(it.doc, it.id)
} else {
node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?
};
if doc.uid != item.doc.uid {
return Err(HostError::Error(CROSS_DOCUMENT.into()));
}
+43 -4
View File
@@ -27,8 +27,10 @@
//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only
//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file.
//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a
//! matrix with no area or one that puts a corner of the image outside the canvas is refused.
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`,
//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a
//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly
//! is refused.
//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system.
use std::cell::RefCell;
@@ -525,13 +527,50 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
return Err(HostError::Range("the matrix puts the image outside the canvas".into()));
}
let old = im.xf;
if old.as_coeffs().iter().zip(target.as_coeffs()).all(|(o, t)| (o - t).abs() <= 1e-9) {
// Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small
// change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the
// conversion to document space rounds away leaves the image's matrix as it is and runs nothing.
// A coefficient the script left as the getter reports keeps the image's own value, so the
// conversion back does not shift an untouched axis.
let olds = old.as_coeffs();
let [a0, b0, c0, d0, e0, f0] = olds;
let reported = match h.dom.coords.get() {
Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0],
Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top],
};
let mut wanted = target.as_coeffs();
for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) {
if r == v {
*w = o;
}
}
if wanted == olds {
return Ok(None);
}
if !area_of(old) {
return Err(HostError::Error("the image has no area to transform".into()));
}
Ok(Some((target * old.inverse()).as_coeffs()))
let target = Affine::new(wanted);
let [ta, tb, tc, td, te, tf] = wanted;
if [ta, tb, tc, td] == [a0, b0, c0, d0] {
// A move alone: the offset difference, without the error an inverse adds.
return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0]));
}
// A nearly singular image loses precision through the inverse; refuse a change that would
// not land where the script asked rather than move the image somewhere else.
let delta = target * old.inverse();
let landed = delta * old;
if landed.as_coeffs() == olds {
return Ok(None);
}
let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| {
let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y));
(p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6
});
if !close || !area_of(landed) {
return Err(HostError::Range("the matrix cannot be applied exactly to this image".into()));
}
Ok(Some(delta.as_coeffs()))
})?;
if let Some(d) = delta {
edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?;
+54 -2
View File
@@ -368,6 +368,55 @@ fn image_matrix_assignment_transforms_the_image() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_tiny_matrix_change_still_transforms_the_image() {
let base = folder("matrix-tiny");
let g = base.join("main/g.png");
std::fs::write(&g, gray_png(10, 20)).unwrap();
let mut s = session();
let id = place(&mut s, &g, false);
let before = undo_steps(&s);
let tx = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Image(im) => im.xf.as_coeffs()[4],
_ => panic!("not an image"),
};
let old = tx(&s);
log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueTX = m.mValueTX + 5e-10; r.matrix = m;");
assert_eq!(undo_steps(&s), before + 1);
assert!(tx(&s) != old, "the image did not move");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_stale_placed_item_is_not_a_relative_object() {
let base = folder("stale-relative");
let a = base.join("main/a.png");
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
place(&mut s, &a, true);
place(&mut s, &a, true);
place(&mut s, &a, true);
let out = log(
&mut s,
&base,
&format!(
"var d = app.activeDocument, p = d.placedItems[0], q = d.placedItems[1], r = d.placedItems[2], m = [];\
r.move(q, ElementPlacement.PLACEBEFORE); m.push('live');\
var n = d.placedItems.add(); n.file = new File('{}'); r.move(n, ElementPlacement.PLACEAFTER); m.push('added');\
p.embed();\
try {{ r.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
try {{ r.duplicate(p, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
n.embed();\
try {{ r.move(n, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
try {{ r.duplicate(n, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
vc.log(m);",
js_path(&a)
),
);
assert_eq!(out, vec![json!(["live", "added", "Stale page item", "Stale page item", "Stale page item", "Stale page item"])]);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn image_matrix_refuses_bad_values_without_changing_the_image() {
let base = folder("matrix-bad");
@@ -489,16 +538,19 @@ fn stale_and_foreign_placed_items_are_refused() {
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
let id = place(&mut s, &a, true);
place(&mut s, &a, false);
let out = log(
&mut s,
&base,
"var p = app.activeDocument.placedItems[0], m = []; p.remove();\
try { p.relink(null); } catch (e) { m.push(e.message); }\
try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\
var g = Object.getOwnPropertyDescriptor(RasterItem.prototype, 'embedded').get;\
try { g.call(1); } catch (e) { m.push(e.name); }\
m.push(g.call(app.activeDocument.rasterItems[0]));\
try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\
vc.log(m);",
);
assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]);
assert_eq!(out, vec![json!(["Stale page item", "TypeError", true, "this is not a PlacedItem"])]);
assert!(s.active().unwrap().doc.node(id).is_none());
let _ = std::fs::remove_dir_all(base);
}
+3 -2
View File
@@ -3215,8 +3215,9 @@ through `$`:
`null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true
for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY`
that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning
`matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of
the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
`matrix` runs `object.transform`, except that a matrix equal to the one `matrix` reads runs no command; a value
that is not finite, a matrix with no area, one that puts a corner of the image outside the canvas and one that a
nearly singular image cannot reach exactly throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete
objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the
item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()`