diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index bf61be91a5..db0352750b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -41,11 +41,13 @@ //! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too. //! - `PathPoint.selected` and `selectedPathPoints` count every point of a path selected as a whole //! as a selected anchor point, and not the endpoints of selected segments; a path in a selected -//! group is not selected as a whole. Direction handles are not selected on their own, so -//! `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they are not -//! available yet. A clipping path cannot be made a guide. Assigning `guides` on a path inside a -//! compound path throws an error that says it is not available yet, on a path that cannot be -//! edited or selected throws `Cannot edit`, and while guides are locked throws an error. +//! group or compound path is selected as a whole. Direction handles are not selected on their +//! own, so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they +//! are not available yet, and so does `NOSELECTION` on a point of a path in a selected group or +//! compound path. Selecting a point of a guide while guides are locked throws an error. A +//! clipping path cannot be made a guide. Assigning `guides` on a path inside a compound path +//! throws an error that says it is not available yet, on a path that cannot be edited or +//! selected throws `Cannot edit` for both values, and while guides are locked throws an error. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, //! so `changeFillGradients` false throws an error that says it is not available yet. @@ -617,7 +619,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { if member { return Err(HostError::Error(COMPOUND_MEMBER_GUIDES.into())); } - if !editable || (on && !selectable) { + if !editable || !selectable { return Err(cannot_edit(item.id)); } if h.session.borrow().menu.guides_locked { @@ -1379,10 +1381,20 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(path_ref(h, item)) } +/// Whether the path `id` is not selected itself but a group or compound path that holds it is, +/// which selects the path as a whole. +fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) -> bool { + !sel.contains(id) && d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer()))) +} + /// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every -/// point of a path selected as a whole is, and of a path with direct-selected anchors only those -/// anchors are. The endpoints of selected segments are not. -fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, subs: &[SubPath], i: usize) -> bool { +/// point of a path selected as a whole is (a path is when a group or compound path that holds it +/// is selected, `held`), and of a path with direct-selected anchors only those anchors are. The +/// endpoints of selected segments are not. +fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[SubPath], i: usize) -> bool { + if held { + return true; + } if !sel.contains(id) || sel.segments.contains_key(&id) { return false; } @@ -1392,11 +1404,27 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, subs: &[SubPath], i: } } +/// Whether the subpaths `a` and `b` have the same number of points in the same subpaths, so that a +/// point index names the same anchor in both. +fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.anchors.len() == y.anchors.len()) +} + /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point -/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. +/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in +/// [`super::State`] are written first only when they add or remove points of this path, since +/// the selection names anchors by their place in the document's path. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - let on = read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, &pd.subpaths, i))?; + let moved = match &*h.dom.pending.borrow() { + Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + _ => false, + }; + if moved { + super::flush(h)?; + } + let on = + read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), &pd.subpaths, i))?; Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into())) } @@ -1406,7 +1434,9 @@ const HANDLE_SELECTIONS: &[&str] = &["PathPointSelection.LEFTDIRECTION", "PathPo /// `selected = PathPointSelection.ANCHORPOINT` adds the point to the direct-selected anchors, and /// `NOSELECTION` removes it, with `select.anchorsMany`; the other selected objects and anchors stay /// selected. A value the point has already runs no command. Direction handles cannot be selected, -/// so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error. +/// so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error, and so does +/// `NOSELECTION` on a path selected through a group or compound path that holds it, and +/// `ANCHORPOINT` on a guide while guides are locked. fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { let on = match arg(a, 1) { Data::String(s) if s == "PathPointSelection.ANCHORPOINT" => true, @@ -1417,18 +1447,30 @@ fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { _ => return Err(HostError::Type("selected must be a PathPointSelection value".into())), }; let (item, i) = this_point(h, a)?; - let (now, at, selectable) = with_doc(h, item.doc, |_, st| { - let subs = st.doc.node(item.id).and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); + let (now, at, selectable, held, guide) = with_doc(h, item.doc, |_, st| { + let node = st.doc.node(item.id); + let subs = node.and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); + let guide = node.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })); let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); - (anchor_selected(&st.selection, item.id, subs, i), locate(subs, i), selectable) + let held = held_selected(&st.doc, &st.selection, item.id); + (anchor_selected(&st.selection, item.id, held, subs, i), locate(subs, i), selectable, held, guide) }); if now == on { return Ok(Data::Undefined); } let Some((s, j)) = at else { return Err(HostError::Error(STALE_POINT.into())) }; + if held { + return Err(HostError::Error(format!( + "PathPoint.selected = PathPointSelection.NOSELECTION is not available yet on PathItem {}: the group or compound path that holds it is selected", + item.id.0 + ))); + } if on && !selectable { return Err(HostError::Error(format!("Cannot select PathItem {}", item.id.0))); } + if on && guide && h.session.borrow().menu.guides_locked { + return Err(HostError::Error(format!("Cannot select PathItem {}: guides are locked", item.id.0))); + } let params = json!({"items": [{"id": item.id.0, "anchors": [[s, j]]}], "mode": if on { "add" } else { "subtract" }}); on_doc(h, item.doc.uid, false, |h| command(h, "select.anchorsMany", ¶ms))?; Ok(Data::Undefined) @@ -1440,14 +1482,15 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; - if !sel.contains(item.id) || sel.segments.contains_key(&item.id) { + let held = held_selected(&st.doc, sel, item.id); + if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { return Vec::new(); } let mut out = Vec::new(); let mut first = 0; for (s, sp) in pd.subpaths.iter().enumerate() { let n = sp.anchors.len(); - out.extend((0..n).filter(|j| sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); + out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); first += n; } out @@ -1555,7 +1598,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("leftDirection", point_property(l, pt_left, pt_set_left)), ("rightDirection", point_property(l, pt_right, pt_set_right)), ("pointType", point_property(l, pt_type, pt_set_type)), - ("selected", property(l, pt_selected, pt_set_selected)), + ("selected", HostMember::Property { get: super::point_function(l, pt_selected), set: super::function(l, pt_set_selected) }), ("remove", point_method(l, pt_remove)), ]), None, diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b8fdf6673d..43ce225e82 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -939,12 +939,39 @@ fn a_path_selected_as_a_whole_has_every_point_selected() { } #[test] -fn a_path_in_a_selected_group_is_not_selected_as_a_whole() { - let (mut s, a, b) = doc(); - s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); - s.execute("object.group", &json!({})).unwrap(); - let out = log(&mut s, "var ps = app.activeDocument.pathItems; vc.log([ps[0].selectedPathPoints.length, ps[1].selectedPathPoints.length]);"); - assert_eq!(out, vec![json!([0, 0])]); +fn a_path_in_a_selected_group_or_compound_path_is_selected_as_a_whole() { + for make in ["object.group", "object.compoundPath.make"] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute(make, &json!({})).unwrap(); + let sel = format!("{:?}", s.active().unwrap().selection); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var ps = app.activeDocument.pathItems; vc.log([ps[0].selectedPathPoints.length, ps[1].selectedPathPoints.length]);\ + vc.log(ps[0].pathPoints[2].selected); ps[0].pathPoints[2].selected = PathPointSelection.ANCHORPOINT;\ + try { ps[0].pathPoints[2].selected = PathPointSelection.NOSELECTION; } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out[..2], [json!([4, 4]), json!("PathPointSelection.ANCHORPOINT")], "{make}"); + assert!(out[2].as_str().is_some_and(|m| m.contains("not available yet")), "{make}: {out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().selection), sel, "{make}: the selection stays as it was"); + assert_eq!(undo_steps(&s), steps, "{make}"); + } +} + +#[test] +fn reading_selected_while_moving_points_writes_the_path_once() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = run( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + for (var i = 0; i < pp.length; i++) if (pp[i].selected == PathPointSelection.ANCHORPOINT) pp[i].anchor = [pp[i].anchor[0] + 1, pp[i].anchor[1]];", + ) + .unwrap(); + let calls: Vec = + r["slowestCommands"].as_array().unwrap().iter().filter(|c| c["id"] == "path.setAnchors").map(|c| c["calls"].as_u64().unwrap()).collect(); + assert_eq!(calls, vec![1], "{r}"); } #[test] @@ -960,6 +987,60 @@ fn path_point_selected_refuses_handles_bad_values_and_locked_paths() { assert!(s.active().unwrap().selection.is_empty()); } +/// The ways an editable path cannot be selected: on a locked artboard, and outside the isolated +/// object. +const UNSELECTABLE: [&str; 2] = ["locked artboard", "isolation"]; + +/// Makes the paths of [`doc`] other than `b` editable but not selectable, as `case` names. +fn lock_out(s: &mut Session, case: &str, b: NodeId) { + if case == "isolation" { + s.execute("object.isolate", &json!({"id": b.0})).unwrap(); + } else { + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + } +} + +#[test] +fn path_point_selected_refuses_paths_on_locked_artboards_and_outside_isolation() { + for case in UNSELECTABLE { + let (mut s, a, b) = doc(); + lock_out(&mut s, case, b); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("Cannot select"), "{case}: {e}"); + assert!(!s.active().unwrap().selection.contains(a), "{case}"); + } +} + +#[test] +fn selecting_a_point_of_a_guide_throws_while_guides_are_locked() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("guides are locked"), "{e}"); + assert!(!s.active().unwrap().selection.contains(a)); +} + +#[test] +fn assigning_guides_refuses_paths_that_cannot_be_selected() { + for case in UNSELECTABLE { + let (mut s, a, b) = doc(); + lock_out(&mut s, case, b); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(e.contains("Cannot edit"), "{case}: {e}"); + assert!(!is_guide(&s, a), "{case}"); + } + // A guide is on no locked artboard, so only isolation keeps a guide from being released. + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(is_guide(&s, a)); + lock_out(&mut s, "isolation", b); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = false;"); + assert!(e.contains("Cannot edit"), "{e}"); + assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide"); +} + fn is_guide(s: &Session, id: NodeId) -> bool { matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) } @@ -986,8 +1067,11 @@ fn assigning_guides_makes_and_releases_a_guide() { s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); - log(&mut s, "app.activeDocument.pathItems[1].guides = true;"); - assert!(is_guide(&s, a) != is_guide(&s, b), "only the assigned path in the group is a guide"); + log(&mut s, "var p = app.activeDocument.pathItems[1]; p.name = 'assigned'; p.guides = true;"); + let (assigned, other) = if node(&s, a).name.as_deref() == Some("assigned") { (a, b) } else { (b, a) }; + assert_eq!(node(&s, assigned).name.as_deref(), Some("assigned")); + assert_eq!((is_guide(&s, assigned), is_guide(&s, other)), (true, false), "only the assigned path in the group is a guide"); + assert!(s.active().unwrap().selection.is_empty(), "the selection stays as it was"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 78a863a2b1..103c6f7ee8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2734,13 +2734,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, - and the endpoints of selected segments are not; a path is selected as a whole only when it is itself selected, not - when a group that holds it is. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, - `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and selecting - a point of a path that cannot be selected throws `Cannot select`. A clipping path cannot be made a guide, and - `guides = true` on one throws an error; assigning `guides` on a path inside a compound path throws an error that says - it is not available yet, on a path that is hidden, locked or cannot be selected throws `Cannot edit`, and while - guides are locked throws an error for either value. Color components left out + and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. + Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` + to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a + path in a selected group or compound path. Selecting a point of a path that cannot be selected throws `Cannot + select`, and selecting a point of a guide while guides are locked throws an error. A clipping path cannot be made a + guide, and `guides = true` on one throws an error; assigning `guides` on a path inside a compound path throws an + error that says it is not available yet, assigning either value on a path that is hidden, locked or cannot be + selected throws `Cannot edit`, and assigning either value while guides are locked throws an error. Color + components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest