diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b29b037908..3c2bbe8d29 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2477,8 +2477,12 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer { /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the /// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path /// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does -/// nothing. +/// nothing. Type in a document in the back that is not measured yet is measured first, as the +/// switch to that document would measure it. fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option, Frame), HostError> { + if h.session.borrow().active_index() != Some(item.doc.index) && rests_on_type(h, item) { + h.session.borrow_mut().measure_back_type(item.doc.uid); + } with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?))) } @@ -2550,20 +2554,41 @@ fn item_height(h: &Host, a: &[Data]) -> Answer { Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height()))) } +/// Whether the item's bounds can rest on laid-out type: it holds type, a symbol instance or a +/// placed document. Such bounds in a document in the back may be laid out in another document's +/// composite fonts, so the setters measure them only after the switch to the document. +fn rests_on_type(h: &Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| { + st.doc.node(item.id).is_none_or(|n| { + let mut found = false; + n.walk(&mut |c| found |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. } | NodeKind::PlacedDocument(_))); + found + }) + }) +} + /// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - // Measured once the document is active. - edit_item_with(h, item, |h| { - let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) }; + // The distance to move, or `None` when the item is already there or has no bounds. + let delta = |h: &Host| -> std::result::Result, HostError> { + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(None) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); let (dx, dy) = (to.x - r.x0, to.y - r.y0); - if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + Ok((dx.abs() > 1e-9 || dy.abs() > 1e-9).then_some((dx, dy))) + }; + // An item already in place stays, and its document stays in the back. + if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && delta(h)?.is_none() { + return Ok(Data::Undefined); + } + // Measured again once the document is active. + edit_item_with(h, item, |h| { + if let Some((dx, dy)) = delta(h)? { command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; } Ok(()) @@ -2601,19 +2626,27 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - // Measured once the document is active, so the ratio applies to the bounds the scale works on. - edit_item_with(h, item, |h| { - let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) }; + // The bounds to scale and the percentage, or `None` when the item already has that size or has + // no bounds. + let scale = |h: &Host| -> std::result::Result, HostError> { + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(None) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { return Err(HostError::Error(format!("the object has no {what} to scale"))); } - if (now - size).abs() < 1e-9 { - return Ok(()); + Ok(((now - size).abs() >= 1e-9).then_some((r, size / now * 100.0))) + }; + // An item already that size stays, and its document stays in the back. + if h.session.borrow().active_index() != Some(item.doc.index) && !rests_on_type(h, item) && scale(h)?.is_none() { + return Ok(Data::Undefined); + } + // Measured again once the document is active, so the ratio applies to the bounds the scale + // works on. + edit_item_with(h, item, |h| { + if let Some((r, pct)) = scale(h)? { + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; } - let pct = size / now * 100.0; - let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; - command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; Ok(()) })?; Ok(Data::Undefined) diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 4669876304..f902c9a3b6 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -496,6 +496,28 @@ impl Session { true } + /// Measure the type not measured yet in the open document with [`DocState::uid`] `uid` when it is + /// in the back, as [`Session::measure_back_document`] does, so bounds read from it are the ones + /// it has once it comes to the front. A document in front, or one with all its type measured, + /// is left as it is. A document unchanged since it was last measured or checked here is not + /// walked again ([`DocState::measured_in_own`]; with no composite font names kept, its coming + /// to the front measures again what it would have measured without the check). + pub(crate) fn measure_back_type(&mut self, uid: u64) { + let Some(index) = self.docs.iter().position(|d| d.uid == uid) else { return }; + if self.active == Some(index) { + return; + } + let st = &mut self.docs[index]; + if st.measured_in_own.as_ref().is_some_and(|(doc, _)| std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))) { + return; + } + if text_trees(&st.doc).any(|n| has_text_where(n, &mut |t| t.cached_bounds.is_none())) { + self.measure_back_document(index); + } else { + st.measured_in_own = Some((Arc::downgrade(&st.doc), HashSet::new())); + } + } + /// Measure the type not measured yet in open document `index`, which is in the back, in its own /// composite fonts, lent for the measuring, so its type has the bounds it will have when the /// document comes to the front: type naming a composite font the document does not define is diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f731eef72d..975de6a42a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -186,6 +186,58 @@ fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); } +/// The getters measure type in a document in the back as the setters do, so assigning an item's +/// own width, height, left, top or position back to it changes nothing and makes no undo step, +/// and for an object without type the document is not switched to. +#[test] +fn page_item_geometry_read_from_a_back_document_assigns_back_without_a_change() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap()); + let uid = s.active().unwrap().uid; + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let front = s.active().unwrap().uid; + let back = |s: &Session| s.documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.history.undo.len()); + let steps = back(&s); + let sets = ["t.width = t.width;", "t.height = t.height;", "t.left = t.left;", "t.top = t.top;", "t.position = t.position;"]; + for (kind, set) in sets.iter().flat_map(|set| [("TextFrame", set), ("PathItem", set)]) { + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + // A switch to the back document and back again would stamp the front document anew. + let stamp = s.active().unwrap().activated; + let out = log( + &mut s, + &format!( + "var p = app.documents[1].pageItems, t = p[0].typename == '{kind}' ? p[0] : p[1];\ + var w = t.width, x = t.left; {set} vc.log(t.width - w); vc.log(t.left - x);" + ), + ); + assert_eq!(out.len(), 2, "{kind} {set}"); + for d in &out { + assert!(d.as_f64().unwrap().abs() < 1e-6, "{kind} {set} moved or resized the item by {d}"); + } + assert_eq!(back(&s), steps, "{kind} {set} made an undo step"); + if kind == "PathItem" { + assert_eq!(s.active().unwrap().activated, stamp, "{set} switched documents"); + } + } + assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + let in_back = log(&mut s, "vc.log(app.documents[1].pageItems[0].width);"); + let index = s.documents().iter().position(|d| d.uid == uid).unwrap(); + s.execute("document.activate", &json!({"index": index})).unwrap(); + let in_front = log(&mut s, "vc.log(app.activeDocument.pageItems[0].width);"); + assert_eq!(in_back, in_front, "the width read in the back is the width read in front"); +} + /// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the /// visible bounds. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index c85072f573..ec746539dc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3106,7 +3106,10 @@ through `$`: 100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"` (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds, widened to take in the direction points of every path in the object), `editable` (false for an + visible bounds, widened to take in the direction points of every path in the object; in a document in the back, type + not measured yet is measured first, as the switch to that document would measure it; a valid + `position`, `left`, `top`, `width` or `height` equal to the value an object that holds no type, symbol instance + or placed document already has is not applied, and its document stays in the back), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`