diff --git a/Cargo.lock b/Cargo.lock index 4b8205c9f0..d7b77b1065 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8538,7 +8538,6 @@ dependencies = [ "raw-window-handle", "rustix 1.1.6", "serde_json", - "socket2", "tempfile", "vectorcraft-engine", "vectorcraft-render", diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index c220474112..ce4d1d3d44 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -20,10 +20,11 @@ vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } craft = { workspace = true, features = ["ui", "keymap", "automation", "platform"] } egui = { workspace = true } -egui_extras = { workspace = true } log = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] +# Image loaders for `src/web.rs`, which builds only for wasm32. +egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 1c3e7f39e7..d17c96eaf7 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -129,5 +129,3 @@ winresource = "0.1" [dev-dependencies] tempfile = "3" -# Bound socket buffers in real loopback transport deadline regressions. -socket2 = { workspace = true } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 121f12aaeb..bb4dcbd416 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -446,6 +446,66 @@ impl Drop for InMask { } } +thread_local! { + /// While an [`InteriorProbe`] lives, whether a leaf tested without + /// [`HitOptions::unfilled_interiors`] would have been hit inside an unfilled closed path with + /// it; `None` outside a probe. + static INTERIOR_SEEN: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// While a guard lives, the leaves tested without [`HitOptions::unfilled_interiors`] note whether +/// they would be hit inside an unfilled closed path with it ([`unfilled_inside`]). A walk that hits +/// nothing then looks inside the unfilled closed paths with a second walk only when one of them +/// holds the point. +struct InteriorProbe { + was: Option, +} + +impl InteriorProbe { + /// A probe when `wanted`, the walk that follows a miss looking inside unfilled closed paths. + /// Otherwise the guard leaves things as they are, and no leaf measures an interior for it. + fn open(wanted: bool) -> Self { + Self { was: if wanted { INTERIOR_SEEN.replace(Some(false)) } else { INTERIOR_SEEN.get() } } + } + + /// Did a leaf tested since [`Self::open`] have an unfilled closed path holding the point? + fn seen(&self) -> bool { + INTERIOR_SEEN.get() == Some(true) + } +} + +impl Drop for InteriorProbe { + fn drop(&mut self) { + // A probe opened inside another passes what it saw on to it. + let seen = INTERIOR_SEEN.get() == Some(true); + INTERIOR_SEEN.set(self.was.map(|was| was || seen)); + } +} + +/// The hit inside path or compound path `n`'s closed subpaths, which have no visible fill, when +/// `n` takes one there ([`takes_interior`]) and `contains` says they hold the point. Without +/// [`HitOptions::unfilled_interiors`], under an [`InteriorProbe`], notes whether `n` would take +/// one with it, and hits nothing. +fn unfilled_inside(n: &Node, opt: HitOptions, contains: impl FnOnce() -> bool) -> Option { + if takes_interior(n, opt) { + return contains().then_some(HitKind::Fill); + } + if INTERIOR_SEEN.get() == Some(false) && takes_interior(n, HitOptions { unfilled_interiors: true, ..opt }) { + #[cfg(test)] + INTERIORS_PROBED.with(|c| c.set(c.get() + 1)); + if contains() { + INTERIOR_SEEN.set(Some(true)); + } + } + None +} + +#[cfg(test)] +thread_local! { + /// How many interiors [`unfilled_inside`] measured for an [`InteriorProbe`] on this thread. + static INTERIORS_PROBED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a /// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to /// the region it clips to. It is also under an [`InMask`] guard. @@ -667,10 +727,15 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option bool, editable_only: bool) -> Option { + let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !opt.outline); let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only); - if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline { + if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline || !probe.seen() { return painted; } + drop(probe); hit_test_walk(doc, p, opt, skip, editable_only) } @@ -1672,8 +1740,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio match &n.kind { NodeKind::Path { path, rule, .. } => { let has_fill = n.appearance.has_visible_fill(); - let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt); - let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill); + let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed); + let inside = || interior.then(|| unfilled_inside(n, opt, || fill_contains(&closed_subpaths_at([path], p), *rule, p))).flatten(); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -1740,7 +1808,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill); } let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p); - (takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill) + unfilled_inside(n, opt, || fill_contains(&closed(), *rule, p)) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -2121,11 +2189,14 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; find.find(&art.art, &mut path, None, outline).map(|_| path) }; - // As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit. + // As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit, and only + // when the first walk passes one holding `p` ([`InteriorProbe`]). + let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !outline); pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| { - if !opt.unfilled_interiors || opt.path_only || outline { + if !opt.unfilled_interiors || opt.path_only || outline || !probe.seen() { return None; } + drop(probe); walk.restart(); pick(opt) }) diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 7ac945e4ee..2f51917dde 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -200,6 +200,88 @@ fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() { assert_eq!(at(220.0), None, "inside the clipping path where no art paints"); } +/// An open path with a black stroke and no fill, from (`o`, 0) to (100, `o`) to (100, 100): its box +/// holds (50, 50), and it is drawn nowhere near that point. +fn open_corner(d: &mut Document, o: f64) -> Node { + let pts = [Point::new(o, 0.0), Point::new(100.0, o), Point::new(100.0, 100.0)]; + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)); + Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)) +} + +/// How many leaves [`hit_leaf`] tested while `f` ran, with its result. +fn leaves_tested(f: impl FnOnce() -> R) -> (R, usize) { + LEAVES_TESTED.with(|c| c.set(0)); + let r = f(); + (r, LEAVES_TESTED.with(std::cell::Cell::get)) +} + +/// A selection click that hits nothing, where no unfilled closed path holds the point, walks the +/// document once: looking inside unfilled closed paths tests no more leaves than a click without +/// it. An unfilled closed path that holds the point is still hit inside. +#[test] +fn a_selection_click_that_hits_nothing_walks_the_document_once() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + for i in 0..10 { + let corner = open_corner(&mut d, f64::from(i)); + d.insert(Some(l), 99, corner).unwrap(); + } + let p = Point::new(50.0, 50.0); + let (hit, without) = leaves_tested(|| hit_test(&d, p, SELECTING)); + assert_eq!(hit, None); + assert_eq!(without, 10); + let (hit, with) = leaves_tested(|| hit_test(&d, p, INTERIORS)); + assert_eq!(hit, None); + assert_eq!(with, without, "hit_test"); + let (tops, with) = leaves_tested(|| objects_at(&d, p, INTERIORS, None)); + assert!(tops.is_empty()); + assert_eq!(with, without, "objects_at"); + // An unfilled frame below them that holds the point: the second walk finds it. + let frame = d.alloc_id(); + let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + d.insert(Some(l), 0, Node::path(frame, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap(); + assert_eq!(hit_test(&d, p, INTERIORS).map(|h| h.leaf), Some(frame)); + assert_eq!(objects_at(&d, p, INTERIORS, None), vec![frame]); +} + +/// A hit test that does not look inside unfilled closed paths measures none of their interiors. +#[test] +fn a_hit_test_without_unfilled_interiors_measures_no_interior() { + let mut d = Document::new(200.0, 200.0); + stroked(&mut d, &FRAME, true); + let p = Point::new(50.0, 50.0); + let probed = |f: &dyn Fn()| { + INTERIORS_PROBED.with(|c| c.set(0)); + f(); + INTERIORS_PROBED.with(std::cell::Cell::get) + }; + assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, SELECTING), None)), 0, "hit_test"); + assert_eq!(probed(&|| assert!(objects_at(&d, p, SELECTING, None).is_empty())), 0, "objects_at"); + assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, HitOptions { path_only: true, ..INTERIORS }), None)), 0, "by path only"); + assert_eq!(probed(&|| assert!(hit_test(&d, p, INTERIORS).is_some())), 1, "looking inside"); +} + +/// Direct Selection on a dynamic symbol's instance that picks no part of its art, where no +/// unfilled closed path of the art holds the point, walks the art once. +#[test] +fn a_symbol_part_pick_that_hits_nothing_walks_the_art_once() { + let mut d = Document::new(200.0, 200.0); + let corners: Vec> = (0..10).map(|i| Arc::new(open_corner(&mut d, f64::from(i)))).collect(); + let root = Node::group(d.alloc_id(), corners); + d.symbols.push(crate::Symbol { dynamic: true, name: "Corners".into(), art: Arc::new(root) }); + let l = d.layers[0].id; + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corners".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + let n = d.node(inst).unwrap(); + let p = Point::new(50.0, 50.0); + let (part, without) = leaves_tested(|| symbol_part_at(&d, n, p, SELECTING)); + assert_eq!(part, None); + assert!(without >= 10, "{without} leaves tested"); + let (part, with) = leaves_tested(|| symbol_part_at(&d, n, p, INTERIORS)); + assert_eq!(part, None); + assert_eq!(with, without); +} + #[test] fn long_plain_stroke_hits_its_middle_and_curved_end() { let mut d = Document::new(200.0, 200.0); @@ -3569,3 +3651,26 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() { assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape"); assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face"); } + +/// The pointer resting over empty canvas past many paths reads their anchors for their culling +/// boxes on the first hover only: the next hovers use the boxes the paths keep. +#[test] +fn hovers_past_many_paths_read_their_anchors_once() { + use vectorcraft_geom::anchors::measured_control_anchors; + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + for i in 0..100 { + let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0); + d.insert(Some(l), 0, n).unwrap(); + } + let empty = Point::new(900.0, 900.0); + let before = measured_control_anchors(); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = measured_control_anchors() - before; + assert!(first >= 400, "the first hover reads every square's anchors: {first}"); + for _ in 0..3 { + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + } + assert_eq!(measured_control_anchors() - before, first, "later hovers read no anchor"); + assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit"); +} diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index facf010415..25269a62e5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2140,6 +2140,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result { /// `name = value`: a number or a Boolean becomes the text `String(value)` gives. fn item_set_name(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let name = &text_arg(arg(a, 1), "name")?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); @@ -2158,11 +2159,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer { /// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number /// or a Boolean becomes the text `String(value)` gives. fn item_set_note(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let note = &text_arg(arg(a, 1), "note")?; if note.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the note is too long".into())); } - let item = this_item(h, a)?; let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim())); if !same { edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?; @@ -2196,8 +2197,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer { } fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let hidden = boolean(arg(a, 1), "hidden")?; - refuse_protected_edit(h, this_item(h, a)?)?; + refuse_protected_edit(h, item)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -2206,8 +2208,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { } fn item_set_locked(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let locked = boolean(arg(a, 1), "locked")?; - refuse_protected_edit(h, this_item(h, a)?)?; + refuse_protected_edit(h, item)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -2216,6 +2219,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer { } fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let v = number(arg(a, 1), "opacity")?; if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); @@ -2225,7 +2229,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // replaces the one the graph keeps for its series or kind. // The opacity the item already has may be assigned while its layer is hidden or locked, unless // it would still replace the opacity a graph keeps for the item's series or kind. - let item = this_item(h, a)?; let (now, keeps_other) = with_doc(h, item.doc, |_, st| { let d = &st.doc; // Only the exact number the getter reports counts as the same opacity. @@ -2271,12 +2274,12 @@ fn item_blending_mode(h: &Host, a: &[Data]) -> Answer { /// The mode the object already has may be assigned while its layer is hidden or locked, unless it /// would still replace the blend mode a graph keeps for the item's series or kind. fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; let mode = match arg(a, 1) { Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode), _ => None, }; let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?; - let item = this_item(h, a)?; let (same, keeps_other) = with_doc(h, item.doc, |_, st| { let d = &st.doc; let same = d.node(item.id).is_some_and(|n| n.blend == mode); @@ -2403,16 +2406,19 @@ fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { } fn item_set_position(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let p = point(arg(a, 1), "position")?; move_to(h, a, Some(p[0]), Some(p[1])) } fn item_set_left(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let x = coordinate(arg(a, 1), "left")?; move_to(h, a, Some(x), None) } fn item_set_top(h: &Host, a: &[Data]) -> Answer { + this_item(h, a)?; let y = coordinate(arg(a, 1), "top")?; move_to(h, a, None, Some(y)) } @@ -2421,12 +2427,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer { /// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated /// objects included. fn resize(h: &Host, a: &[Data], width: bool) -> Answer { + let item = this_item(h, a)?; let what = if width { "width" } else { "height" }; let size = number(arg(a, 1), what)?; if size <= 0.0 || size > MAX_SIZE { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } - let item = this_item(h, a)?; refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 27b449a5b9..e4f6bb203e 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1225,7 +1225,26 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; - path_at(h, *run, *uid, *high, *low) + let item = path_at(h, *run, *uid, *high, *low)?; + flush_other(h, item)?; + Ok(item) +} + +/// Writes the waiting point changes of another path in the same Objects on Path group as `item`. +fn flush_other(h: &super::Host, item: Item) -> std::result::Result<(), HostError> { + let waiting = h.dom.pending.borrow().as_ref().map(|(w, _)| *w); + let other = waiting.is_some_and(|w| { + w.doc.uid == item.doc.uid + && w.id != item.id + && with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let read = d.ancestry(item.id).unwrap_or_default(); + d.ancestry(w.id).is_some_and(|a| { + a.iter().any(|g| read.contains(g) && d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)) + }) + }) + }); + if other { flush(h) } else { Ok(()) } } /// `typename` of the points of a path that is still in its document. @@ -1322,7 +1341,8 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// the object model is changing ([`super::State`]), or that object itself, take the change as the /// object model's own, and their points stay valid. A document that is the one the run last looked /// at is skipped, as are its paths. While the object model writes one path's points -/// ([`super::State`]'s `one_path`), only that path is looked at in its document. +/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing +/// Objects on Path group are looked at in its document. pub(super) fn see_all_points(h: &super::Host) { let keys: Vec<(u64, u64)> = { let seen = h.dom.point_nodes.borrow(); @@ -1335,9 +1355,24 @@ pub(super) fn see_all_points(h: &super::Host) { let mut keys = Vec::new(); // The documents that changed since the last look, kept as they are now. for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) { + // Editing a path in an Objects on Path group can move other paths in the group. + let mut moved = Vec::new(); match s.documents().iter().find(|d| d.uid == *uid) { Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue, Some(st) => { + if let Some(item) = one.filter(|i| i.doc.uid == *uid) { + let d = &st.doc; + let group = d.ancestry(item.id).and_then(|a| { + a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g)) + }); + if let Some(g) = group { + g.walk(&mut |n: &crate::doc::Node| { + if n.id != item.id && paths.contains_key(&n.id.0) { + moved.push((*uid, n.id.0)); + } + }); + } + } docs.insert(*uid, st.doc.clone()); } None => { @@ -1345,7 +1380,10 @@ pub(super) fn see_all_points(h: &super::Host) { } } match one { - Some(item) if item.doc.uid == *uid => keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0))), + Some(item) if item.doc.uid == *uid => { + keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0))); + keys.append(&mut moved); + } _ => keys.extend(paths.keys().map(|id| (*uid, *id))), } } @@ -1432,6 +1470,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; let item = path_at(h, *run, *uid, *high, *low)?; + flush_other(h, item)?; if whole(*cuts) != Some(point_cuts(h, item)) { return Err(HostError::Error(STALE_POINT.into())); } @@ -1664,38 +1703,69 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let sel = &st.selection; (sel.anchors.contains_key(&item.id) || sel.segments.contains_key(&item.id)).then(|| sel.clone()) }; + // Writing the points can prune the selection, and selecting loads the selected paths' paint + // into new art, so new art's paint, the defaults a script set included, is put back. + keeping_paint(h, || remove_point(h, item, i, selected))?; + cut_points(h, item); + Ok(Data::Undefined) +} + +/// Removes point `i` of the path of `item` for [`pt_remove`], and renumbers `selected`, the +/// direct selection of the path's points before the removal. +fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option) -> std::result::Result<(), HostError> { let removed = edit_points(h, item, |subs| { let (s, j) = locate(subs, i)?; let sp = subs.get_mut(s)?; - // The segment that closes a closed subpath ends at its first anchor. - let closing = (sp.closed && j == 0).then(|| sp.anchors.len() - 1); + // The segment that closes a closed subpath runs from its last anchor to its first. + let last = sp.closed.then(|| sp.anchors.len() - 1); sp.anchors.remove(j); let gone = sp.anchors.is_empty(); if gone { subs.remove(s); } - Some((s, j, gone, closing)) + Some((s, j, gone, last)) })?; - if let (Some((s, j, gone, closing)), Some(mut sel)) = (removed, selected) { - // The points are written first, and the selection is then set with selection commands, - // which the journal records with the edit. - flush(h)?; - renumber_selected(&mut sel, item.id, s, j, gone, closing); - on_doc(h, item.doc.uid, false, |h| { - let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - super::restore_selection(h, &doc, &sel) - })?; + if let (Some((s, j, gone, last)), Some(before)) = (removed, selected) { + let mut sel = before.clone(); + renumber_selected(&mut sel, item.id, s, j, gone, last); + // A selection the removal leaves as it was waits with the points, so that removals in a + // row are written together, unless its anchors are now all of the path's, which selects + // the path whole, or the path is in an Objects on Path group, which places it again. + let wait = sel == before && { + let valid = read_points(h, item, |subs| { + sel.anchors.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| *k < sp.anchors.len()))) + && sel.segments.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| sp.has_segment(*k, true)))) + })?; + let total = points_of(h, item)?; + let all = sel.anchors.get(&item.id).is_some_and(|a| a.len() >= total) && !sel.segments.contains_key(&item.id); + let on_path = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + d.ancestry(item.id).is_some_and(|a| a.iter().any(|g| d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))) + }); + valid && !all && !on_path + }; + if !wait { + // The points are written first, and the selection is then set with selection + // commands, which the journal records with the edit. + flush(h)?; + on_doc(h, item.doc.uid, false, |h| { + let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + super::restore_selection(h, &doc, &sel) + })?; + } } - cut_points(h, item); - Ok(Data::Undefined) + Ok(()) } /// Updates the direct selection `sel` of the path `id` after the anchor `j` of its subpath `s` was /// removed, and the subpath with it when `gone`: the anchor, the segments it ended and their other /// ends leave the selection, unless a segment still selected ends there, and the anchors, segments -/// and subpaths after it keep the points they selected. `closing` is the segment that closed the -/// subpath at the removed anchor, when it did. -fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, closing: Option) { +/// and subpaths after it keep the points they selected. `last` is the index of the subpath's last +/// anchor before the removal when the subpath is closed: its closing segment runs from that anchor +/// to anchor 0. +fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, last: Option) { + // The closing segment ends at the removed anchor when the removed anchor is the first one. + let closing = last.filter(|_| j == 0); // An anchor (or a segment, by its first anchor) after the removed one moves down one place. let shift = |(p, k): (usize, usize), segment: bool| -> Option<(usize, usize)> { match p.cmp(&s) { @@ -1713,7 +1783,14 @@ fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: u let cut: Vec<(usize, usize)> = segments.iter().copied().filter(|g| shift(*g, true).is_none() && g.0 == s && !gone).collect(); for (p, k) in cut { // Segment k runs from anchor k to anchor k + 1; one of the two is the removed one. - let other = if k == j { k + 1 } else { k }; + // The closing segment of a closed subpath ends at anchor 0. + let other = if k != j { + k + } else if last == Some(k) { + 0 + } else { + k + 1 + }; // The closing segment's other end is its first anchor, the old last one. let other = if closing == Some(k) { k } else { other }; ends.extend(shift((p, other), false)); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 03cab27e93..bb333e91d8 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1702,6 +1702,29 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +/// A setter on a removed item reports the stale item before it checks the value it was given. +#[test] +fn setters_on_a_stale_item_report_it_before_a_bad_value() { + let (mut s, _, _) = doc(); + for set in [ + "name = {}", + "note = {}", + "hidden = 'x'", + "locked = 'x'", + "opacity = 500", + "blendingMode = 'x'", + "selected = 'x'", + "position = 'x'", + "left = 'x'", + "top = 'x'", + "width = -1", + "height = -1", + ] { + let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0].duplicate(); i.remove(); i.{set};")); + assert!(e.contains("Stale page item"), "{set}: {e}"); + } +} + /// File › Revert loads objects with the ids they were saved with: an object or a layer read before /// the revert does not name the loaded one. #[test] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index d33246aba7..87f1c4f9ab 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -809,6 +809,221 @@ fn removing_a_point_keeps_the_direct_selection_on_the_same_anchors() { assert!(!s.active().unwrap().selection.objects.contains(&a)); } +/// Removing the last anchor of a closed path with only its closing segment selected takes the +/// segment's other end, the first anchor, out of the selection too. +#[test] +fn removing_the_last_point_deselects_the_closing_segment_and_its_first_anchor() { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 3]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();"); + assert_eq!(selected_anchors(&s, a), None, "the first anchor is not selected"); + assert!(!s.active().unwrap().selection.objects.contains(&a)); +} + +/// Removing a point that renumbers the selected anchors keeps the new-art stroke width a script +/// set, so the next path it draws gets it. +#[test] +fn removing_a_point_keeps_the_default_stroke_width_a_script_set() { + let (mut s, a, _) = doc(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.defaultStrokeWidth = 7; d.pathItems[0].pathPoints[0].remove();\ + vc.log(d.pathItems.rectangle(10, 10, 5, 5).strokeWidth);", + ); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1)])); + assert_eq!(out, [json!(7)]); +} + +/// Removals that leave the direct selection as it was are written together, with one +/// `path.setAnchors`. +#[test] +fn removals_that_keep_the_selection_are_written_together() { + let (mut s, a, _) = doc(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap(); + let start = s.journal.len(); + log(&mut s, "var q = app.activeDocument.pathItems[0].pathPoints; q[3].remove(); q[2].remove();"); + let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count(); + assert_eq!(writes, 1); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors.len(), 2); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); +} + +#[test] +fn removing_a_replacement_point_clears_selection_of_a_missing_subpath() { + for segments in [false, true] { + let (mut s, a, _) = doc(); + let anchors: Vec = (0..3).map(|x| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false})).collect(); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": [{"anchors": anchors, "closed": false}, {"anchors": anchors, "closed": false}]})) + .unwrap(); + if segments { + s.execute("select.segments", &json!({"id": a.0, "segments": [[1, 0]], "mode": "set"})).unwrap(); + } else { + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[1, 0]]}], "mode": "set"})).unwrap(); + } + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [20, 0], [30, 0]]);\ + p.pathPoints[3].remove(); vc.log(p.selected); vc.log(p.selectedPathPoints.length);", + ); + assert_eq!(out, [json!(false), json!(0)], "segments: {segments}"); + let path = node(&s, a); + let subs = &path.path_data().unwrap().subpaths; + assert_eq!(subs.len(), 1); + assert_eq!(subs[0].anchors.len(), 3); + assert_eq!(selected_anchors(&s, a), None); + let sel = &s.active().unwrap().selection; + assert!(!sel.segments.contains_key(&a)); + assert!(!sel.objects.contains(&a)); + } +} + +#[test] +fn reading_an_unrelated_path_keeps_point_edits_written_together() { + let (mut s, a, b) = doc(); + let before = node(&s, b); + let start = s.journal.len(); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, p = P[0].pathPoints, q = P[1].pathPoints;\ + p[0].anchor = [20, 30]; vc.log(q.length); vc.log(q[0].anchor); p[1].anchor = [50, 30];", + ); + let writes = s.journal.iter().skip(start).filter(|(id, _)| id == "path.setAnchors").count(); + assert_eq!(writes, 1); + assert_eq!(out, [json!(4), json!([100, 200])]); + assert_eq!(node(&s, b), before); + let edited = node(&s, a); + let anchors = &edited.path_data().unwrap().subpaths[0].anchors; + assert_eq!(anchors[0].p, vectorcraft_geom::Point::new(20.0, 270.0)); + assert_eq!(anchors[1].p, vectorcraft_geom::Point::new(50.0, 270.0)); +} + +/// Removing the one point that was not direct-selected leaves every point selected, which +/// selects the path whole. +#[test] +fn removing_the_only_unselected_point_selects_the_path_whole() { + let (mut s, a, _) = doc(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]}], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();"); + assert_eq!(selected_anchors(&s, a), None); + assert!(s.active().unwrap().selection.objects.contains(&a)); +} + +/// Removing a point of a direct-selected member of an Objects on Path group writes it at once, so +/// its points read where the group places it. +#[test] +fn removing_a_point_of_a_selected_member_reads_where_the_group_places_it() { + let (mut s, b) = doc_on_path(); + s.execute("select.anchorsMany", &json!({"items": [{"id": b.0, "anchors": [[0, 0]]}], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + m.pathPoints[3].remove(); m.pathPoints[2].remove(); vc.log(m.pathPoints[0].anchor);\ + P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor);", + ); + assert_eq!(out[0], out[1], "the member read where it is after the run"); +} + +/// [`doc`] with path `drive`, the path of an Objects on Path group that holds `b`, named `m`. +fn doc_on_path() -> (Session, NodeId) { + let (mut s, _, b) = doc(); + let c = rect(&mut s, 200.0, 50.0, 100.0, 100.0); + log(&mut s, "var p = app.activeDocument.pathItems; p[0].name = 'drive'; p[2].name = 'm';"); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.objectsOnPath.attach", &json!({"path": c.0, "ids": [b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + (s, b) +} + +/// Reading the points of a path writes the waiting point changes of another path first, so a +/// member of an Objects on Path group reads where the group's edited path moved it. +#[test] +fn reading_a_member_point_after_editing_its_group_path_reads_where_it_moved() { + let (mut s, _) = doc_on_path(); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\ + var x = m.pathPoints[0].anchor[0];\ + for (var i = 0; i < g.pathPoints.length; i++) { var q = g.pathPoints[i]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; }\ + vc.log(m.pathPoints[0].anchor[0] - x);\ + P.rectangle(0, 0, 1, 1); vc.log(P.getByName('m').pathPoints[0].anchor[0] - x);", + ); + assert_ne!(out[1], json!(0), "the member moved"); + assert_eq!(out[0], out[1], "the member read where it is after the run"); +} + +/// A member point read before the group's path is edited is stale afterwards, as the engine moved +/// the member, even when an undo puts the member back. +#[test] +fn a_member_point_read_before_its_group_path_changes_is_stale() { + let (mut s, _) = doc_on_path(); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, g = P.getByName('drive'), m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + var q = g.pathPoints[0]; q.anchor = [q.anchor[0] + 50, q.anchor[1]]; app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); +} + +#[test] +fn a_point_in_a_nested_member_is_stale_after_another_path_changes_and_undoes() { + let (mut s, a, b) = doc(); + log(&mut s, "var P = app.activeDocument.pathItems; P[0].name = 'edit'; P[1].name = 'm';"); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.active().unwrap().doc.parent_of(a).unwrap(); + let drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0); + s.execute("object.objectsOnPath.attach", &json!({"path": drive.0, "ids": [group.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = art(&s); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + +#[test] +fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_changes_and_undoes() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].name = 'drive';"); + s.execute("object.objectsOnPath.attach", &json!({"path": a.0, "ids": [b.0]})).unwrap(); + let inner = s.active().unwrap().doc.parent_of(a).unwrap(); + let sibling = rect(&mut s, 100.0, 200.0, 50.0, 50.0); + s.execute("object.setProps", &json!({"ids": [sibling.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [inner.0, sibling.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.active().unwrap().doc.parent_of(inner).unwrap(); + let outer_drive = rect(&mut s, 200.0, 50.0, 100.0, 100.0); + s.execute("object.objectsOnPath.attach", &json!({"path": outer_drive.0, "ids": [group.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]];\ + vc.log(m.pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the sibling outside the inner group moved"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('drive'), m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 50, q.anchor[1]]; app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + /// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. fn doc_with_paints() -> (Session, NodeId) { let (mut s, a, _) = doc(); diff --git a/crates/geom/src/anchors.rs b/crates/geom/src/anchors.rs index 57b8081686..3b9f4aa9bd 100644 --- a/crates/geom/src/anchors.rs +++ b/crates/geom/src/anchors.rs @@ -8,12 +8,16 @@ //! in and rebuilds the table, which has one entry per chunk. //! //! The list reads and writes as one flat sequence of anchors, as a `Vec` does. +//! +//! The list also keeps the box round its anchors' points and handles ([`Anchors::control_bounds`]) +//! once it has been measured, until the list changes. use std::borrow::Cow; use std::fmt; use std::ops::{Index, IndexMut, RangeBounds}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; +use kurbo::Rect; use serde::{Deserialize, Serialize}; use crate::path::Anchor; @@ -40,12 +44,49 @@ pub struct Anchors { ends: Vec, /// The number of anchors. len: usize, + /// The box round every anchor's point and handles, once measured; emptied by every change. + control: OnceLock, +} + +thread_local! { + /// [`measured_control_anchors`] of this thread. + static MEASURED_CONTROL_ANCHORS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many anchors [`Anchors::control_bounds`] has read on this thread. +pub fn measured_control_anchors() -> u64 { + MEASURED_CONTROL_ANCHORS.get() } impl Anchors { /// An empty list. pub const fn new() -> Self { - Self { chunks: Vec::new(), ends: Vec::new(), len: 0 } + Self { chunks: Vec::new(), ends: Vec::new(), len: 0, control: OnceLock::new() } + } + + /// The box round every anchor's point and handles, or `None` when the list is empty. The list + /// reads its anchors for it once, and again only after it has changed. + pub fn control_bounds(&self) -> Option { + if self.len == 0 { + return None; + } + Some(*self.control.get_or_init(|| { + MEASURED_CONTROL_ANCHORS.set(MEASURED_CONTROL_ANCHORS.get().saturating_add(self.len as u64)); + let mut r: Option = None; + for c in &self.chunks { + for a in c.iter() { + for p in [a.p, a.h_in, a.h_out] { + r = Some(r.map_or(Rect::from_points(p, p), |r| r.union_pt(p))); + } + } + } + r.unwrap_or_default() + })) + } + + /// Forget the measured [`Self::control_bounds`]: every change calls it. + fn changed(&mut self) { + self.control.take(); } /// The number of anchors. @@ -85,6 +126,7 @@ impl Anchors { if i >= self.len { return None; } + self.changed(); let (c, o) = self.locate(i); Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o) } @@ -101,11 +143,13 @@ impl Anchors { /// The first anchor to change. pub fn first_mut(&mut self) -> Option<&mut Anchor> { + self.changed(); Arc::make_mut(self.chunks.first_mut()?).first_mut() } /// The last anchor to change. pub fn last_mut(&mut self) -> Option<&mut Anchor> { + self.changed(); Arc::make_mut(self.chunks.last_mut()?).last_mut() } @@ -118,6 +162,7 @@ impl Anchors { /// The anchors in order, to change. Each chunk is copied, when another list shares it, as the /// iterator reaches it. pub fn iter_mut(&mut self) -> IterMut<'_> { + self.changed(); let chunk: fn(&mut Arc>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut(); self.chunks.iter_mut().flat_map(chunk) } @@ -177,6 +222,7 @@ impl Anchors { /// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks. fn reindex(&mut self) { + self.changed(); self.chunks.retain(|c| !c.is_empty()); self.len = self.chunks.iter().map(|c| c.len()).sum(); let n = self.chunks.len(); @@ -193,6 +239,7 @@ impl Anchors { /// Add `a` at the end. pub fn push(&mut self, a: Anchor) { + self.changed(); match self.chunks.last_mut() { Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a), _ => { @@ -210,6 +257,7 @@ impl Anchors { /// Remove the last anchor. pub fn pop(&mut self) -> Option { + self.changed(); let last = self.chunks.last_mut()?; let a = Arc::make_mut(last).pop(); if last.is_empty() { @@ -489,6 +537,7 @@ impl Index for Anchors { impl IndexMut for Anchors { /// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does. fn index_mut(&mut self, i: usize) -> &mut Anchor { + self.changed(); let (c, o) = self.locate(i); &mut Arc::make_mut(&mut self.chunks[c])[o] } @@ -501,7 +550,7 @@ impl From> for Anchors { } let len = v.len(); let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() }; - Self { chunks, ends: Vec::new(), len } + Self { chunks, ends: Vec::new(), len, control: OnceLock::new() } } } @@ -725,6 +774,8 @@ mod tests { } } assert_eq!(a.len(), v.len(), "step {step}"); + // The box kept from the step before is measured again after the edit. + assert_eq!(a.control_bounds(), Anchors::from(v.clone()).control_bounds(), "step {step}"); if step % 50 == 0 { assert_eq!(a, v, "step {step}"); for i in 0..v.len() { @@ -737,6 +788,60 @@ mod tests { assert_eq!(a.get(v.len()), None); } + /// The box of every anchor of `v` with its handles, measured anchor by anchor. + fn box_of(v: &[Anchor]) -> Option { + let mut it = v.iter().flat_map(|a| [a.p, a.h_in, a.h_out]); + let first = it.next()?; + Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p))) + } + + #[test] + fn control_bounds_read_the_anchors_once_until_they_change() { + let n = 1000; + let mut a = Anchors::from(line(n)); + let read = measured_control_anchors; + let before = read(); + assert_eq!(a.control_bounds(), box_of(&line(n))); + assert_eq!(read() - before, n as u64, "the first call reads every anchor"); + let copy = a.clone(); + for _ in 0..5 { + assert_eq!(a.control_bounds(), box_of(&line(n))); + assert_eq!(copy.control_bounds(), box_of(&line(n))); + } + assert_eq!(read() - before, n as u64, "later calls, and a copy's, read no anchor"); + // Every change measures again, and only the list that changed. + let far = Point::new(-50.0, 900.0); + type Edit = fn(&mut Anchors, Point); + let edits: [(&str, Edit); 11] = [ + ("get_mut", |a, p| a.get_mut(3).into_iter().for_each(|x| x.h_out = p)), + ("index_mut", |a, p| a[4].h_in = p), + ("first_mut", |a, p| a.first_mut().into_iter().for_each(|x| x.p = p)), + ("last_mut", |a, p| a.last_mut().into_iter().for_each(|x| x.p = p)), + ("iter_mut", |a, p| a.iter_mut().take(1).for_each(|x| x.p = p)), + ("push", |a, p| a.push(Anchor::corner(p))), + ("insert", |a, p| a.insert(1, Anchor::corner(p))), + ("pop", |a, _| { + let _ = a.pop(); + }), + ("remove", |a, _| { + let _ = a.try_remove(0); + }), + ("truncate", |a, _| a.truncate(10)), + ("reverse", |a, _| a.reverse()), + ]; + for (k, (what, edit)) in edits.iter().enumerate() { + let p = Point::new(far.x - k as f64, far.y + k as f64); + assert!(a.control_bounds().is_some()); + edit(&mut a, p); + let r = read(); + assert_eq!(a.control_bounds(), box_of(&a.to_vec()), "after {what}"); + assert_eq!(read() - r, a.len() as u64, "after {what}: measured again"); + } + assert_eq!(copy.control_bounds(), box_of(&line(n)), "the copy keeps its box"); + a.clear(); + assert_eq!(a.control_bounds(), None); + } + #[test] fn iterators_skip_and_count_as_a_slice_does() { let v = line(1000); diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index 5264414cb3..c5e857f017 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -745,11 +745,10 @@ impl PathData { } bbox } - /// Bounds including control handles (used for quick culling). + /// Bounds including control handles (used for quick culling). Each subpath keeps its own box + /// ([`Anchors::control_bounds`]) until its anchors change. pub fn control_bounds(&self) -> Option { - let mut it = self.subpaths.iter().flat_map(|s| s.anchors.iter()).flat_map(|a| [a.p, a.h_in, a.h_out]); - let first = it.next()?; - Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p))) + self.subpaths.iter().filter_map(|s| s.anchors.control_bounds()).reduce(|a, b| a.union(b)) } pub fn transform(&mut self, a: Affine) { for sp in &mut self.subpaths { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5b7221b7c2..6271e758d2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -814,8 +814,8 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print root.values.set(TabCloseLook::Glyph); // A collapsed panel column's icon groups stand apart by a hairline, as production drew them. root.values.set(IconGroupSeparator::Rule); - // New Document's preset cards show blank paper on a flat card, as production drew them. - root.values.set(PresetCardLook::Page); + // New Document's preset cards show blank paper on a card that rests on a tile, as production drew them. + root.values.set(PresetCardLook::PageTile); // A bare Tab on the canvas, or with nothing focused, toggles the panels (`window.dock`) instead of moving focus. root.tab_toggles_chrome = true; // Escape in a text field gives up its focus, reverting any typing, so the next keys are the window's. diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 3e8a78a618..584964e0c4 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1126,15 +1126,7 @@ macro_rules! style_dialog { } fn show(&mut self, ui: &mut egui::Ui, stack: &craft::ui::dialog::DialogStack) -> Option> { - // A measuring run can end without running the dialog's body and then sets the first tab as the - // shown one. The dialog keeps the tab that was shown before that run. - let measuring = craft::ui::runtime::measure::active(ui.ctx()); - let tab = self.inner.tab(); - let shown = craft::ui::dialog::StackDialog::show(&mut self.inner, ui, stack); - if measuring && self.inner.tab() != tab { - let _ = craft::ui::dialog::StackDialog::set_json_field(&mut self.inner, ui.ctx(), "tab", serde_json::json!(tab)); - } - shown + craft::ui::dialog::StackDialog::show(&mut self.inner, ui, stack) } fn key(&self) -> Option<&str> { diff --git a/crates/ui-egui/src/dialogs/char_style_options/tests.rs b/crates/ui-egui/src/dialogs/char_style_options/tests.rs index 258d925608..c779f4a9f6 100644 --- a/crates/ui-egui/src/dialogs/char_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/char_style_options/tests.rs @@ -1079,6 +1079,38 @@ fn new_character_style_refuses_size_and_leading_errors_at_ok() { } } +/// Character Style Options and New Character Style opened on a tab other than General still show that tab after +/// their first frames, which measure the dialog before its body runs. +#[test] +fn a_style_dialog_opened_on_a_later_tab_keeps_it_through_its_first_frames() { + use egui::{Pos2, RawInput, Rect, vec2}; + + let mut app = app(); + app.run("charStyle.new", json!({"name": "Body", "attrs": {}})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 0.25; + crate::testing::app_frame(app, &ctx, RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }); + }; + frame(&mut app); + open(&mut app, "Body"); + set::(&app, "tab", json!("advanced")); + for _ in 0..5 { + frame(&mut app); + } + assert_eq!(fields::(&app)["tab"], json!("advanced"), "Character Style Options left Advanced Character Formats"); + cancel::(&mut app); + + app.run("ui.newCharStyle", json!({})).unwrap(); + set::(&app, "tab", json!("color")); + for _ in 0..5 { + frame(&mut app); + } + assert_eq!(fields::(&app)["tab"], json!("color"), "New Character Style left Character Color"); +} + #[test] fn invalid_number_keeps_last_valid_preview() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 94ff0e8339..c82a6f76d5 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -907,6 +907,34 @@ mod tests { assert!(st.history.undo.is_empty()); } + /// Document Setup opened on a tab other than General still shows that tab after its first frames, which + /// measure the dialog before its body runs. + #[test] + fn a_later_tab_picked_before_the_first_frame_stays_shown() { + for tab in ["Transparency", "Type", "Color"] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0)); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 0.25; + crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }); + }; + frame(&mut app); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "tab", json!(tab)); + for _ in 0..5 { + frame(&mut app); + } + let shown = app.dialogs().unwrap().with(|h| { + use craft::ui::dialog::StackDialog as _; + h.get_by_id::(id()).and_then(|d| d.json_fields()) + }); + assert_eq!(shown.map(|f| f["tab"].clone()), Some(json!(tab)), "Document Setup left {tab}"); + } + } + #[test] fn every_tab_draws_and_ok_is_one_undo_step() { let (mut app, ctx) = setup_open(); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index efcccd932b..c20582141e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1112,6 +1112,38 @@ mod tests { assert!(inside.is_empty(), "the segments draw icons, not words: {inside:?}"); } + /// Each preset card rests on a tile, a light veil of the scrim over the dialog's surface, with its paper on it, so a + /// card that is not selected still stands apart from the dialog. + #[test] + fn resting_preset_cards_stand_on_a_tile() { + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + let mut scrim = egui::Color32::TRANSPARENT; + let mut theme = + crate::testing::ui_context().run_ui(Default::default(), |ui| scrim = rgba_color(Env::of(ui).tokens.tokens().color.surface.scrim)); + // The test reads the theme; no renderer applies the frame's textures. + theme.textures_delta.clear(); + let mut app = app(); + open(&mut app); + let out = laid_out(&mut app); + let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default(); + let card = nodes + .iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::ListItem && n.label().is_some_and(|l| !l.is_empty()) && n.is_selected() == Some(false)) + .and_then(|(_, n)| n.bounds()) + .map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + .expect("a preset card that is not selected"); + let shapes = crate::tests_labels::flat_painted_shapes(&out.shapes); + let rects: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None }).collect(); + let veil = |fill: egui::Color32| fill.a() > 0 && fill.a() < scrim.a() && fill.to_opaque() == scrim.to_opaque(); + assert!( + rects.iter().any(|rect| veil(rect.fill) && rect.rect.contains_rect(card.shrink(1.0)) && card.expand(1.0).contains_rect(rect.rect)), + "a veil of the scrim {scrim:?} covers the resting card {card:?}: {:?}", + rects.iter().filter(|rect| card.expand(1.0).contains_rect(rect.rect)).map(|rect| (rect.rect, rect.fill)).collect::>() + ); + assert!(rects.iter().any(|rect| rect.fill == egui::Color32::WHITE && card.contains_rect(rect.rect)), "the card's paper is on the tile"); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two documents, and /// the built-in cards turn to the picked orientation (#2860). #[test] diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 74a5586b04..0fd8936a45 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -521,22 +521,6 @@ fn flyout_tab(layout: &Layout, panel: &str) -> Option { .map(|front| front.to_string()) } -/// The actions that expand each floating window the pass made from part of a column collapsed to -/// icons, so a group or tab dragged out of an icon column floats as an expanded panel with its tabs -/// in the window. A whole icon column floated stays collapsed. -fn floated_from_icons(before: &Layout, after: &Layout) -> Vec> { - after - .floating - .iter() - .filter(|window| window.column.iconic && !before.floating.iter().any(|old| old.id == window.id)) - .filter_map(|window| { - let first = window.panels().next()?; - let (_, column) = column_of(before, first)?; - (column.iconic && column.panels().count() > window.panels().count()).then(|| Action::set_iconic(first.clone(), false)) - }) - .collect() -} - /// Show `panel` as `window.panel` does, but leave it be when it can be seen already ([`visible`]): /// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. A flyout /// keeps the name of the icon that opened it after another of its tabs is clicked, so a panel whose @@ -1393,20 +1377,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo app.dock_rt.rails = rails; // A workspace a command switched to or changed in this pass (`Workspace::replace`) stays; the // pass's edits were to the one it replaced. - let mut expand = Vec::new(); if app.ui.dock_workspace.revision() == revision { - let before = std::mem::replace(&mut app.ui.dock_workspace, workspace); - expand = floated_from_icons(before.layout(), layout_of(&app.ui)); + app.ui.dock_workspace = workspace; } // A command of this pass that opened or closed a flyout wins over the area's own change. if app.ui.open_panel == flyout_before { app.ui.open_panel = flyout; } - if !expand.is_empty() - && let Err(error) = apply(app, None, expand) - { - app.status(error); - } if output.error.is_some() { Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[])); app.status(tl!("Invalid panel layout; restored the default dock").to_string()); diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 64d9b2e101..e6f7cb6e86 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -35,14 +35,9 @@ pub struct DocInfoView { /// the second or third click of a double or triple click. pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool { let mut clicked = false; - // A row whose label and value fit on one line keeps the value at its end. A wrapping row places its children as - // `Start` does, so the row wraps only when the two do not fit, as in a narrow panel or a longer translation. - let width = |text: &str| { - let font = egui::TextStyle::Body.resolve(ui.style()); - ui.painter().layout_no_wrap(text.to_string(), font, egui::Color32::WHITE).size().x - }; - let fits = width(label) + width(value) + 2.0 * ui.spacing().item_spacing.x <= ui.available_width(); - Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(!fits).show(ui, |ui, _| { + // A row whose label and value fit on one line keeps the value at its end; otherwise the value wraps under the + // label, as in a narrow panel or a longer translation. + Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(true).show(ui, |ui, _| { Text::new(label.to_string()).shade(Shade::Muted).show(ui); // The value can be selected and copied, and a click copies all of it (#8432). A drag selects // and a Shift-click extends the selection, so neither copies. A value wider than the panel diff --git a/crates/ui-egui/src/panels/image_trace/rows.rs b/crates/ui-egui/src/panels/image_trace/rows.rs index 98551787eb..2c87a42d50 100644 --- a/crates/ui-egui/src/panels/image_trace/rows.rs +++ b/crates/ui-egui/src/panels/image_trace/rows.rs @@ -10,7 +10,7 @@ use craft::color_ui::ui::{ColorPopover, PickedColor}; use craft::theme::Srgba; use craft::ui::buttons::ToggleButton; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout}; use craft::ui::layout_components::Row; use craft::ui::pickers::Select; @@ -271,14 +271,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _ Row::new().show(ui, |ui, _| { let mut hit = None; for (key, on, other, label) in [("fills", fills, strokes, tl!("Fills")), ("strokes", strokes, fills, tl!("Strokes"))] { - // Inside the Create field a check box's own label is not drawn, so each box takes a field of - // its own with the label after it. - let enabled = !on || other; - let mut value = on; - Field::new(label).layout(FieldLayout::After).enabled(enabled).show(ui, |ui, _| { - Checkbox::new(Bind::bound(&mut value)).enabled(enabled).show(ui); - }); - if value != on { + if check(ui, label, on, !on || other) { hit = Some(key); } } diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 7ea1db6e49..7f71d73da4 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -377,7 +377,7 @@ pub(crate) fn link_field(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static } /// The Stroke panel: the weight, the stroke editor (cap, corner, align, dashes), arrowheads, scale, align and the -/// width profile. The panel's own rows share one label column, so their controls start at one x. +/// width profile. The panel's rows and the editor's rows share one label column, so their controls start at one x. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { use craft::ui::runtime::env::{WordRows, WordsOverride, with_env}; @@ -411,7 +411,8 @@ fn rows(app: &mut VectorcraftApp, ui: &mut Ui) { let editor = StrokeEditor::new(tl!("Stroke"), Bind::given(style.clone())) .sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN) .closed(mixed.can_align) - .mixed(&mixed_of(&mixed)); + .mixed(&mixed_of(&mixed)) + .host_labels(true); let output = editor.show(ui); if let (Some(new), Some(field)) = (output.events.landed(), output.field) { apply_style(app, &style, new.clone(), field); diff --git a/crates/ui-egui/src/panels/tests_panel_spacing.rs b/crates/ui-egui/src/panels/tests_panel_spacing.rs index 621c92817d..cc9b859468 100644 --- a/crates/ui-egui/src/panels/tests_panel_spacing.rs +++ b/crates/ui-egui/src/panels/tests_panel_spacing.rs @@ -51,6 +51,22 @@ fn a_long_document_info_value_wraps_inside_a_narrow_panel() { } } +#[test] +fn a_document_info_value_that_does_not_fit_beside_its_label_moves_under_it() { + let name = "A document name long enough to run past a narrow panel"; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + run(&mut app, "file.new", json!({"width": 200, "height": 200, "name": name})); + let mut panel = Panel::new(app, doc_info::show); + panel.room(egui::vec2(160.0, ROOM.y)); + panel.frame(); + panel.frame(); + let label = one(&panel, "Name"); + let value = run_starting(&panel, "A document"); + assert!(value.top() >= label.bottom() - 0.5, "the value {value:?} stands beside its label {label:?}, not under it"); + // A row that wraps starts each line at the start edge. + assert!((value.left() - label.left()).abs() < 1.0, "the value {value:?} does not start under its label {label:?}"); +} + #[test] fn info_paints_stand_a_section_apart_from_the_numbers() { let mut app = app_with_rect(); diff --git a/crates/ui-egui/src/panels/tests_stroke.rs b/crates/ui-egui/src/panels/tests_stroke.rs index 8aca326b47..66cf954339 100644 --- a/crates/ui-egui/src/panels/tests_stroke.rs +++ b/crates/ui-egui/src/panels/tests_stroke.rs @@ -28,9 +28,16 @@ fn turning_dashes_on_fits_them_to_corners_and_turning_back_on_restores_the_last_ #[test] fn the_panel_rows_start_their_controls_at_one_x() { let mut panel = Panel::new(app_with_rect(), stroke::show); + // Dashes show the Dash offset row. + run(&mut panel.app(), "stroke.set", json!({"dash": [4, 2]})); panel.frame(); panel.frame(); - let starts: Vec<(&str, f32)> = ["Weight", "Start arrowhead", "Profile"].into_iter().map(|name| (name, panel.rect(name).min.x)).collect(); + let names = ["Weight", "Miter limit", "Dash offset", "Start arrowhead", "Profile"]; + let mut starts: Vec<(&str, f32)> = names.into_iter().map(|name| (name, panel.rect(name).min.x)).collect(); + // The label text of the editor's button rows has the same names as their button groups. + for name in ["Alignment", "Caps", "Corners"] { + starts.push((name, panel.rect_role(name, craft::ui::contract::Role::RADIO_GROUP).min.x)); + } let first = starts[0].1; assert!(starts.iter().all(|(_, x)| (x - first).abs() < 0.5), "controls start at {starts:?}"); } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 6f2f72d06a..973e47ddf1 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -768,11 +768,11 @@ fn quad_bounds(quad: &[Point; 4]) -> vectorcraft_geom::Rect { /// The Fill/Stroke proxy, Color/Gradient/None, the drawing modes and screen mode under the rail's /// tools: in two columns the three drawing modes show, in one only the current one, which cycles /// them. A row the rail is too narrow for goes on in the next line. The All Tools drawer's Show -/// section hides any of them. A rule above them parts them from the tools, which scroll above it in a short rail. +/// section hides any of them. The rail's footer region draws the rule that parts them from the tools, which scroll +/// above it in a short rail. fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) { let two = footer.columns > 1; let show = app.ui.toolbar_show; - Divider::horizontal().show(ui); if show.fill_stroke { crate::panels::proxy(app, ui); } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 9ce6cca2e6..66688bf9ed 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -306,9 +306,9 @@ fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() { assert_eq!(app.session.draw_mode, vectorcraft_engine::DrawMode::Behind); } -/// In one column the Color, Gradient and None chips share one line, and a rule across the rail parts the controls under -/// the tools from the tools, which scroll above them in a short rail: it lies between the last tool and Fill and -/// Stroke. +/// In one column the Color, Gradient and None chips share one line, and one rule across the rail parts the controls +/// under the tools from the tools, which scroll above them in a short rail: it lies between the last tool and Fill and +/// Stroke, and no second rule doubles it. #[test] fn the_controls_under_the_tools_share_a_line_under_a_rule() { let mut app = app_with(200, 200); @@ -325,12 +325,15 @@ fn the_controls_under_the_tools_share_a_line_under_a_rule() { // A rule is a thin horizontal line or bar across most of the rail's width, between the tools and the controls. let between = |y: f32| y > last.bottom() && y < proxy.top(); let across = |left: f32, right: f32| right - left >= last.width() * 0.75 && left < last.right() && right > last.left(); - let ruled = flat.iter().any(|shape| match shape { - egui::Shape::LineSegment { points: [a, b], .. } => (a.y - b.y).abs() < 0.5 && between(a.y) && across(a.x.min(b.x), a.x.max(b.x)), - egui::Shape::Rect(r) => r.rect.height() <= 2.0 && between(r.rect.center().y) && across(r.rect.left(), r.rect.right()), - _ => false, - }); - assert!(ruled, "a rule lies between the last tool {last:?} and Fill and Stroke {proxy:?}"); + let rules = flat + .iter() + .filter(|shape| match shape { + egui::Shape::LineSegment { points: [a, b], .. } => (a.y - b.y).abs() < 0.5 && between(a.y) && across(a.x.min(b.x), a.x.max(b.x)), + egui::Shape::Rect(r) => r.rect.height() <= 2.0 && between(r.rect.center().y) && across(r.rect.left(), r.rect.right()), + _ => false, + }) + .count(); + assert_eq!(rules, 1, "one rule lies between the last tool {last:?} and Fill and Stroke {proxy:?}"); } /// A screen reader reads the drawing-mode buttons' state as the rail shows it, in every mode: in two columns the diff --git a/docs/mcp.md b/docs/mcp.md index a6822e992b..d984e7b92d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3116,8 +3116,9 @@ through `$`: stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one - `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the - script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points + `path.setAnchors` before the script uses any other member or command, edits the points of another path, or reads + the points of another path in the same Objects on Path group, and when the script ends; + a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and @@ -3142,7 +3143,10 @@ through `$`: a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`), or before anything other 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, + object that holds it, such as `translate()`. An exception applies when editing another path in an Objects on + Path group moves a path inside that group. Its existing `PathPoint` handles throw `Stale path point`. + Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of + another path in the same Objects on Path group. Every point of a path selected as a whole is a selected anchor point, 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cca1a334aa..ee49042298 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1120,7 +1120,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: `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. `crates/engine/src/tests/script_dom_paths.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`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7c2e587a7d..08a55df09a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -316,13 +316,18 @@ fn test_packages(select: &[String], shown: &str, part: Option) -> /// The doctests, which nextest doesn't run. fn cmd_doctests() -> Result<(), String> { - doctest_packages(&["--workspace".to_owned()], "--workspace") + doctest_packages(&shards::members(&metadata()?)?) } -/// [`cmd_doctests`] for the packages `select` picks, shown as `shown`. -fn doctest_packages(select: &[String], shown: &str) -> Result<(), String> { +/// [`cmd_doctests`] for the crates of `crates` that have doc tests. +fn doctest_packages(crates: &[shards::Member]) -> Result<(), String> { + let crates = shards::with_doctests(crates); + if crates.is_empty() { + return Ok(()); + } + let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); let mut c = cargo(); - c.arg("test").args(select).arg("--doc"); + c.arg("test").args(shards::select(&crates)).arg("--doc"); run(c, &format!("cargo test {shown} --doc")) } @@ -372,9 +377,9 @@ fn cmd_ci_shard() -> Result<(), String> { steps.push(("test", Box::new(move || test_packages(&s, &w, part)))); // The doctests and the i18n report run once, on a split's first part. let first = part.is_none_or(|p| p.is_first()); - let (s, w) = (select.clone(), shown.clone()); if first { - steps.push(("doctests", Box::new(move || doctest_packages(&s, &w)))); + let c = crates.clone(); + steps.push(("doctests", Box::new(move || doctest_packages(&c)))); } if first && crates.iter().any(|m| m.name == "vectorcraft-ui-egui") { steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown)))); diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 29f5281a84..2a4ae4d927 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -88,6 +88,10 @@ pub struct Member { /// against this repo's geom and pathops by git, so the graph holds a second copy of each. pub id: String, pub version: String, + /// Whether `cargo test --doc` can select this package without a warning: it has no library + /// target, or one of `lib`, `rlib` or `proc-macro` kind. Cargo warns for a selected package + /// whose library is only a `cdylib`, `dylib` or `staticlib`. + pub doctests: bool, } /// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part. @@ -159,7 +163,7 @@ pub fn members(meta: &Value) -> Result, String> { .filter(|p| p["id"].as_str().is_some_and(|id| ids.contains(id))) .map(|p| { let field = |key: &str| p[key].as_str().map(str::to_owned).ok_or_else(|| format!("cargo metadata: a workspace package has no `{key}`")); - Ok(Member { name: field("name")?, id: field("id")?, version: field("version")? }) + Ok(Member { name: field("name")?, id: field("id")?, version: field("version")?, doctests: has_doctests(p) }) }) .collect::>()?; if members.is_empty() { @@ -168,6 +172,24 @@ pub fn members(meta: &Value) -> Result, String> { Ok(members) } +/// [`Member::doctests`] for the `cargo metadata` package `p`. +fn has_doctests(p: &Value) -> bool { + let kinds = |t: &Value| t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect::>(); + let libraries: Vec> = p["targets"] + .as_array() + .into_iter() + .flatten() + .map(kinds) + .filter(|k| k.iter().any(|k| matches!(k.as_str(), "lib" | "rlib" | "dylib" | "cdylib" | "staticlib" | "proc-macro"))) + .collect(); + libraries.is_empty() || libraries.iter().flatten().any(|k| matches!(k.as_str(), "lib" | "rlib" | "proc-macro")) +} + +/// The crates of `crates` that `cargo test --doc` can select (see [`Member::doctests`]). +pub fn with_doctests(crates: &[Member]) -> Vec { + crates.iter().filter(|m| m.doctests).cloned().collect() +} + /// Each group of `groups` with its crates: a named crate must be a workspace member and named /// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's /// parts 1 to n must be consecutive shards, with at least two parts, and no test pinned twice. @@ -347,7 +369,24 @@ mod tests { use super::*; fn m(name: &str) -> Member { - Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into() } + Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true } + } + + #[test] + fn the_doc_tests_leave_out_only_packages_whose_library_cargo_cannot_doc_test() { + let package = |kinds: &[&str]| serde_json::json!({ "targets": [{ "kind": kinds }, { "kind": ["bin"] }] }); + assert!(has_doctests(&package(&["lib"]))); + assert!(has_doctests(&package(&["rlib"]))); + assert!(has_doctests(&package(&["proc-macro"]))); + assert!(has_doctests(&package(&["cdylib", "rlib"]))); + assert!(has_doctests(&package(&["bin"]))); + assert!(has_doctests(&serde_json::json!({ "targets": [] }))); + assert!(!has_doctests(&package(&["cdylib"]))); + assert!(!has_doctests(&package(&["dylib"]))); + assert!(!has_doctests(&package(&["staticlib"]))); + let mut cdylib = m("cdylib"); + cdylib.doctests = false; + assert_eq!(with_doctests(&[m("a"), cdylib, m("b")]).iter().map(|m| m.name.as_str()).collect::>(), ["a", "b"]); } fn crates(shard: &Shard) -> Vec<&str> { @@ -514,6 +553,15 @@ mod tests { assert_eq!(shards.iter().filter(|s| **s == Shard::Checks).count(), 1); } + #[test] + fn the_workspace_doc_tests_skip_the_cdylib_thumbnail_handler() { + let ws = members(&crate::metadata().unwrap()).unwrap(); + let doctests = |name: &str| ws.iter().find(|m| m.name == name).map(|m| m.doctests); + assert_eq!(doctests("vectorcraft-thumbnail-handler"), Some(false)); + assert_eq!(doctests("vectorcraft-geom"), Some(true)); + assert_eq!(doctests("vectorcraft-cli"), Some(true)); + } + #[test] fn a_feature_only_another_shard_turns_on_is_a_difference() { let ws = [m("lib"), m("geom")];