From 4f2bb0d1778bfd22746a5055d95252cba27c11c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 03:09:24 -0800 Subject: [PATCH 01/22] Arrange Tools: Match Objects gives the others the key object's size, angle and stacking place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Arrange Tools › Match Objects… (addon.arrange.match) makes the other selected objects match one source object: the key object, or the top or the bottom selected object. Each can take the source's width (height in proportion), height (width in proportion) or both, its bounding-box angle, and its stacking place directly above it in its layer or group, about a reference point, as one undo step. No step is recorded when nothing changes, and invalid params are refused. The dialog previews on the canvas; OK stays off while nothing is chosen or the source is a missing key object. Docs: docs/mcp.md, docs/target-app-parity.md, docs/ui-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/arrange.rs | 112 ++++++++++- crates/engine/src/cmd/addons/arrange/tests.rs | 181 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 4 + crates/ui-egui/src/addons/arrange.rs | 43 ++++- crates/ui-egui/src/addons/arrange/tests.rs | 53 +++++ docs/mcp.md | 5 + docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 10 files changed, 402 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index d40c33e9e1..fbd5c54036 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index f81d7a599a..1588ec1162 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -2,7 +2,8 @@ //! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two; //! Replace with Top Object puts a copy of the topmost selected object in place of each of the //! others; and Set Size of Each gives every selected object an exact width and height. Places and -//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the +//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected +//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the //! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in //! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection @@ -79,6 +80,15 @@ pub fn specs() -> Vec { has_selection, size ), + cmd!( + "addon.arrange.match", + "Match Objects", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame; to match places, use object.align {to: \"key\"} → {source, count}", + has_multi, + match_objects + ), cmd!( "addon.arrange.groupOverlapping", "Group Overlapping Objects", @@ -313,6 +323,106 @@ fn size(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": xfs.len() })) } +/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its +/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost. +fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result { + let st = s.doc()?; + let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id))); + let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? { + Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?), + Some("bottom") => roots.first().copied(), + Some(_) => roots.last().copied(), + None => key.or_else(|| roots.last().copied()), + }; + picked.ok_or_else(|| bad(cmd, "select at least two objects")) +} + +/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order. +fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool { + let paths = d.index_paths(targets.iter().copied().chain([source])); + let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false }; + targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up))) +} + +fn match_objects(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.match"; + let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none"); + let rotate = switch_or(p, "rotate", false, C)?; + let stacking = switch_or(p, "stacking", false, C)?; + let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); + let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?; + if size == "none" && !rotate && !stacking { + return Err(bad(C, "give `size`, `rotate` or `stacking`")); + } + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let source = match_source(s, p, &roots, C)?; + let targets: Vec = roots.iter().copied().filter(|id| *id != source).collect(); + if targets.is_empty() { + return Err(bad(C, "select at least two objects")); + } + let sb = box_of(s, source)?; + let (w, h) = (sb.rect.width(), sb.rect.height()); + let wanted = match size { + "width" if w < LEAST => return Err(bad(C, "the source object has no width")), + "height" if h < LEAST => return Err(bad(C, "the source object has no height")), + "both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")), + "width" => Some(json!({ "width": w, "proportional": true })), + "height" => Some(json!({ "height": h, "proportional": true })), + "both" => Some(json!({ "width": w, "height": h })), + _ => None, + }; + let angle = s.doc()?.doc.bbox_angle(&[source]); + let mut xfs = Vec::with_capacity(targets.len()); + for &id in &targets { + let Some(b) = s.transform_box(&[id]) else { continue }; + let mut xf = Affine::IDENTITY; + if let Some(q) = &wanted { + let mut q = q.clone(); + q["reference"] = json!(reference); + q["strokes"] = json!(strokes); + xf = object_bounds_transform(s, &q, id)?; + } + if rotate { + // Turned about the reference point, which the sizing keeps in place; angles are + // counter-clockwise and y is down. + let turn = vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])); + if turn.abs() > 1e-9 { + let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + xf = Affine::rotate_about(-turn.to_radians(), at) * xf; + } + } + xfs.push((id, xf)); + } + let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); + xfs.retain(|(_, xf)| !still(xf)); + let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets); + let count = json!({ "source": source.0, "count": targets.len() }); + if xfs.is_empty() && !restack { + return Ok(count); + } + let q = json!({ "strokes": strokes, "patterns": patterns }); + let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); + let mut sc = scaling(s, &q); + sc.patterns = transform_patterns(s, &q, &ids)?; + s.edit("Match Objects", |d, _| { + for (id, xf) in &xfs { + if let Some(n) = d.node_mut(*id) { + transform_node(n, *xf, sc, true); + } + } + if restack { + let moved = d.remove_many(&targets)?; + d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?; + } + Ok(()) + })?; + Ok(count) +} + /// The sets of two or more of `items` (each in the order given) whose rects overlap or touch, /// chains included, among items of the same key (parent). A sweep along x: only the rects still /// open where each one starts are compared with it. diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 759f6f321e..7cf91abfb7 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -215,6 +215,186 @@ fn size_gives_each_object_a_width_and_height() { assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a)); } +/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at +/// (100, 100) and `c` 10 × 30 at (200, 0). +fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) { + let a = rect(s, 0.0, 0.0, 20.0, 10.0); + let b = rect(s, 100.0, 100.0, 40.0, 40.0); + let c = rect(s, 200.0, 0.0, 10.0, 30.0); + select(s, &[a, b, c]); + (a, b, c) +} + +#[test] +fn match_gives_the_others_the_key_objects_size() { + let mut s = session(); + let (a, b, c) = three(&mut s); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + let n = steps(&s); + let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap(); + assert_eq!(r, json!({"source": b.0, "count": 2})); + assert_eq!(steps(&s), n + 1, "one undo step"); + // About each center; the key object stays. + assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c)); + assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0))); + // The width, with the height in proportion, about the top-left corner. + s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap(); + assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap(); + assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c)); +} + +#[test] +fn match_takes_the_top_or_the_bottom_object_without_a_key() { + let mut s = session(); + let (a, b, c) = three(&mut s); + // No key object: the frontmost, c. + let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap(); + assert_eq!(r["source"], json!(c.0)); + assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a)); + assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b)); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap(); + assert_eq!(r["source"], json!(a.0)); + assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b)); + assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c)); + s.execute("edit.undo", &json!({})).unwrap(); + // "top" names the frontmost even while a key object is set. + s.execute("select.key", &json!({"id": a.0})).unwrap(); + let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap(); + assert_eq!(r["source"], json!(c.0)); +} + +#[test] +fn match_turns_the_others_to_the_sources_angle() { + let mut s = session(); + let (a, b, c) = three(&mut s); + select(&mut s, &[b]); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + select(&mut s, &[a, b, c]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + let n = steps(&s); + s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] { + let o = s.transform_box(&[id]).unwrap(); + assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle); + assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect); + let at = o.center(); + assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}"); + } + // Turned back to the angle of an unturned source. + let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, d]); + s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap(); + assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6); +} + +#[test] +fn match_puts_the_others_directly_above_the_source() { + let mut s = session(); + let (a, b, c) = three(&mut s); + let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0); + select(&mut s, &[d, a, c]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + let n = steps(&s); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object"); + assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes"); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "already above it: no step"); + // An object in another layer goes into the source's. + s.execute("layer.new", &json!({})).unwrap(); + let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0); + select(&mut s, &[b, e]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(layer_order(&s), [a, c, d, b, e]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_order(&s), [a, c, d, b]); +} + +#[test] +fn match_makes_no_step_when_everything_matches() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0); + select(&mut s, &[a, b]); + let n = steps(&s); + let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap(); + assert_eq!(r["count"], json!(1)); + assert_eq!(steps(&s), n, "the same size and angle: no step"); +} + +#[test] +fn match_turns_the_others_about_their_reference_point() { + let mut s = session(); + let (a, b, c) = three(&mut s); + select(&mut s, &[b]); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + select(&mut s, &[a, b, c]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap(); + // Each top-left corner stays where it was. + for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] { + let o = s.transform_box(&[id]).unwrap(); + assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle); + let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0); + assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}"); + } +} + +#[test] +fn match_scales_strokes_as_asked() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2})).unwrap(); + let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width(); + s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap(); + assert_eq!(weight(&s, a), 2.0, "off by default (the preference)"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap(); + assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a)); + assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a)); +} + +#[test] +fn match_refuses_bad_params() { + let mut s = session(); + let (a, _, _) = three(&mut s); + refuses( + &mut s, + "addon.arrange.match", + &[ + json!({}), + json!({"size": "none"}), + json!({"size": "area"}), + json!({"size": 1}), + json!({"rotate": 1}), + json!({"stacking": "yes"}), + json!({"size": "both", "reference": 9}), + json!({"size": "both", "reference": 1.5}), + json!({"size": "both", "source": "left"}), + json!({"size": "both", "scaleStrokes": "no"}), + json!({"size": "both", "patterns": 0}), + ], + ); + let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string(); + assert!(e.contains("no key object"), "{e}"); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.match"), "one object selected"); +} + #[test] fn bad_params_are_refused() { let mut s = session(); @@ -261,6 +441,7 @@ fn off_without_a_selection() { "addon.arrange.swap", "addon.arrange.replace", "addon.arrange.size", + "addon.arrange.match", "addon.arrange.groupOverlapping", "addon.arrange.randomizeOpacity", "addon.arrange.sort", diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..4cf43ae92c 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -6,6 +6,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.arrange.grid", "addon.arrange.groupOverlapping", + "addon.arrange.match", "addon.arrange.randomizeOpacity", "addon.arrange.replace", "addon.arrange.size", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..93a444a1d9 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1000,6 +1000,10 @@ fn structured_junk() { ("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})), + ("addon.arrange.match", json!({"size": "both", "rotate": true, "stacking": true, "reference": 8, "scaleStrokes": true})), + ("addon.arrange.match", json!({"source": "bottom", "size": "width", "patterns": true})), + ("addon.arrange.match", json!({"source": "key", "rotate": true})), + ("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})), ("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a26f5f7a28..6ef3c8e3c1 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,5 +1,5 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, +//! Arrange in Grid, Replace with Top Object, Set Size of Each, Match Objects, Randomize Opacity and Sort Objects, //! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping //! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. @@ -24,13 +24,15 @@ pub const ZOOM: &str = "addon.arrange.zoomSelection"; const GRID: &str = "addon.arrange.grid"; const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; +const MATCH: &str = "addon.arrange.match"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 5] = [ +const DIALOGS: [(&str, &str); 6] = [ (GRID, "Arrange in Grid"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), + (MATCH, "Match Objects"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), ]; @@ -60,6 +62,7 @@ pub fn menu() -> Vec { cp("Swap Objects and Sizes", "addon.arrange.swap", json!({ "size": true })), c("Replace with Top Object…", REPLACE), c("Set Size of Each…", SIZE), + c("Match Objects…", MATCH), cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), @@ -71,6 +74,7 @@ pub fn menu() -> Vec { static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None }; static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None }; static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; +static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; @@ -134,6 +138,20 @@ fn size_rows(lengths: LengthUnits) -> Vec { ] } +fn match_rows() -> Vec { + let sources = [("key", "Key Object"), ("top", "Top Object"), ("bottom", "Bottom Object")]; + let sizes = [("none", "None"), ("width", "Width"), ("height", "Height"), ("both", "Width and Height")]; + vec![ + choice("source", "Match To:", &sources, "key"), + choice("size", "Size:", &sizes, "both"), + check("rotate", "Rotation", false), + check("stacking", "Stacking Order", false), + reference_param("reference", tl!("Reference Point")), + scale_strokes().enabled_when_in("size", ["width", "height", "both"]), + check("patterns", "Transform Patterns", false), + ] +} + fn opacity_rows() -> Vec { vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()] } @@ -173,6 +191,10 @@ fn size_params(fields: &DialogFields) -> Value { Value::Object(params) } +fn match_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&match_rows(), fields)) +} + fn opacity_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&opacity_rows(), fields)) } @@ -186,6 +208,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option Option (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })), + // The key object while the selection has one, else the top object. + MATCH => ( + match_rows(), + json!({ + "source": if key { "key" } else { "top" }, "size": "both", "rotate": false, "stacking": false, + "reference": 4, "scaleStrokes": strokes, "patterns": app.session.prefs.transform_pattern_tiles, + }), + ), // A new seed each time the document has changed, so running it again varies the result. OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })), // The random order's seed (not shown): new whenever the document has changed, so each run @@ -224,6 +255,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), + MATCH => super::dialogs::open(app, &MATCH_SPEC, fields, move |fields| { + let chosen = fields.text("size").is_some_and(|size| size != "none") + || fields.bool("rotate") == Some(true) + || fields.bool("stacking") == Some(true); + let source = key || fields.text("source") != Some("key"); + let reason = if source { tl!("Choose Size, Rotation or Stacking Order.") } else { tl!("The selection has no key object.") }; + dialog(MATCH, match_rows()).ok_enabled(chosen && source).ok_reason(reason.into()).values(Bind::bound(fields)) + }), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 420bfdb01d..da066784f1 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -124,6 +124,59 @@ fn set_size_of_each_sets_the_sides_ticked() { assert_eq!((bounds(&app, b).width(), bounds(&app, b).height()), (30.0, 40.0)); } +fn layer_order(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn real_match_keyboard_edits_preview_confirm_and_cancel() { + let (app, a, b) = app(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let before = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Match Objects…"); + panel.frame(); + let id = host::dialog_id(&panel.app()); + // No key object: it opens on the top object, b, and previews its size on a. + assert_eq!( + host::read(&panel.app(), id, |f| (f.text("source").map(str::to_owned), f.text("size").map(str::to_owned))), + (Some("top".into()), Some("both".into())) + ); + assert_eq!(bounds(&panel.app(), a), vectorcraft_geom::Rect::new(-10.0, -15.0, 30.0, 25.0)); + panel.focus("Stacking Order"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + panel.frame(); + assert_eq!(host::read(&panel.app(), id, |f| f.bool("stacking")), Some(true)); + assert_eq!(layer_order(&panel.app()), [b, a], "the preview puts a above b"); + panel.click("Cancel"); + panel.frame(); + { + let app = panel.app(); + assert_eq!((bounds(&app, a), layer_order(&app), steps(&app)), (vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0), vec![a, b], before)); + } + click(&mut panel.app(), "Match Objects…"); + panel.frame(); + let id = host::dialog_id(&panel.app()); + host::set(&panel.app(), id, "size", json!("none")); + panel.frame(); + assert!(!panel.enabled("OK"), "nothing to match"); + host::set(&panel.app(), id, "size", json!("width")); + host::set(&panel.app(), id, "source", json!("key")); + panel.frame(); + assert!(!panel.enabled("OK"), "the selection has no key object"); + host::set(&panel.app(), id, "source", json!("bottom")); + panel.frame(); + assert!(panel.enabled("OK")); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + // b takes a's width, its height in proportion, as one undo step. + assert_eq!(bounds(&app, b), vectorcraft_geom::Rect::new(110.0, 110.0, 130.0, 130.0)); + assert_eq!(bounds(&app, a), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0)); + assert_eq!(steps(&app), before + 1); +} + #[test] fn replace_opens_with_the_scale_strokes_preference_and_swap_runs_directly() { let (mut app, a, b) = app(); diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..ae4203a3ce 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17438,6 +17438,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source does not have, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | @@ -17447,11 +17448,15 @@ active view so the selection's visual bounds fill the window with a margin, as ` and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. +Match Objects… opens a dialog of its own in the same way, keyed by its command, whose fields are the command's +parameters, with Preview; it opens on the key object when the selection has one, else on the top object, and OK is +off while nothing is chosen to match or the source is the key object and there is none. ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} +{"name":"run_command","arguments":{"command":"addon.arrange.match","params":{"source":"key","size":"both","rotate":true}}} ``` ## Document Tools add-on diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..445a68aeeb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3144,6 +3144,10 @@ scaling, replace with each fit and kept originals in stacking order, size with p undo step, off states, bad params refused), `addons::arrange::tests` in `vectorcraft-ui-egui` (the submenu, the dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Match Objects (2026-11-29) + +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had. Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the top-level selected objects wherever their visual bounds overlap or touch, chains included (A overlapping B and B overlapping C makes one group of three), only among objects of the same layer or group; objects that overlap nothing stay as they are, each new group takes its frontmost member's place in the stacking order, and the groups and the loose objects stay selected. One undo step; at most 20000 objects, compared by a sweep along x with union-find. Tests: `group_overlapping_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (chains, loners, stacking order, layers kept apart, visual bounds, no step when nothing overlaps, many objects), `group_overlapping_objects_runs_directly` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 453bda832d..0e7750475b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -564,6 +564,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | | Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer that is not a template and whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Match Objects… gives the other selected objects the size (Width, Height or Width and Height), the bounding-box angle (Rotation) and the stacking place (Stacking Order) of the source, chosen in Match To (Key Object, Top Object, Bottom Object); the reference point, Scale Strokes & Effects, Transform Patterns; Preview; one undo step | done | `addon.arrange.match`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | From 59b4e54710d297ed76e59a4fe39baf48904ef143 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:08:57 -0800 Subject: [PATCH 02/22] Build: the workspace manifest prints no unused-dependency or unused-patch warnings Every cargo command printed seven manifest warnings, and clippy on all targets printed one more. Each entry below had no reader on main. - peniko (workspace dependency): no member crate has ever declared it. It has been in the list since the workspace skeleton (bfee80a22c). crates/render reaches peniko through vello_cpu::peniko. - rfd and webbrowser (workspace dependencies): #8800 moved the app onto the craft UI framework and removed their last declarations in apps/vectorcraft and crates/ui-egui. The folder picker and the browser links now come from craft-libs. The rfd name in xtask's layer check is a crate name to reject, so it does not read this entry. - workspace.package.repository: no member crate sets repository.workspace = true, and no packaging script, xtask command or workflow reads the field. - egui_demo_lib, egui_inspection and egui_system_font_provider ([patch.crates-io]): #8800 copied these from craft-libs' own patch list, and nothing in VectorCraft's graph depends on them. Cargo.lock listed them under [[patch.unused]]. A dependency's [patch] does not apply in this workspace, so removing them does not change how craft-libs builds. The egui crates that are in the graph keep their patches at 932a73b285. - apps/vectorcraft-web declared egui_extras for every target, but only the wasm32 module web.rs calls it. It now sits under the wasm32 target dependencies. Cargo.lock drops the three [[patch.unused]] entries. --- Cargo.lock | 15 --------------- Cargo.toml | 7 ------- apps/vectorcraft-web/Cargo.toml | 3 ++- 3 files changed, 2 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 520647b95d..d12ce6efa6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10758,18 +10758,3 @@ dependencies = [ "syn 3.0.9", "winnow", ] - -[[patch.unused]] -name = "egui_demo_lib" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" - -[[patch.unused]] -name = "egui_inspection" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" - -[[patch.unused]] -name = "egui_system_font_provider" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081" diff --git a/Cargo.toml b/Cargo.toml index a0fb986dcc..f8b43c538d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,6 @@ version = "0.24.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" -repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" } @@ -86,7 +85,6 @@ vectorcraft-apischema = { path = "crates/apischema" } # foundation kurbo = { version = "0.13", features = ["serde"] } -peniko = "0.6" thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } @@ -156,10 +154,8 @@ egui = "0.37" egui_extras = { version = "0.37", default-features = false, features = ["svg"] } eframe = { version = "0.37", default-features = false } egui_kittest = "0.37" -rfd = "0.17" arboard = { version = "3.6", default-features = false } clipboard-win = "5.4" -webbrowser = "1" [workspace.lints.rust] unsafe_code = "deny" @@ -210,8 +206,5 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560 egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index e8b56c29a9..d4293d8320 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -20,12 +20,13 @@ 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] # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } +# The image loaders `web.rs` installs. +egui_extras = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" } From 13f3227220ed4d7c09065faecbc2f49fda1fb1e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:39:04 -0800 Subject: [PATCH 03/22] Match Objects: rotate says which way it turns; scaleStrokes is journaled The gate's turn_direction test failed because the `rotate` param of addon.arrange.match did not say which way it turns. Its description now says each target turns clockwise or counter-clockwise to the source's angle. Match, Set Size of Each, Swap, Replace and Sort now record the resolved `scaleStrokes` value in their journal entry, so a replay scales strokes the same way after the preference changes. --- crates/engine/src/cmd/addons/arrange.rs | 20 +++++++--- crates/engine/src/cmd/addons/arrange/tests.rs | 37 +++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 1588ec1162..bb16af321a 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target turns, clockwise or counter-clockwise, to the source's bounding-box angle), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -177,6 +177,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A }) } +/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the +/// command's journal entry, so replaying it scales the same way whatever the preference is then. +fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result { + let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?; + s.note_journal("scaleStrokes", json!(on)); + Ok(on) +} + /// The box of object `id` as `object.setBounds` measures it. fn box_of(s: &Session, id: NodeId) -> Result { s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into())) @@ -241,7 +249,7 @@ fn grid(s: &mut Session, p: &Value) -> Result { fn swap(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.swap"; let size = switch_or(p, "size", false, C)?; - let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let strokes = scale_strokes(s, p, C)?; let roots = selected_roots(s)?; let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) }; let (ba, bb) = (box_of(s, a)?, box_of(s, b)?); @@ -254,7 +262,7 @@ fn swap(s: &mut Session, p: &Value) -> Result { fn replace(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.arrange.replace"; let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep"); - let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let strokes = scale_strokes(s, p, C)?; let keep = switch_or(p, "keep", false, C)?; let roots = selected_roots(s)?; let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else { @@ -305,7 +313,7 @@ fn size(s: &mut Session, p: &Value) -> Result { } let proportional = switch_or(p, "proportional", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); - let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let strokes = scale_strokes(s, p, C)?; let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) }); if let Some(w) = width { q["width"] = json!(w); @@ -350,7 +358,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let rotate = switch_or(p, "rotate", false, C)?; let stacking = switch_or(p, "stacking", false, C)?; let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4); - let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let strokes = scale_strokes(s, p, C)?; let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?; if size == "none" && !rotate && !stacking { return Err(bad(C, "give `size`, `rotate` or `stacking`")); @@ -569,7 +577,7 @@ fn sort(s: &mut Session, p: &Value) -> Result { let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending"); let distribute = switch_or(p, "distribute", false, C)?; let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); - let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?; + let strokes = scale_strokes(s, p, C)?; let ids = checked_ids_or_selection(s, p, C)?; if ids.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 7cf91abfb7..8dc7ab5c43 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -368,6 +368,43 @@ fn match_scales_strokes_as_asked() { assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a)); } +/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and +/// replaying its journal entry after the preference is turned off scales the stroke the same way. +fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2})).unwrap(); + let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width(); + s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap(); + s.execute(cmd, &p).unwrap(); + assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s)); + let (id, q) = s.journal.last().unwrap().clone(); + assert_eq!(id, cmd); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap(); + select(&mut s, &[a, b]); + s.execute(&id, &q).unwrap(); + assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s)); +} + +#[test] +fn match_replays_with_the_stroke_scaling_it_ran_with() { + replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); +} + +#[test] +fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() { + replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20})); +} + +#[test] +fn swap_replays_with_the_stroke_scaling_it_ran_with() { + replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true})); +} + #[test] fn match_refuses_bad_params() { let mut s = session(); From 740b04cde0bab8b78449c06d61bc5426fabd65ca Mon Sep 17 00:00:00 2001 From: Fredrik Hallin Date: Sun, 29 Nov 2026 18:54:50 +0100 Subject: [PATCH 04/22] CI: use the standard macOS runner for releases --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 226830fc1b..538d09cc31 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -42,6 +42,7 @@ jobs: dry-run: ${{ github.event_name == 'schedule' }} app-name: vectorcraft app-title: VectorCraft + macos-runner: macos-15 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 web-craft-fonts: true version: ${{ inputs.version }} From a17883546e75e8e63f115b51d8a385597e932e08 Mon Sep 17 00:00:00 2001 From: Fredrik Hallin Date: Sun, 29 Nov 2026 18:58:59 +0100 Subject: [PATCH 05/22] Release: VectorCraft v0.25.0 Ship the drawing, text, import/export and editing fixes merged since 0.24.1. --- Cargo.lock | 120 ++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 61 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4da7886c88..b6394fde6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8515,7 +8515,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.24.1" +version = "0.25.0" dependencies = [ "arboard", "block2 0.6.2", @@ -8559,7 +8559,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-affinity", "craft-image-codecs", @@ -8570,26 +8570,26 @@ dependencies = [ [[package]] name = "vectorcraft-apischema" -version = "0.24.1" +version = "0.25.0" dependencies = [ "serde_json", ] [[package]] name = "vectorcraft-brush" -version = "0.24.1" +version = "0.25.0" dependencies = [ "kurbo 0.13.1", "serde", "serde_json", "vectorcraft-color", "vectorcraft-doc", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", ] [[package]] name = "vectorcraft-cad" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-dxf", "craft-image-codecs", @@ -8601,14 +8601,14 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.24.1", - "vectorcraft-pathops 0.24.1", + "vectorcraft-geom 0.25.0", + "vectorcraft-pathops 0.25.0", "vectorcraft-text", ] [[package]] name = "vectorcraft-cli" -version = "0.24.1" +version = "0.25.0" dependencies = [ "log", "objc2-core-foundation", @@ -8619,7 +8619,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-engine", "vectorcraft-format", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-mcp", "vectorcraft-render", "vectorcraft-svg", @@ -8631,7 +8631,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-cms", "craft-color-ui", @@ -8647,7 +8647,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.24.1" +version = "0.25.0" dependencies = [ "chrono", "craft-image-codecs", @@ -8663,13 +8663,13 @@ dependencies = [ "thiserror 2.0.21", "tiff", "vectorcraft-color", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "zune-jpeg", ] [[package]] name = "vectorcraft-effects" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-image-codecs", "craft-svg", @@ -8679,8 +8679,8 @@ dependencies = [ "svgtypes 0.16.1", "vectorcraft-color", "vectorcraft-doc", - "vectorcraft-geom 0.24.1", - "vectorcraft-pathops 0.24.1", + "vectorcraft-geom 0.25.0", + "vectorcraft-pathops 0.25.0", "vectorcraft-plugins", "vectorcraft-text", "vectorcraft-three-d", @@ -8690,7 +8690,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.24.1" +version = "0.25.0" dependencies = [ "apple-native-keyring-store", "cfb", @@ -8737,10 +8737,10 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-eps", "vectorcraft-format", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-js", "vectorcraft-metafile", - "vectorcraft-pathops 0.24.1", + "vectorcraft-pathops 0.25.0", "vectorcraft-pdf", "vectorcraft-plugins", "vectorcraft-render", @@ -8760,7 +8760,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-eps", "craft-image-codecs", @@ -8781,9 +8781,9 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-effects", "vectorcraft-eps", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-metafile", - "vectorcraft-pathops 0.24.1", + "vectorcraft-pathops 0.25.0", "vectorcraft-pdf", "vectorcraft-render", "vectorcraft-testkit", @@ -8792,7 +8792,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-gzip", "craft-vectorcraft-format", @@ -8804,7 +8804,7 @@ dependencies = [ "thiserror 2.0.21", "vectorcraft-brush", "vectorcraft-doc", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-testkit", ] @@ -8820,7 +8820,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.24.1" +version = "0.25.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -8831,7 +8831,7 @@ dependencies = [ [[package]] name = "vectorcraft-js" -version = "0.24.1" +version = "0.25.0" dependencies = [ "chrono", "craft-xml", @@ -8842,7 +8842,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft", "craft-image-codecs", @@ -8854,7 +8854,7 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-engine", "vectorcraft-format", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-render", "vectorcraft-svg", "vectorcraft-testkit", @@ -8863,7 +8863,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-image-codecs", "craft-metafile", @@ -8873,7 +8873,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-text", ] @@ -8890,19 +8890,19 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.24.1" +version = "0.25.0" dependencies = [ "kurbo 0.13.1", "linesweeper", "proptest", "thiserror 2.0.21", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-testkit", ] [[package]] name = "vectorcraft-pdf" -version = "0.24.1" +version = "0.25.0" dependencies = [ "aes 0.8.4", "chrono", @@ -8931,7 +8931,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-pdf", "vectorcraft-testkit", "vectorcraft-text", @@ -8939,7 +8939,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugin-worker" -version = "0.24.1" +version = "0.25.0" dependencies = [ "js-sys", "vectorcraft-plugins", @@ -8949,7 +8949,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-image-codecs", "craft-vectorcraft-format", @@ -8961,7 +8961,7 @@ dependencies = [ "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-js", "vectorcraft-plugins", "wasmi", @@ -8972,7 +8972,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-gif", "craft-image-codecs", @@ -8990,7 +8990,7 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-plugins", "vectorcraft-testkit", "vectorcraft-text", @@ -9003,7 +9003,7 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.24.1" +version = "0.25.0" dependencies = [ "proptest", "unicode-properties", @@ -9011,7 +9011,7 @@ dependencies = [ [[package]] name = "vectorcraft-svg" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-docpath", "craft-image-codecs", @@ -9035,15 +9035,15 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.24.1", - "vectorcraft-pathops 0.24.1", + "vectorcraft-geom 0.25.0", + "vectorcraft-pathops 0.25.0", "vectorcraft-testkit", "vectorcraft-text", ] [[package]] name = "vectorcraft-testkit" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-image-codecs", "fax", @@ -9054,14 +9054,14 @@ dependencies = [ "vectorcraft-doc", "vectorcraft-engine", "vectorcraft-format", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-render", "vectorcraft-svg", ] [[package]] name = "vectorcraft-text" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft", "craft-fonts-build", @@ -9079,23 +9079,23 @@ dependencies = [ "unicode-script", "unicode-segmentation", "vectorcraft-doc", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vello_cpu", "write-fonts", ] [[package]] name = "vectorcraft-three-d" -version = "0.24.1" +version = "0.25.0" dependencies = [ "proptest", - "vectorcraft-geom 0.24.1", - "vectorcraft-pathops 0.24.1", + "vectorcraft-geom 0.25.0", + "vectorcraft-pathops 0.25.0", ] [[package]] name = "vectorcraft-thumbnail-handler" -version = "0.24.1" +version = "0.25.0" dependencies = [ "png 0.18.1", "windows", @@ -9104,7 +9104,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-image-codecs", "kurbo 0.13.1", @@ -9114,15 +9114,15 @@ dependencies = [ "vectorcraft-color", "vectorcraft-doc", "vectorcraft-effects", - "vectorcraft-geom 0.24.1", - "vectorcraft-pathops 0.24.1", + "vectorcraft-geom 0.25.0", + "vectorcraft-pathops 0.25.0", "vectorcraft-text", "vectorcraft-tools", ] [[package]] name = "vectorcraft-trace" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft-image-codecs", "image", @@ -9130,12 +9130,12 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", ] [[package]] name = "vectorcraft-ui-egui" -version = "0.24.1" +version = "0.25.0" dependencies = [ "bytemuck", "chrono", @@ -9159,7 +9159,7 @@ dependencies = [ "vectorcraft-engine", "vectorcraft-eps", "vectorcraft-format", - "vectorcraft-geom 0.24.1", + "vectorcraft-geom 0.25.0", "vectorcraft-pdf", "vectorcraft-plugins", "vectorcraft-render", @@ -9174,7 +9174,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.24.1" +version = "0.25.0" dependencies = [ "craft", "craft-web-api", @@ -10403,7 +10403,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.24.1" +version = "0.25.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index d3057fb0af..1a611b41e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.24.1" +version = "0.25.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From c31cef119901acf0df8201107d1734f5109c9d55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:12:18 -0800 Subject: [PATCH 06/22] Tools: the controls under the tools scroll with them in a short window In a window too short for every tool, the Tools panel kept its paint chips, drawing modes and the other controls under the tools pinned at the bottom, so fewer tools were in view. The controls now scroll with the tools (ToolRail::footer_scrolls): in a window 560 points tall the rail shows 14 tools instead of 10, and scrolling to the end brings the controls into view under the last tool. Toolbars made with New Toolbar and torn-off strips keep their footer in view. --- crates/ui-egui/src/toolbar.rs | 4 +++ crates/ui-egui/src/toolbar/tests.rs | 49 ++++++++++++++++++++++++++--- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 6f2f72d06a..65c1aadc35 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -456,6 +456,10 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m if app.session.prefs.tool_group_labels { rail = rail.captions(); } + // The Tools panel's controls under the tools scroll with them, so a short window shows more tools. + if tools_panel { + rail = rail.footer_scrolls(); + } if own_bar { rail = rail.tear_off().edit_toolbar(tl!("Edit Toolbar")); } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 9ce6cca2e6..75dfeb327c 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -282,17 +282,18 @@ fn polygon_and_star_canvas_counts_persist_without_new_toolbar_dialogs() { /// The paint chips, drawing modes and the rest of the footer lie inside the rail at one and at two columns (one column /// shows the current drawing mode alone), and in two columns the three drawing modes sit side by side, each setting -/// its mode (#1129). +/// its mode (#1129). The window is tall enough for every tool and the controls under them, which scroll with the tools. #[test] fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() { let mut app = app_with(200, 200); let ctx = reader(); + let height = 2000.0; let footer = ["Color (, or Shift+,)", "Gradient (. or Shift+.)", "None (/)", "Draw Normal (Shift+D)", "Draw Behind (Shift+D)", "Draw Inside (Shift+D)"]; let mut nodes = vec![]; for (k, double) in [false, true].into_iter().enumerate() { app.run("window.toolbarColumns", json!({ "double": double })).unwrap(); - nodes = settled(&mut app, &ctx, k as f64 * 10.0, 900.0); + nodes = settled(&mut app, &ctx, k as f64 * 10.0, height); // The rail itself, not its dock grip, which is named for the pane too. let rail = nodes.iter().find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools")).and_then(bounds).expect("the rail is drawn"); for label in &footer[..if double { 6 } else { 4 }] { @@ -302,13 +303,12 @@ fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() { } let modes = ["Draw Normal (Shift+D)", "Draw Behind (Shift+D)", "Draw Inside (Shift+D)"].map(|label| named_rect(&nodes, label)); assert!(modes.iter().all(|r| (r.top() - modes[0].top()).abs() < 0.5), "side by side: {modes:?}"); - click(&mut app, &ctx, 20.0, modes[1].center(), 900.0); + click(&mut app, &ctx, 20.0, modes[1].center(), height); 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. +/// the tools from the tools: it lies between the last tool and Fill and Stroke. #[test] fn the_controls_under_the_tools_share_a_line_under_a_rule() { let mut app = app_with(200, 200); @@ -604,3 +604,42 @@ fn a_short_tools_rail_shows_its_scroll_bar_at_rest() { assert!(bars(&mut app, 0.0, 400.0) > 0, "a short rail shows its scroll bar with the pointer away"); assert_eq!(bars(&mut app, 10.0, 2000.0), 0, "a rail with room for every tool shows no scroll bar"); } + +/// In a window too short for the Tools panel, the controls under the tools scroll with them: the tool buttons fill +/// the rail down to its bottom edge, Fill and Stroke starts out of view under them, and scrolling to the end brings +/// Fill and Stroke into view under the last tool. +#[test] +fn the_tools_panel_controls_scroll_with_the_tools_in_a_short_window() { + let mut app = app_with(200, 200); + let ctx = reader(); + app.run("window.toolbarColumns", json!({ "double": false })).unwrap(); + let height = 560.0; + let nodes = settled(&mut app, &ctx, 0.0, height); + let rail = nodes.iter().find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools")).and_then(bounds).expect("the rail is drawn"); + let tools = cells(&app, &nodes); + let in_view: Vec<&egui::Rect> = tools.iter().filter(|r| r.bottom() <= rail.bottom() + 0.5).collect(); + assert!(in_view.len() < tools.len(), "the window is too short for every tool: {} of {}", in_view.len(), tools.len()); + let pitch = tools[1].top() - tools[0].top(); + let lowest = in_view.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); + let bottom = rail.bottom(); + assert!(bottom - lowest < pitch, "the tools fill the rail to its bottom: the last in view ends at {lowest}, the rail at {bottom}"); + let proxy = named_rect(&nodes, "Fill and Stroke"); + assert!(proxy.top() >= rail.bottom() - 0.5, "Fill and Stroke starts out of view: {proxy:?} under {rail:?}"); + + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -400.0), + modifiers: Default::default(), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }; + let over = tools[0].center(); + for k in 0..10 { + frame(&mut app, &ctx, 1.0 + f64::from(k) * 0.05, vec![Event::PointerMoved(over), wheel.clone()], height); + } + let nodes = settled(&mut app, &ctx, 2.0, height); + let proxy = named_rect(&nodes, "Fill and Stroke"); + let last = cells(&app, &nodes).into_iter().max_by(|a, b| a.bottom().total_cmp(&b.bottom())).expect("the rail shows tools"); + assert!(proxy.bottom() <= rail.bottom() + 0.5, "Fill and Stroke is in view after scrolling: {proxy:?} in {rail:?}"); + assert!(last.bottom() <= proxy.top(), "the last tool {last:?} stands above Fill and Stroke {proxy:?}"); +} From a978fd242a56161482bcc533e5aae8baa97fc426 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:16:00 -0800 Subject: [PATCH 07/22] Type: an edit runs each idle and typing frame once The Type tool's text part was shown in the canvas's flow, in a scope sized to the caret. While the tool edited text, every other frame ran its UI twice: the frame's layout check found the part changed and the frame was run again. The part is now shown at the caret's rect with no allocation, as the canvas's other overlays are, and each idle and typing frame runs once. --- crates/ui-egui/src/tests/lifecycle.rs | 19 +++++++++++++++++++ crates/ui-egui/src/type_editing.rs | 6 +++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tests/lifecycle.rs b/crates/ui-egui/src/tests/lifecycle.rs index 41ace0ff2d..4080427be8 100644 --- a/crates/ui-egui/src/tests/lifecycle.rs +++ b/crates/ui-egui/src/tests/lifecycle.rs @@ -245,3 +245,22 @@ fn ime_delete_surrounding_then_commit_edit_the_type_tool_once_in_order() { ime_frame(&mut app, &ctx, vec![Event::Ime(egui::ImeEvent::Commit("Q".into()))], |_| {}); assert_eq!(plain(&app, id), "abcQZ"); } + +/// While the Type tool edits text, each idle frame and each typing frame runs its UI once: the text part measures the +/// same in the measuring run and the real run, so no frame is discarded and run again. +#[test] +fn an_edit_runs_each_idle_and_typing_frame_once() { + let (mut app, id) = app_with_text("abc"); + let ctx = crate::testing::ui_context(); + ime_frame(&mut app, &ctx, vec![], |_| {}); + ime_frame(&mut app, &ctx, vec![], |_| {}); + begin_typing(&mut app, &ctx, id); + for _ in 0..3 { + ime_frame(&mut app, &ctx, vec![], |_| {}); + } + let idle: Vec = (0..6).map(|_| run_frame(&mut app, &ctx, vec![], |_| {}, false).0).collect(); + assert_eq!(idle, [1; 6], "each idle frame of the edit runs one pass"); + let typing: Vec = (0..6).map(|_| run_frame(&mut app, &ctx, vec![Event::Text("x".into())], |_| {}, false).0).collect(); + assert_eq!(typing, [1; 6], "each typing frame runs one pass"); + assert!(plain(&app, id).contains("xxxxxx"), "every frame's typing reached the text"); +} diff --git a/crates/ui-egui/src/type_editing.rs b/crates/ui-egui/src/type_editing.rs index 8ee26749a2..878d1d757e 100644 --- a/crates/ui-egui/src/type_editing.rs +++ b/crates/ui-egui/src/type_editing.rs @@ -486,7 +486,8 @@ impl Component for TypeEditor<'_> { } /// Shows the editor part over the Type tool's caret while the tool edits text, before the tool host; returns the part's -/// id. A new edit target is a new IME owner, so a reloaded document interrupts its composition. +/// id. A new edit target is a new IME owner, so a reloaded document interrupts its composition. The part is shown at +/// the caret's rect and takes no room in the canvas's flow, as the canvas's other overlays are. pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> Option { if !app.session.tool_wants_text() || app.viewport_hidden(ui.ctx()) { return None; @@ -496,8 +497,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> Option Date: Sun, 29 Nov 2026 10:54:58 -0800 Subject: [PATCH 08/22] Tests: Save options radios start in the control column The craft-libs pin on main includes craft-libs#4231, which starts a radio row's options past the form's label column. A new test checks that in the EPS and .ai save options dialogs the All and Range radios start where the artboard check box starts, and that Transparent and Opaque start where the Preview menu starts. With the craft-libs rev pinned before #4231 it fails: All starts at x 526 and the check box at x 619. --- .../ui-egui/src/dialogs/save_options/tests.rs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 750e5b1130..666f094e60 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -568,6 +568,31 @@ fn save_options_radios_have_no_empty_caption_over_them() { } } +/// The All and Range radios start where the artboard check box above them starts, in the control column past the +/// captions, and EPS's Transparent and Opaque radios start where the Preview menu starts. +#[test] +fn save_options_radios_start_in_the_control_column() { + for (picked, check) in [("art.eps", "Use Artboards"), ("art.ai", "Save each artboard to a separate file")] { + let (mut app, _, _) = desktop(picked); + save_as(&mut app, "file.saveAs"); + let controls = labelled_controls(&mut app); + let (check, all, range) = (control(&controls, check), control(&controls, "All"), control(&controls, "Range:")); + assert!((all.left() - check.left()).abs() < 1.0, "{picked}: All at {all:?}, the check box at {check:?}"); + assert!((range.left() - check.left()).abs() < 1.0, "{picked}: Range at {range:?}, the check box at {check:?}"); + if picked == "art.eps" { + let (transparent, opaque) = (control(&controls, "Transparent"), control(&controls, "Opaque")); + let preview = controls + .iter() + .filter(|(l, r)| l.trim_end_matches(':') == "Preview" && r.bottom() <= transparent.top()) + .map(|(_, r)| *r) + .max_by(|a, b| a.bottom().total_cmp(&b.bottom())) + .expect("the Preview menu above Transparent"); + assert!((transparent.left() - preview.left()).abs() < 1.0, "Transparent at {transparent:?}, Preview at {preview:?}"); + assert!((opaque.left() - preview.left()).abs() < 1.0, "Opaque at {opaque:?}, Preview at {preview:?}"); + } + } +} + #[test] fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() { let (mut app, written, _) = desktop("original.vectorcraft"); From 65ebc72ec4e2fa9cb7de72ca96220ea04792689c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 11:22:27 -0800 Subject: [PATCH 09/22] Performance: a hover reads each plain path's effects once The culling box of every path a click or hover passes asked whether the path draws geometry effects by reading its effects twice: once on the path itself, and again in the walk of the path and what it holds, which starts at the path. The walk alone now answers, so a hover over many plain paths reads half as much. The walk also stops at the first object with an effect, for drawn art and for a clipping path's region, instead of visiting every member of a large compound path or group after the answer is known. --- crates/doc/src/hit.rs | 26 +++++++++++++---------- crates/doc/src/hit/tests.rs | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 121f12aaeb..18be31051f 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -2,6 +2,7 @@ use std::cell::RefCell; use std::collections::{HashMap, HashSet}; +use std::ops::ControlFlow; use std::rc::Rc; use std::sync::{Arc, OnceLock}; @@ -403,6 +404,8 @@ thread_local! { thread_local! { /// How many objects' drawn art [`drawn`] evaluated on this thread. static DRAWN_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times [`has_own_effects`] read an object's effects on this thread. + static OWN_EFFECTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect @@ -467,7 +470,7 @@ fn plain(mask: bool, f: impl FnOnce() -> T) -> T { /// kept alone. fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc>, Option)> { let f = DRAWN_ART.get()?; - if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) { + if DRAWN_OFF.get() || !evaluates(n) || !draws_effects(symbols, n) { return None; } let doc = symbols.document(); @@ -508,7 +511,7 @@ fn evaluates(n: &Node) -> bool { match &n.kind { NodeKind::Path { guide, .. } => !guide, NodeKind::Compound { .. } => true, - NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(), + NodeKind::Group { .. } | NodeKind::Layer { .. } => !n.appearance.items.is_empty() || has_own_effects(n), _ => false, } } @@ -1120,23 +1123,24 @@ pub(crate) fn clip_region_inputs() -> (u64, bool) { /// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only /// then can the registered [`ClipRegion`] find a geometry effect in it. fn has_effects(clip: &Node) -> bool { - let mut found = false; - clip.walk(&mut |n| found |= has_own_effects(n)); - found + clip.try_walk(&mut |n| if has_own_effects(n) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }).is_break() } /// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible -/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. +/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it. The walk starts +/// at `n`, so its own effects are read once, here, and it ends at the first object with an effect. fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool { - let mut found = false; - n.walk(&mut |c| { - found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol)); - }); - found + n.try_walk(&mut |c| { + let has = has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol)); + if has { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } + }) + .is_break() } /// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes? fn has_own_effects(n: &Node) -> bool { + #[cfg(test)] + OWN_EFFECTS_READ.with(|c| c.set(c.get() + 1)); let visible = |e: &crate::Effect| e.visible; n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)) } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 7ac945e4ee..23ba46415c 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -3569,3 +3569,45 @@ 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"); } + +/// A hover over empty canvas past many plain paths reads each path's effects once, and the layer's +/// once. +#[test] +fn hovers_past_plain_paths_read_each_paths_effects_once() { + set_drawn_art(shifted_art); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let paths = 100; + for i in 0..paths { + 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 reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get); + let before = reads(); + assert!(hit_test(&d, Point::new(900.0, 900.0), HitOptions::default()).is_none()); + let read = reads() - before; + assert_eq!(read, paths + 1, "each path's effects and the layer's are read once"); + assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit"); +} + +/// Whether a compound clipping path, or a compound path, has a live effect is settled by the first +/// object found with one: the members after it are not read. +#[test] +fn an_effect_on_a_compound_path_is_found_without_reading_its_members() { + set_clip_region(moved_clip_region); + set_drawn_art(shifted_art); + let mut d = Document::new(1000.0, 1000.0); + let members: Vec<_> = (0..100) + .map(|i| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(i as f64, 0.0, i as f64 + 5.0, 5.0)), Default::default()))) + .collect(); + let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero }); + mask.appearance.effects.push(test_move()); + let reads = || OWN_EFFECTS_READ.with(std::cell::Cell::get); + let before = reads(); + assert!(has_effects(&mask)); + assert_eq!(reads() - before, 1, "the clipping path's own effect ends the search"); + let symbols = d.symbol_boxes(); + let before = reads(); + assert!(draws_effects(&symbols, &mask)); + assert_eq!(reads() - before, 1, "the compound path's own effect ends the search"); +} From 9f7501a8f6bf523351ef7b6232994da64ea1a31a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 11:24:48 -0800 Subject: [PATCH 10/22] Status bar: scrolling the view no longer lays out the zoom and artboard controls again The status bar's Zoom field, Zoom Presets menu, Rotation menu and artboard navigator were one memoized view keyed on the whole canvas view, so every frame of a wheel pan changed the key and ran all four again. The Zoom field reads only the view's zoom, and the status bar reads only the zoom of the view the field commits. - The Zoom field and Zoom Presets menu are their own memoized view, keyed on the zoom instead of the canvas view, so a pan replays them. - The Rotation menu and the artboard navigator are a second memoized view, so a zoom change runs only the zoom controls. The new test counts the runs of each view over ten pan frames and four zoom changes; before the change the pan ran the navigation controls ten times. --- crates/ui-egui/src/chrome/status_bar.rs | 130 +++++++++++++++--------- 1 file changed, 84 insertions(+), 46 deletions(-) diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 1a3df7737b..b7446defb4 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -1,5 +1,5 @@ use super::{ROTATE_VIEW_ANGLES, Ui, VectorcraftApp, json}; -use craft::behavior::kurbo::Size; +use craft::behavior::kurbo::{Point, Size}; use craft::behavior::{CanvasView, IconId}; use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress}; use craft::ui::buttons::{Button, IconButton}; @@ -31,7 +31,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let view = app.view(); let rotation = view.map_or(0.0, |v| v.rotation); let lang = crate::i18n::current(); - let canvas_view = app.canvas_view(); + let canvas_zoom = app.canvas_view().map(|v| v.zoom); // PLAN: assumed Artboard::rect has `width()` and `height()`. let document = st.and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height())); let scaling = app.ui_scaling(); @@ -92,21 +92,10 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { }; // PLAN: assumed VectorcraftApp::canvas_view() -> Option (cv.S4) and the label msgid "Status Bar". Bar::new(tl!("Status Bar"), BarKind::Status).trailing(readouts).show(ui, |ui, _| { - let navigation = Navigation { - view: canvas_view, - document, - scaling, - print, - shown_zoom, - has_view: view.is_some(), - turned, - degrees, - cur, - revision, - artboards, - lang, - picked: Outbox::new(&mut picks), - }; + let zoom = + ZoomControls { zoom: canvas_zoom, document, scaling, print, shown_zoom, has_view: view.is_some(), lang, picked: Outbox::new(&mut picks) }; + let _ = MemoView::new("status-bar-zoom", zoom, show_zoom).show(ui); + let navigation = Navigation { has_view: view.is_some(), turned, degrees, cur, revision, artboards, lang, picked: Outbox::new(&mut picks) }; let _ = MemoView::new("status-bar-navigation", navigation, show_navigation).show(ui); Divider::vertical().show(ui); // An empty readout shows a dash. @@ -187,13 +176,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } -/// What the status bar's navigation controls read: the Zoom field, the Rotation menu and the artboard navigator. The -/// bar replays them while these hold still and nothing reaches them (`MemoView`), as most frames only move the -/// readouts. +/// What the status bar's Zoom field and Zoom Presets menu read. The bar replays them while these hold still and +/// nothing reaches them (`MemoView`). The canvas view's center is not among them, so a pan replays them. #[derive(MemoProps)] -struct Navigation<'a> { - /// The canvas view the Zoom field shows and edits. - view: Option, +struct ZoomControls<'a> { + /// The canvas view's zoom (`CanvasView::zoom`), which the Zoom field shows and edits. + zoom: Option, /// The size of the artboard the navigator shows, which the Zoom field fits. document: Size, /// UI Scaling, which divides the canvas view's zoom. @@ -202,6 +190,45 @@ struct Navigation<'a> { print: Option, /// The view's zoom percentage, which the Zoom Presets menu checks. shown_zoom: Option, + /// Whether the active document has a view to zoom. + has_view: bool, + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, + /// What the controls chose in the pass. + picked: Outbox<'a, NavigationPick>, +} + +/// The Zoom field and the Zoom Presets menu of the status bar, from [`ZoomControls`]. +fn show_zoom(p: &mut ZoomControls<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::ZOOM_RUNS.with(|n| n.set(n.get() + 1)); + // The field reads only the view's zoom, and the bar reads only the zoom of the view it commits. + let view = p.zoom.map(|zoom| CanvasView::new(egui::Rect::ZERO, Point::ZERO, zoom)); + let document = p.document; + let zoom = Field::new(tl!("Zoom")) + .side(SideLabel::new().kind(LabelKind::Hidden)) + .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).status_bar().show(ui)); + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. + if let Some(zoom) = zoom.inner { + if let Some(view) = zoom.view.committed() { + let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print); + p.picked.send(NavigationPick::Zoom(percent)); + } + if let Some(invalid) = zoom.invalid_zoom { + p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui)))); + } + } + let presets = zoom_presets(p.shown_zoom, p.print); + let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui); + if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked { + p.picked.send(NavigationPick::Preset(preset)); + } +} + +/// What the status bar's Rotation menu and artboard navigator read. The bar replays them while these hold still and +/// nothing reaches them (`MemoView`), as most frames only move the readouts, and a pan or a zoom leaves them alone. +#[derive(MemoProps)] +struct Navigation<'a> { /// Whether the active document has a view to turn. has_view: bool, /// The Rotate View preset the view is turned to, else `usize::MAX`. @@ -234,29 +261,10 @@ enum NavigationPick { Artboard(serde_json::Value), } -/// The Zoom field, the Rotation menu and the artboard navigator of the status bar, from [`Navigation`]. +/// The Rotation menu and the artboard navigator of the status bar, from [`Navigation`]. fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { #[cfg(test)] tests::NAVIGATION_RUNS.with(|n| n.set(n.get() + 1)); - let (view, document) = (p.view, p.document); - let zoom = Field::new(tl!("Zoom")) - .side(SideLabel::new().kind(LabelKind::Hidden)) - .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).status_bar().show(ui)); - // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. - if let Some(zoom) = zoom.inner { - if let Some(view) = zoom.view.committed() { - let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print); - p.picked.send(NavigationPick::Zoom(percent)); - } - if let Some(invalid) = zoom.invalid_zoom { - p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui)))); - } - } - let presets = zoom_presets(p.shown_zoom, p.print); - let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui); - if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked { - p.picked.send(NavigationPick::Preset(preset)); - } let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view); let mut rotate_to = None; @@ -388,13 +396,15 @@ mod tests { thread_local! { /// How many times this thread ran the status bar's navigation controls ([`show_navigation`]). pub(super) static NAVIGATION_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times this thread ran the status bar's Zoom field and Zoom Presets menu ([`show_zoom`]). + pub(super) static ZOOM_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; } - /// Frames that change nothing the navigation controls show replay them instead of laying them out again; a new - /// zoom or a new artboard runs them once, and they show it. + /// Frames that change nothing the zoom and navigation controls show replay them instead of laying them out again; + /// a new zoom or a new artboard runs them once, and they show it. #[test] fn idle_frames_replay_the_navigation_controls() { - let runs = || NAVIGATION_RUNS.with(std::cell::Cell::get); + let runs = || ZOOM_RUNS.with(std::cell::Cell::get) + NAVIGATION_RUNS.with(std::cell::Cell::get); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); @@ -423,6 +433,34 @@ mod tests { assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard"); } + /// Scrolling the view moves its center and nothing the navigation controls show, so frames of a wheel pan replay + /// them; a new zoom runs only the Zoom field and its presets, not the Rotation menu and the artboard navigator. + #[test] + fn wheel_frames_run_only_the_controls_that_show_what_changed() { + let runs = || (ZOOM_RUNS.with(std::cell::Cell::get), NAVIGATION_RUNS.with(std::cell::Cell::get)); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.frame(); + panel.frame(); + let before = runs(); + for i in 0..10 { + panel.app().view_mut().unwrap().center.y += if i % 2 == 0 { 40.0 } else { -25.0 }; + panel.frame(); + } + assert_eq!(runs(), before, "a pan runs neither the zoom controls nor the navigation controls"); + for i in 0..4 { + panel.app().run("view.setZoom", json!({"zoom": 150 + 25 * i})).unwrap(); + panel.frame(); + } + let after = runs(); + assert!(after.0 > before.0, "a new zoom runs the zoom controls"); + assert_eq!(after.1, before.1, "a new zoom does not run the Rotation menu and the artboard navigator"); + assert_eq!(panel.value("Zoom").as_deref(), Some("225%"), "the field shows the last zoom"); + } + #[test] fn the_zoom_presets_menu_sets_a_stop_and_fits_the_view() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); From da9c3947e250e87b0ce3138b3c8971748e56dd10 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Sun, 29 Nov 2026 11:34:41 -0800 Subject: [PATCH 11/22] Dialogs: style options dialogs keep their tab through the framework (#10109) craft-libs 186a229c8d holds storytold/craft-libs#4261, so a properties dialog keeps its bound tab when a measuring frame ends before its body runs. The style_dialog! wrapper no longer saves and restores the tab around that frame for Character Style Options, Paragraph Style Options and New Character Style or New Paragraph Style. New tests open Character Style Options on Advanced Character Formats, New Character Style on Character Color, and Document Setup on Transparency, Type and Color, and check that each tab is still shown after the first frames. With craft-libs before that change they fail with the dialog back on General. --- .../ui-egui/src/dialogs/char_style_options.rs | 10 +----- .../src/dialogs/char_style_options/tests.rs | 32 +++++++++++++++++++ crates/ui-egui/src/dialogs/document_setup.rs | 28 ++++++++++++++++ 3 files changed, 61 insertions(+), 9 deletions(-) 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(); From 3617039ef5c2b953e2f6e028a1d4cc88c680fc22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 11:36:48 -0800 Subject: [PATCH 12/22] Global Edit: the canvas shares the kept outlines instead of copying them each frame With one object selected and the Selection tool active, or while Global Edit is on, every frame copied each highlighted outline out of the kept list and made one overlay per object, which the canvas flattened and stroked again. With 10,000 matching objects that was most of a 27 ms frame. highlights and similar now return the kept outlines as a shared Highlights, grouped by layer color with a revision that changes only when the outlines are found again. The session sends one Overlay::Outlines per color, and the canvas shows it as a SelectionOutline keyed by that revision, so the lines are stroked again only when the outlines or the view change. --- crates/engine/src/cmd/globaledit.rs | 65 ++++++++++++++++++++++----- crates/engine/src/tests/globaledit.rs | 42 +++++++++++++++-- crates/engine/src/tooling.rs | 9 ++-- crates/tools/src/lib.rs | 5 +++ crates/ui-egui/src/canvas/overlays.rs | 10 ++++- crates/ui-egui/src/canvas/tests.rs | 24 ++++++++++ 6 files changed, 136 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 4f498e972a..cecf216b24 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -194,6 +194,51 @@ impl Options { /// Outlines with their layer colours ([`highlights`]). pub type Outlines = Vec<(BezPath, [u8; 3])>; +/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same +/// allocation back until the outlines are found again. +#[derive(Debug, Default, PartialEq)] +pub struct Highlights { + /// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines + /// it stroked for these outlines while the number stays the same. + pub revision: u64, + /// The outlines in each layer color, the colors in the order of their first outline. + pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>, +} + +/// The [`Highlights::revision`] the next set of outlines takes. +static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing. +static NO_HIGHLIGHTS: std::sync::LazyLock> = std::sync::LazyLock::new(Default::default); + +impl Highlights { + /// `outlines` grouped by color, under a new revision. + fn new(outlines: Outlines) -> std::sync::Arc { + if outlines.is_empty() { + return NO_HIGHLIGHTS.clone(); + } + let mut groups: Vec<([u8; 3], Vec)> = vec![]; + for (path, color) in outlines { + match groups.iter_mut().find(|(c, _)| *c == color) { + Some((_, paths)) => paths.push(path), + None => groups.push((color, vec![path])), + } + } + let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() }) + } + + /// How many outlines there are, in every color. + pub fn len(&self) -> usize { + self.groups.iter().map(|(_, paths)| paths.len()).sum() + } + + /// Whether there is no outline. + pub fn is_empty(&self) -> bool { + self.groups.iter().all(|(_, paths)| paths.is_empty()) + } +} + /// A Global Edit in progress (per document; not saved, not an undo step). #[derive(Clone, Debug, PartialEq)] pub struct GlobalEdit { @@ -202,7 +247,7 @@ pub struct GlobalEdit { /// outline onto its own. pub members: Vec<(NodeId, Affine)>, /// [`highlights`] as of a document revision: the canvas asks every frame. - outlines: std::cell::RefCell>, + outlines: std::cell::RefCell)>>, } /// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells @@ -1017,31 +1062,31 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) { /// highlights them while Global Edit is on. While it is off, with one supported object selected, /// they are the outlines of the objects Start Global Edit would take with the Global Edit Options /// ([`similar`]). -pub fn highlights(s: &Session) -> Outlines { - let Some(st) = s.active() else { return vec![] }; +pub fn highlights(s: &Session) -> std::sync::Arc { + let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() }; let Some(ge) = &st.global_edit else { return similar(s) }; if let Some((rev, out)) = &*ge.outlines.borrow() && *rev == st.revision { return out.clone(); } - let out = outlines(st, &ge.members); + let out = Highlights::new(outlines(st, &ge.members)); *ge.outlines.borrow_mut() = Some((st.revision, out.clone())); out } /// [`similar`]'s outlines as of a document revision and the options they were found with. -pub type SimilarCache = std::cell::RefCell>; +pub type SimilarCache = std::cell::RefCell)>>; /// Before Global Edit starts: with one supported object selected, the outlines of the other /// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas /// shows them as soon as the object is selected. None while an interaction (a drag) is in /// progress, or when fewer than two objects would be taken. Kept per document revision and /// options, as finding them walks the whole document. -pub fn similar(s: &Session) -> Outlines { - let Some(st) = s.active() else { return vec![] }; +pub fn similar(s: &Session) -> std::sync::Arc { + let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() }; if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 { - return vec![]; + return NO_HIGHLIGHTS.clone(); } let o = &s.global_edit_options; if let Some((rev, opts, out)) = &*st.similar_outlines.borrow() @@ -1050,10 +1095,10 @@ pub fn similar(s: &Session) -> Outlines { { return out.clone(); } - let out = match matches(s, o) { + let out = Highlights::new(match matches(s, o) { Ok(m) if m.len() >= 2 => outlines(st, &m), _ => vec![], - }; + }); *st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone())); out } diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index ae56fa7c5a..076816e994 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -150,7 +150,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() { assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar"); assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match"); let moved = node(&s, copies[1]).stroke_path().unwrap(); - assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now"); + assert!(shown.groups.iter().flat_map(|(_, paths)| paths.iter()).any(|p| *p == moved), "the moved copy is shown where it is now"); s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out"); assert_eq!(crate::cmd::globaledit::match_count(&s), 38); @@ -162,9 +162,7 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too let [a, b, ..] = squares(&mut s); let outline = node(&s, b).stroke_path().unwrap(); let shown = |s: &mut Session| { - s.overlays(ViewInfo::default()) - .iter() - .any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0)) + s.overlays(ViewInfo::default()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Outlines { paths, .. } if paths.contains(&outline))) }; sel(&mut s, &[a]); s.select_tool("selection", ViewInfo::default()).unwrap(); @@ -175,6 +173,42 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too assert!(shown(&mut s), "while Global Edit is on, with any tool"); } +/// Each frame hands the canvas the kept outlines, one overlay per layer color sharing them, with no copy of a path; the +/// revision changes when the outlines are found again. +#[test] +fn every_frame_shares_the_kept_outlines_instead_of_copying_each_one() { + use std::sync::Arc; + use vectorcraft_tools::Overlay; + let outlines = |s: &mut Session| -> Vec<(Arc<[vectorcraft_geom::BezPath]>, u64)> { + s.overlays(ViewInfo::default()) + .into_iter() + .filter_map(|o| if let Overlay::Outlines { paths, revision, .. } = o { Some((paths, revision)) } else { None }) + .collect() + }; + let mut s = session(); + let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + for i in 1..200 { + rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0); + } + sel(&mut s, &[key]); + s.select_tool("selection", ViewInfo::default()).unwrap(); + let first = outlines(&mut s); + let [(paths, revision)] = &first[..] else { panic!("one overlay for the one layer color, not one per object: {}", first.len()) }; + assert_eq!(paths.len(), 199); + let second = outlines(&mut s); + let [(again, same)] = &second[..] else { panic!("{}", second.len()) }; + assert!(Arc::ptr_eq(paths, again), "the next frame gets the same outlines, not a copy"); + assert_eq!(same, revision); + s.execute("select.globalEdit", &json!({})).unwrap(); + let on = outlines(&mut s); + let [(members, started)] = &on[..] else { panic!("{}", on.len()) }; + assert_eq!(members.len(), 199); + assert_ne!(started, revision, "outlines found again take a new revision"); + let next = outlines(&mut s); + let [(kept, still)] = &next[..] else { panic!("{}", next.len()) }; + assert!(Arc::ptr_eq(members, kept) && still == started, "and are kept from frame to frame while Global Edit is on"); +} + #[test] fn size_and_appearance_options_narrow_the_match() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index c5d2905963..422caab5ec 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1478,9 +1478,12 @@ impl Session { // Global Edit: the objects edited with the selected one are highlighted; before it starts, // with the Selection tool, the objects it would take. let ge_on = self.active().is_some_and(|d| d.global_edit.is_some()); - let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] }; - for (path, color) in shown { - v.push(Overlay::Path { path, color, width: 1.0, dashed: false }); + // One overlay per layer color, sharing the kept outlines. + if ge_on || self.tool.id() == "selection" { + let shown = crate::cmd::globaledit::highlights(self); + for (color, paths) in &shown.groups { + v.push(Overlay::Outlines { paths: paths.clone(), color: *color, revision: shown.revision }); + } } if let Some((cmd, p)) = deferred_preview { v.extend(self.deferred_preview_overlays_from_command(&cmd, &p)); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index cfcce40bf9..7d0c17f068 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -88,6 +88,11 @@ pub enum Overlay { /// the dash pattern: the pieces of one line, each starting where the one before it ends, dash /// as the whole line does. SharedPath { path: std::sync::Arc, color: [u8; 3], width: f32, dash: Option }, + /// Thin solid outlines of many objects in one color (the objects Global Edit takes). Later calls + /// return the same `paths` with the same `revision` for as long as the outlines do not change, and + /// a new `revision` when they do. The host strokes them again only when `revision` or the view + /// changes. + Outlines { paths: std::sync::Arc<[BezPath]>, color: [u8; 3], revision: u64 }, /// A line segment (smart guide, handle line). Line { a: Point, b: Point, color: [u8; 3], dashed: bool }, /// An anchor square: filled = selected. diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 8f9bd6f663..d1f8c469a8 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -48,7 +48,7 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, }); } -/// The framework control `o` stands for, if it is one: a marquee, a settled outline or a distance. +/// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance. fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) { match o { Overlay::Marquee(r) => { @@ -65,6 +65,11 @@ fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) { let outline = if dash.is_some() { SelectionOutline::dashed(Label::Empty, paths) } else { SelectionOutline::solid(Label::Empty, paths) }; outline.color(data(*color)).revision(revision).show_at(ui, rect); } + Overlay::Outlines { paths, color, revision } => { + // The overlay's revision changes whenever its paths do, so the lines are stroked again only then or when + // the view changes. + SelectionOutline::solid(Label::Empty, paths).color(data(*color)).revision(*revision).show_at(ui, rect); + } Overlay::Distance { .. } => { if let Some((measure, color)) = distance_measure(o) { SmartGuides::new(&[], std::slice::from_ref(&measure)).color(color).show_at(ui, rect); @@ -180,7 +185,7 @@ impl Component for ToolMarks<'_> { } } -/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths and distances are controls +/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths, outlines and distances are controls /// of their own and paint nothing here. // PLAN: contract cv.S14 gives `paint(draw, view, overlays, options)`; the pill, ink and ring colours come from the theme, so the style goes too. fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &PathOptionsSettings, style: &ToolMarksStyle) { @@ -244,6 +249,7 @@ fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &Pat Overlay::Marquee(_) | Overlay::SelectionMarquee { .. } | Overlay::SharedPath { .. } + | Overlay::Outlines { .. } | Overlay::Distance { .. } | Overlay::HoverText { .. } => {} } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index ae6956a288..a5fa556b8c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -333,6 +333,30 @@ fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { assert!(moved >= 4, "the drag moves the object: {moved} frames"); } +/// With one rectangle selected, the canvas outlines its copies, which Start Global Edit would take, at their corners. +#[test] +fn the_canvas_outlines_the_objects_global_edit_would_take() { + let mut app = drag_app(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap() + }; + let key = rect(&mut app, 20.0); + let copies = [rect(&mut app, 120.0), rect(&mut app, 220.0)]; + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [key]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let points = painted_points(&mut app, &ctx, vec![]); + for id in copies { + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y1)] { + let at = xf.to_screen(corner); + assert!(points.iter().any(|p| p.distance(at) < 1.0), "copy {id} is outlined at {at:?}"); + } + } +} + /// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and /// none at the pointer of the frame before. #[test] From c7487a4657285922e15b78d6b6fb608a1b427fed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 11:42:07 -0800 Subject: [PATCH 13/22] Missing Fonts: the frame after an open lists a document's missing fonts once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The frame after a document opens checked whether its Missing Fonts dialog waits by building the whole dialog (opening::may_switch), and the dialog pump then built it again to open it. Each build walked the document's type and resolved every font it names: 6.5 ms over the two calls at 20,000 objects. The rows are now kept in CanvasCache::missing_fonts for the document's content version and the font database's generation, the same key Type › Find Font's cache uses, and both calls read them. An edit or a font that loads while the dialog waits makes the next call list the fonts again. The Fonts folder next to the document is still looked up when the dialog opens. Rows are dropped once their document no longer waits. text.missingFonts's answer is unchanged; its rows and its folder are now two engine functions, missing_font_rows and fonts_next_to_document. Tests count the row lists (one for the check and the open together) and check that a document edited while its dialog waits lists its new font. --- crates/engine/src/cmd/fontfiles.rs | 44 ++++++++++++------- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 13 ++++++ crates/ui-egui/src/dialogs/missing_fonts.rs | 42 +++++++++++++++--- .../src/dialogs/missing_fonts/tests.rs | 34 ++++++++++++++ crates/ui-egui/src/opening.rs | 7 ++- 6 files changed, 116 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/fontfiles.rs b/crates/engine/src/cmd/fontfiles.rs index c13b256210..4cc41982df 100644 --- a/crates/engine/src/cmd/fontfiles.rs +++ b/crates/engine/src/cmd/fontfiles.rs @@ -114,7 +114,17 @@ pub fn missing_fonts(d: &Document) -> Vec { /// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this /// computer's when `None`). pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value { - let fonts: Vec = missing_fonts(&st.doc) + let fonts = missing_font_rows(&st.doc); + let mut out = json!({ "count": fonts.len(), "fonts": fonts }); + if let Some(dir) = fonts_next_to_document(st, rules) { + out["fontsNextToDocument"] = json!(dir); + } + out +} + +/// `text.missingFonts`'s `fonts` rows for `d` ([`missing_fonts`]). +pub fn missing_font_rows(d: &Document) -> Vec { + missing_fonts(d) .into_iter() .map(|m| { json!({ @@ -122,26 +132,26 @@ pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Valu "resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })), }) }) - .collect(); - let mut out = json!({ "count": fonts.len(), "fonts": fonts }); + .collect() +} + +/// `text.missingFonts`'s `fontsNextToDocument` for the open document `st`, where searches go by +/// `rules` (this computer's when `None`). +pub fn fonts_next_to_document(st: &DocState, rules: Option<&findfiles::Rules>) -> Option { // File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder // is made absolute against the working folder when the document's path is relative. It is // offered when a search may start there, as far as the rules tell without listing a folder. - if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) { - let dir = super::fileio::absolute_path(&dir.to_string_lossy()); - let system; - let rules = match rules { - Some(rules) => rules, - None => { - system = findfiles::Rules::system(); - &system - } - }; - if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) { - out["fontsNextToDocument"] = json!(dir); + let dir = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir())?; + let dir = super::fileio::absolute_path(&dir.to_string_lossy()); + let system; + let rules = match rules { + Some(rules) => rules, + None => { + system = findfiles::Rules::system(); + &system } - } - out + }; + std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()).then_some(dir) } fn missing(s: &mut Session, _: &Value) -> Result { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5b7221b7c2..cae4d9f39f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -134,6 +134,7 @@ impl VectorcraftApp { print_tiling: None, live_paint_gaps: None, find_font: None, + missing_fonts: vec![], hidden_chars: Default::default(), spelling: Default::default(), text_nodes: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6679ecf591..7f0ade064e 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -64,6 +64,10 @@ pub struct CanvasCache { /// version of the document's content and of the available fonts: the dialog reads them every /// frame. pub find_font: Option, + /// The missing fonts of each document whose Missing Fonts dialog waits to open, for a version of + /// the document's content and of the available fonts: the frame that checks whether a dialog + /// waits and the frame's pump that opens it read the same list. + pub missing_fonts: Vec, /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::marks::HiddenChars, @@ -253,6 +257,15 @@ pub struct FindFontCache { pub missing: Option, } +/// [`CanvasCache::missing_fonts`]: a document's `text.missingFonts` rows +/// ([`vectorcraft_engine::cmd::fontfiles::missing_font_rows`]). +#[derive(Clone, Debug)] +pub struct MissingFontsCache { + /// The document and the content and fonts the rows were worked out from. + pub key: FontsKey, + pub fonts: Vec, +} + /// A document's uid, a version of its content (compared by identity) and the font database's /// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's /// allocation, so a later version is never placed at the same address while the key is kept. diff --git a/crates/ui-egui/src/dialogs/missing_fonts.rs b/crates/ui-egui/src/dialogs/missing_fonts.rs index 96a32785e3..bd06b24e40 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts.rs @@ -35,6 +35,7 @@ use egui::{Context, Ui}; use serde_json::{Map, Value, json}; use crate::VectorcraftApp; +use crate::caches::{FontsKey, MissingFontsCache}; use crate::file_asks::{self, Owner}; /// The dialog's key and kind: the fonts a document opened without. @@ -327,19 +328,45 @@ fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) { } /// Whether an opened document's Missing Fonts dialog waits for the frame's pump to open it. -pub(crate) fn waiting(app: &VectorcraftApp) -> bool { - app.ui.pending_fonts.iter().any(|&uid| dialog_for(app, uid).is_some()) +pub(crate) fn waiting(app: &mut VectorcraftApp) -> bool { + let queued = app.ui.pending_fonts.clone(); + queued.into_iter().any(|uid| missing_rows(app, uid).is_some_and(|fonts| !fonts.is_empty())) } /// The Missing Fonts dialog of the open document `uid`, when fonts it uses aren't available. -fn dialog_for(app: &VectorcraftApp, uid: u64) -> Option { +fn dialog_for(app: &mut VectorcraftApp, uid: u64) -> Option { + let fonts = missing_rows(app, uid).filter(|f| !f.is_empty())?; let st = app.session.documents().iter().find(|d| d.uid == uid)?; - let r = vectorcraft_engine::cmd::fontfiles::missing_fonts_of(st, app.session.search_rules.as_ref()); - let fonts = r["fonts"].as_array().filter(|f| !f.is_empty())?.clone(); - let next = r["fontsNextToDocument"].as_str().unwrap_or_default().to_string(); + let next = vectorcraft_engine::cmd::fontfiles::fonts_next_to_document(st, app.session.search_rules.as_ref()).unwrap_or_default(); Some(MissingFontsDialog::new(State::new(uid, fonts, next, file_asks::can(app, PickKind::Folder)))) } +#[cfg(test)] +thread_local! { + /// How many times [`missing_rows`] worked out a document's missing fonts. + static ROW_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The `text.missingFonts` rows of the open document `uid` (`None` when it is closed), kept in +/// [`crate::CanvasCache::missing_fonts`] and worked out again only for another version of its +/// content or another font generation. +fn missing_rows(app: &mut VectorcraftApp, uid: u64) -> Option> { + let st = app.session.documents().iter().find(|d| d.uid == uid)?; + // The generation is read first: fonts loaded while the rows are worked out leave the entry + // under the older generation, so the next look works them out again. + let key = FontsKey { uid, doc: std::sync::Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() }; + if let Some(c) = app.canvas.missing_fonts.iter().find(|c| c.key == key) { + return Some(c.fonts.clone()); + } + #[cfg(test)] + ROW_SCANS.set(ROW_SCANS.get() + 1); + let fonts = vectorcraft_engine::cmd::fontfiles::missing_font_rows(&st.doc); + let cache = &mut app.canvas.missing_fonts; + cache.retain(|c| c.key.uid != uid); + cache.push(MissingFontsCache { key, fonts: fonts.clone() }); + Some(fonts) +} + /// Once per frame: run what the finished dialog left to do, follow a running search, stop the search /// of a dialog that is gone, and with no dialog open open the dialog of the first queued document /// that is still open and still misses fonts. @@ -360,6 +387,9 @@ pub(crate) fn open_next(app: &mut VectorcraftApp) { } break; } + // Only the documents that still wait keep their rows. + let queued = &app.ui.pending_fonts; + app.canvas.missing_fonts.retain(|c| queued.contains(&c.key.uid)); } /// Run what `answer` asks, and open the dialog again when it stays open (a search starts, a search diff --git a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs index dad177950a..de32e2cbe6 100644 --- a/crates/ui-egui/src/dialogs/missing_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/missing_fonts/tests.rs @@ -445,6 +445,40 @@ fn reopening_an_open_document_does_not_ask_about_its_fonts_again() { assert!(!is_open::(&app)); } +/// The frame after an open checks whether a Missing Fonts dialog waits (before a file that finished +/// opening may come to the front) and then opens it: the document's missing fonts are worked out +/// once for both. +#[test] +fn the_frame_after_an_open_works_out_the_missing_fonts_once() { + let root = folder("once"); + let mut app = app_for(&root); + let doc = root.join("doc.vectorcraft"); + save_doc(&mut app, &doc, "No Such Font Family", false); + open(&mut app, &doc); + ROW_SCANS.set(0); + assert!(!crate::opening::may_switch(&mut app), "the dialog waits for the pump"); + pump(&mut app); + assert_eq!(family(&app).as_deref(), Some("No Such Font Family")); + assert_eq!(ROW_SCANS.get(), 1, "one look at the document's fonts"); + assert!(app.canvas.missing_fonts.is_empty(), "the rows go once the dialog opens"); +} + +/// A document changed while its dialog waits lists the fonts of its new content. +#[test] +fn a_document_changed_while_its_dialog_waits_lists_its_new_fonts() { + let root = folder("changed"); + let mut app = app_for(&root); + let doc = root.join("doc.vectorcraft"); + save_doc(&mut app, &doc, "Alpha Missing Family", false); + open(&mut app, &doc); + assert!(!crate::opening::may_switch(&mut app)); + app.run("text.create", json!({"x": 10, "y": 80, "text": "More", "font": "Beta Missing Family"})).unwrap(); + pump(&mut app); + let fonts = fields(&app).expect("the dialog is open")["fonts"].clone(); + let families: Vec<_> = fonts.as_array().unwrap().iter().map(|f| f["family"].as_str().unwrap_or_default()).collect(); + assert_eq!(families, ["Alpha Missing Family", "Beta Missing Family"]); +} + /// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does. #[test] fn edit_original_asks_about_the_placed_documents_fonts() { diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index f45209ee65..5e72952fe2 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -147,9 +147,12 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver bool { +pub(crate) fn may_switch(app: &mut VectorcraftApp) -> bool { + if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) { + return false; + } let s = &app.session; - !(app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) || s.in_interaction() || (s.tool_busy() && s.pointer_held())) + !(s.in_interaction() || (s.tool_busy() && s.pointer_held())) } /// Open the files that are ready (each frame). Not while a dialog is open: a document that opens From 214c88d98536c143061b8560dff02f092afa1804 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 11:45:44 -0800 Subject: [PATCH 14/22] Tools: the controls under the tools scroll with them, as bottom_controls says The doc comment on bottom_controls still said the tools scroll above the controls in a short rail. The Tools panel's rail now uses footer_scrolls, so the controls scroll with the tools and the rail draws the rule above them. --- crates/ui-egui/src/toolbar.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 4d58c972d7..618bace39b 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -772,8 +772,8 @@ 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. The rail's footer region draws the rule that parts them from the tools, which scroll -/// above it in a short rail. +/// section hides any of them. The rail draws the rule that parts them from the tools, and they scroll with the tools +/// 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; From 4f6eb4b36dbfcffe41d8b3f290b49c7cea7de633 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 11:53:39 -0800 Subject: [PATCH 15/22] 3D: depth, bevel and offset fields show the document's unit Extrude & Bevel's Depth and bevel Width and Height, Revolve's Offset, the classic Extrude & Bevel and Revolve rows, and the Map Art X and Y rows showed points in a document set to millimeters, inches or another unit. Each row now goes through Param::length, so its field shows and reads the document's unit while the effect keeps points. The rows set no decimals, so a typed 10 mm is kept unrounded and Up steps by the shown unit's own step. --- crates/ui-egui/src/dialogs/revolve.rs | 10 ++- crates/ui-egui/src/dialogs/revolve/tests.rs | 65 +++++++++++++++++-- crates/ui-egui/src/dialogs/three_d_classic.rs | 48 ++++++++------ 3 files changed, 93 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index a3acab8b0b..5d2d8ee72e 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -14,7 +14,6 @@ use craft::ui::contract::{Bind, CollectionEvent, Gap, Props as _, Show as _, Sho use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; use craft::ui::pickers::Select; -use craft::ui::runtime::env::LengthUnits; use craft::ui::runtime::env::UnitKind; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::tabs::{Tab, TabKind, TabStrip}; @@ -194,12 +193,11 @@ impl Rows<'_> { self.range(key, label, range, 1, UnitKind::Percent) } - /// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says. + /// A length in points, shown in the general unit as [`length_units`](super::three_d_classic::length_units) says. fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param { - // Stored in points; a pixel is a point, as the rulers count it. - let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0); - let shown = super::three_d_classic::length_unit(self.unit); - self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points)) + let lengths = super::three_d_classic::length_units(self.unit, self.bare_points); + let row = Param::new(key, label, ParamKind::range(range.0, range.1, self.default_number(key), SliderScale::Linear)).resettable(); + super::three_d_classic::as_length(row, lengths) } fn flag(&self, key: &str, label: &'static str) -> Param { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index ceb96018f7..16b99491a6 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -494,10 +494,10 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() { assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent))); } -/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their -/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit. +/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, hold points and show the +/// document's unit: "pt" in a points document, "px" in a pixels one, "mm" in a millimeters one, "in" in an inches one. #[test] -fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { +fn the_3d_length_rows_show_the_document_unit() { use craft::ui::patterns::form_dialogs::DialogFields; use craft::ui::runtime::env::UnitKind; use vectorcraft_doc::Unit; @@ -510,7 +510,13 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit) }; let mut checked = 0; - for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] { + let units = [ + (Unit::Points, UnitKind::Points), + (Unit::Pixels, UnitKind::Pixels), + (Unit::Millimeters, UnitKind::Millimetres), + (Unit::Inches, UnitKind::Inches), + ]; + for (general, shown) in units { for key in ["depth", "bevelWidth", "bevelHeight"] { assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}"); checked += 1; @@ -526,7 +532,56 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { checked += 1; } } - assert_eq!(checked, 21); + assert_eq!(checked, 28); +} + +/// In a millimeters document the 3D dialogs' depth and offset fields show the 72 pt they hold as 25.4 mm, and a +/// number typed there is read in millimeters and kept unrounded; Up steps by a millimeter step. +#[test] +fn a_3d_dialog_in_a_millimeters_document_shows_its_lengths_in_millimeters() { + use craft::ui::contract::Role; + let rows = [ + (CLASSIC_EXTRUDE, "object", "depth", "Depth"), + (CLASSIC_REVOLVE, "object", "offset", "Offset"), + (EXTRUDE, "object", "depth", "Depth"), + (REVOLVE, "rotation", "offset", "Offset"), + ]; + for (effect, page, key, name) in rows { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300,"units":"Millimeters"})).unwrap(); + app.run("path.create", json!({"d": SQUARE})).unwrap(); + let mut h = opened(app, json!({"effect": effect, "item": null})); + h.set("__page", json!(page)); + h.set(key, json!(72.0)); + let field = |h: &ThreeD| { + let tree = h.fixture.tree(); + h.fixture + .by_role(Role::SPIN_BUTTON) + .into_iter() + .find(|t| tree.name_of(t.node) == Some(name)) + .unwrap_or_else(|| panic!("{effect}: no {name} field")) + }; + let shown = h.fixture.tree().value_of(field(&h).node).map(str::to_owned); + assert!(shown.as_deref().is_some_and(|s| s.contains("25.4") && s.contains("mm")), "{effect} {key}: 72 pt shows as 25.4 mm: {shown:?}"); + let target = field(&h); + h.fixture.click(&target); + // Tab commits the field and leaves the dialog open (Enter would press OK). + h.fixture.key(Key::A, Modifiers::COMMAND).type_text("10").key(Key::Tab, Modifiers::NONE); + h.settle(); + let stored = h.json(key); + assert!( + stored.as_f64().is_some_and(|points| (points - 10.0 * 72.0 / 25.4).abs() < 1e-3), + "{effect} {key}: 10 mm is kept in points: {stored:?}" + ); + // Up moves by the shown unit's own step, at least a tenth of a millimeter. + let target = field(&h); + h.fixture.click(&target); + h.fixture.key(Key::ArrowUp, Modifiers::NONE).key(Key::Tab, Modifiers::NONE); + h.settle(); + let moved = h.json(key).as_f64().zip(stored.as_f64()).map(|(after, before)| after - before); + assert!(moved.is_some_and(|by| by >= 0.1 * 72.0 / 25.4 - 1e-6), "{effect} {key}: Up moves at least 0.1 mm: {moved:?}"); + h.cancel(); + } } #[test] diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index f461b3cfe2..5c7c0f8254 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -20,7 +20,7 @@ use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; use craft::ui::pickers::Select; use craft::ui::primitives::ContentPainterCx; -use craft::ui::runtime::env::{Env, UnitKind}; +use craft::ui::runtime::env::{Env, LengthUnits, UnitKind}; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::style::DataColor; use craft::ui::text::NumberField; @@ -50,13 +50,23 @@ const MAP_SYMBOL: &str = "mapSymbol"; /// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters. pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]]; -/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when -/// that counts the same number (points, or pixels at 72 per inch), and points otherwise. -pub(super) fn length_unit(unit: Unit) -> UnitKind { - match crate::canvas::rulers::unit_kind(unit) { - UnitKind::Pixels => UnitKind::Pixels, - _ => UnitKind::Points, - } +/// The lengths of a 3D length row: stored in points and shown in the general `unit` (a pixel is a point, as the rulers +/// count it), a bare number read as Numbers Without Units Are Points (`bare_points`) says. +pub(super) fn length_units(unit: Unit, bare_points: bool) -> LengthUnits { + crate::fields::bare_points(LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(unit), 72.0), bare_points) +} + +/// `row`, a range row of points with no decimals set, as a length shown in `lengths.shown`. Without set decimals the +/// field keeps the shown unit's own places and step, and the points are kept unrounded, so a value typed in +/// millimeters or inches reads back as typed. +pub(super) fn as_length(row: Param, lengths: LengthUnits) -> Param { + row.unit(lengths.shown).length(lengths) +} + +/// A length row over `range` points with the effect's default, shown as [`as_length`] says. +fn length_row(effect: &str, key: &str, label: &'static str, range: (f64, f64), lengths: LengthUnits) -> Param { + let default = vectorcraft_effects::default_params(effect).and_then(|p| p.get(key).and_then(Value::as_f64)).unwrap_or(range.0); + as_length(Param::new(key, label, ParamKind::range(range.0, range.1, default, SliderScale::Linear)).resettable(), lengths) } /// Where the rows show: the 3D and Materials panel marks its fields with `__panel`. @@ -120,15 +130,15 @@ fn map_art_button(fields: &DialogFields) -> Option { /// Extrude & Bevel (Classic)'s Object page: depth and cap, then the bevel: its shape (a custom one included), its /// height and whether it is added around the shape or carved into it. pub(crate) fn object_params(data: &Data, fields: &DialogFields, effect: &str) -> Vec { - let unit = Some(length_unit(data.unit)); + let lengths = length_units(data.unit, data.bare_points); let shaped: Vec<&str> = options_of(effect, "bevel").into_iter().map(|(value, _)| value).filter(|v| *v != "none").collect(); let mut rows = vec![ Param::section(tl!("Object")), - range_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), unit, 1), + length_row(effect, "depth", tl!("Depth"), (0.0, 2000.0), lengths), cap_row(effect), Param::section(c3("Bevel")), bevel_row(data, CLASSIC_EXTRUDE, place_of(fields)), - range_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), unit, 1).enabled_when_in("bevel", shaped.clone()), + length_row(effect, "bevelHeight", tl!("Height"), (1.0, 100.0), lengths).enabled_when_in("bevel", shaped.clone()), toggle_row(effect, "bevelInside", tl!("Bevel Inside")).enabled_when_in("bevel", shaped), ]; rows.extend(map_art_button(fields)); @@ -141,7 +151,7 @@ pub(crate) fn revolve_params(data: &Data, fields: &DialogFields, effect: &str) - Param::section(tl!("Object")), range_row(effect, "angle", tl!("Angle"), (0.0, 360.0), Some(UnitKind::Degrees), 1), cap_row(effect), - range_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), Some(length_unit(data.unit)), 1), + length_row(effect, "offset", tl!("Offset"), (0.0, 1000.0), length_units(data.unit, data.bare_points)), choice_row(effect, "edge", tl!("Axis side")), ]; rows.extend(map_art_button(fields)); @@ -505,7 +515,7 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) - let flat_row = flat.clone(); rows.push(Param::custom("__mapFlat", "", move |ui, fields, _| flat_view(ui, fields, &flat_row)).full_width()); if let Some(m) = &map { - let unit = Some(length_unit(data.unit)); + let lengths = length_units(data.unit, data.bare_points); let values = [m.x, m.y, m.scale_x, m.scale_y, m.rotation]; let labels = ["X", "Y", tl!("Horizontal Scale"), tl!("Vertical Scale"), tl!("Rotation")]; let bounds = [ @@ -515,14 +525,14 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) - GRAPHIC_SCALE_RANGE, (-360.0, 360.0), ]; - let kinds = [unit, unit, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)]; + // X and Y are lengths in points; the scales are shares and the rotation an angle. + let kinds = [None, None, Some(UnitKind::Percent), Some(UnitKind::Percent), Some(UnitKind::Degrees)]; for i in 0..MAP_KEYS.len() { - let row = Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear)) - .decimals(2) - .on_set(set_map_value); + let row = + Param::new(MAP_KEYS[i], labels[i], ParamKind::range(bounds[i].0, bounds[i].1, values[i], SliderScale::Linear)).on_set(set_map_value); rows.push(match kinds[i] { - Some(kind) => row.unit(kind), - None => row, + Some(kind) => row.decimals(2).unit(kind), + None => as_length(row, lengths), }); } } From c3c8a0a17a78966a8417c711b25aa596308c9eb7 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 21:28:17 +0100 Subject: [PATCH 16/22] Pin Binaryen 133 for the web release optimizer --- apps/vectorcraft-web/Trunk.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/vectorcraft-web/Trunk.toml b/apps/vectorcraft-web/Trunk.toml index aad9a1638f..1bb9ef3f24 100644 --- a/apps/vectorcraft-web/Trunk.toml +++ b/apps/vectorcraft-web/Trunk.toml @@ -5,6 +5,10 @@ dist = "../../dist/web" public_url = "./" filehash = true +[tools] +# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit. +wasm_opt = "version_133" + [serve] addresses = ["127.0.0.1"] port = 8766 From b893f05f61992398a07fb6d4dfe575c4aeec6c73 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 12:57:08 -0800 Subject: [PATCH 17/22] 3D: Map Art X and Y keep the points a document unit converts to Typing 10 into X in a millimeters document stored 28.35 pt instead of 28.3464567 pt, because the X and Y setters rounded to two point decimals. They now only clamp. The flat view also wrote the map back through the box on every frame, rounding the offsets again; it now writes the map only when the box was edited. --- crates/ui-egui/src/dialogs/three_d_classic.rs | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 5c7c0f8254..1a5acb6f6f 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -282,8 +282,9 @@ fn set_map_value(fields: &mut DialogFields, key: &str, value: Value) -> Result<( let n = value.as_f64().filter(|n| n.is_finite()).ok_or("not a number")?; let mut m = old.ok_or("the surface has no map")?; match key { - "mapX" => m.x = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), - "mapY" => m.y = round_clamp(n, 2, -GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), + // X and Y arrive in points converted from the document's unit: rounding them would move a typed 10 mm. + "mapX" => m.x = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), + "mapY" => m.y = n.clamp(-GRAPHIC_MAX_OFFSET, GRAPHIC_MAX_OFFSET), "mapScaleX" => m.scale_x = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1), "mapScaleY" => m.scale_y = round_clamp(n, 2, GRAPHIC_SCALE_RANGE.0, GRAPHIC_SCALE_RANGE.1), "mapRotation" => m.rotation = n.clamp(-360.0, 360.0), @@ -380,6 +381,12 @@ fn map_of_box(state: &BoxState, rect: Rect, base: &SurfaceMap) -> SurfaceMap { } } +/// The map a box edit leaves, or none while the box is still the one `map` drew (`drawn`), so a frame without an edit +/// keeps the map's numbers exactly as typed. +fn map_after_edit(state: &BoxState, drawn: &BoxState, rect: Rect, map: &SurfaceMap) -> Option { + (state != drawn).then(|| map_of_box(state, rect, map)).filter(|moved| moved != map) +} + /// The id of Map Art's Done, in the footer as Reset all is on the other pages. pub(crate) const MAP_DONE: &str = "mapDone"; @@ -416,6 +423,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { } let (Some(m), Some(rect)) = (map.as_ref(), rect) else { return }; let mut state = map_box(m, rect); + let drawn = state; if m.rotation.abs() < 0.01 && let (Some(doc), Some((w, h))) = (flat.doc.as_ref(), flat.art) { @@ -432,8 +440,7 @@ fn flat_view(ui: &mut Ui, fields: &mut DialogFields, flat: &Flat) -> Response { .reference_point(false) .rotate_zone(RotateZone::border(18.0)) .show_at(ui, body.rect); - let moved = map_of_box(&state, rect, m); - if moved != *m { + if let Some(moved) = map_after_edit(&state, &drawn, rect, m) { edited = Some(moved); } }); @@ -585,4 +592,26 @@ mod tests { let turned = map(190.0); assert_eq!(map_of_box(&map_box(&turned, rect), rect, &turned).rotation, -170.0, "a turn wraps to ±180"); } + + #[test] + fn map_offsets_keep_the_points_a_document_unit_converts_to() { + // 10 mm, as the X and Y rows hand it over in points. + let ten_mm = 10.0 * 72.0 / 25.4; + let mut fields = DialogFields::new(); + store_map(&mut fields, 1, Some(&map(0.0))); + assert_eq!(set_map_value(&mut fields, "mapX", json!(ten_mm)), Ok(())); + assert_eq!(set_map_value(&mut fields, "mapY", json!(-ten_mm)), Ok(())); + let stored = maps_of(&fields).into_iter().find(|m| m.surface == 1).map(|m| (m.x, m.y)); + assert_eq!(stored, Some((ten_mm, -ten_mm)), "the typed offset is stored unrounded"); + assert_eq!(set_map_value(&mut fields, "mapX", json!(GRAPHIC_MAX_OFFSET * 2.0)), Ok(())); + assert_eq!(maps_of(&fields).first().map(|m| m.x), Some(GRAPHIC_MAX_OFFSET), "the offset still keeps to its bounds"); + + // A frame without a box edit leaves those numbers as they are. + let rect = art_rect((20.0, 10.0)); + let typed = SurfaceMap { x: ten_mm, y: -ten_mm, ..map(0.0) }; + let drawn = map_box(&typed, rect); + assert_eq!(map_after_edit(&drawn, &drawn, rect, &typed), None); + let dragged = drawn.moved(Vec2::new(1.0, 0.0)); + assert!(map_after_edit(&dragged, &drawn, rect, &typed).is_some(), "a drag still edits the map"); + } } From a3b93d585b3458c9296776a32fe6924c748ec3f7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 15:57:37 -0500 Subject: [PATCH 18/22] ci(sonarcloud): give each main commit its own concurrency group (#10126) --- .github/workflows/sonarcloud.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 4cd4eb6387..dde1f6f5a8 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -11,7 +11,7 @@ permissions: contents: read concurrency: - group: sonarcloud-${{ github.ref }} + group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }} # A push to main is the run that publishes coverage; superseded runs there would never finish. cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} From aaa54f13070fd752b2337b2e417fc61d0be18436 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:03:07 -0800 Subject: [PATCH 19/22] Performance: an edit skips unchanged objects without reading them After every edit, the pixel grid, color mask, Objects on Path, Shaper and symbol instance passes, and the inline graphics refresh, pair each object with its counterpart from before the edit. Each pass read both objects to compare their ids before it found that they were the same node, so moving one object in a layer of 20,000 objects read all of them in four passes. The color mask pass is new since v0.24.1, and object.move became slower than in that release. The new vectorcraft_doc::changed_nodes does the pairing for all six. An object that is the same node at the same position is skipped by a pointer comparison; only changed and new objects are looked up by id. object.move of one rectangle in a document of 20,000 objects, release build, median CPU time of 2,000 moves: main 1.25 ms, this change 1.08 ms, v0.24.1 1.06 ms. The passes' share of the move went from about 30% to 5% in a profile. --- crates/doc/src/inline.rs | 10 +------ crates/doc/src/lib.rs | 1 + crates/doc/src/node.rs | 4 +++ crates/doc/src/node/changed.rs | 33 +++++++++++++++++++++ crates/doc/src/node/tests.rs | 34 ++++++++++++++++++++++ crates/engine/src/cmd/addons/image/mask.rs | 11 ++----- crates/engine/src/cmd/object/pixelgrid.rs | 22 ++------------ crates/engine/src/cmd/objects_on_path.rs | 14 ++------- crates/engine/src/cmd/shaper.rs | 17 ++--------- 9 files changed, 84 insertions(+), 62 deletions(-) create mode 100644 crates/doc/src/node/changed.rs diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index b22f6cbfc7..731fba6d34 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -308,16 +308,8 @@ fn resolve_kids( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec, ) -> Vec<(usize, Arc)> { - let mut by_id: Option>> = None; let mut out = vec![]; - for (i, c) in kids.iter().enumerate() { - let o = old.and_then(|old| match old.get(i) { - Some(b) if b.id == c.id => Some(b), - _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), - }); - if o.is_some_and(|o| Arc::ptr_eq(o, c)) { - continue; - } + for (i, c, o) in crate::changed_nodes(old.unwrap_or_default(), kids) { let mut c = c.clone(); if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { out.push((i, c)); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 470b0a94c4..6a331c6b77 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -116,6 +116,7 @@ pub use live_paint::{GapOptions, GapSize}; pub use metadata::{CopyrightStatus, DocMetadata}; pub use node::Knockout; pub use node::Scaling; +pub use node::changed_nodes; pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask}; pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; pub use orient::OrientedBox; diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 87b9a375db..3a4b2abd03 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -15,6 +15,7 @@ use crate::symbols::{SYMBOL_SQUARE, SymbolBoxes}; use crate::text::TextObject; mod attributes; +mod changed; mod clip; mod extras; mod ids; @@ -25,6 +26,9 @@ mod ops; mod wire; pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS}; +#[cfg(test)] +pub(crate) use changed::COUNTERPART_LOOKUPS; +pub use changed::changed_nodes; pub use clip::{ClipPaint, Uniter}; pub use extras::{Extras, ExtrasMut, NodeExtras}; pub use ids::{LAYER_COLORS, LayerColor, NodeId}; diff --git a/crates/doc/src/node/changed.rs b/crates/doc/src/node/changed.rs new file mode 100644 index 0000000000..4aba12f78e --- /dev/null +++ b/crates/doc/src/node/changed.rs @@ -0,0 +1,33 @@ +use std::collections::HashMap; + +use super::{Arc, Node, NodeId}; + +#[cfg(test)] +thread_local! { + /// Tests: how many nodes [`changed_nodes`] looked up a counterpart for on this thread. + pub(crate) static COUNTERPART_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The nodes of `after` that are not the same nodes as their counterparts in `before` (the same +/// list before an edit), with their positions in `after`. A node's counterpart is the node at the +/// same position when it has the same id, else the node in `before` with its id, else `None` (the +/// node is new). A node that is the same node as the one at its position in `before` is skipped +/// without reading it, so a list of many unchanged nodes costs one pointer comparison per node. +pub fn changed_nodes<'a>(before: &'a [Arc], after: &'a [Arc]) -> impl Iterator, Option<&'a Arc>)> { + let mut by_id: Option>> = None; + after.iter().enumerate().filter_map(move |(i, a)| { + if before.get(i).is_some_and(|b| Arc::ptr_eq(b, a)) { + return None; + } + #[cfg(test)] + COUNTERPART_LOOKUPS.with(|c| c.set(c.get() + 1)); + let b = match before.get(i) { + Some(b) if b.id == a.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), + }; + if b.is_some_and(|b| Arc::ptr_eq(b, a)) { + return None; + } + Some((i, a, b)) + }) +} diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 8d6520265a..ed2fdb08d9 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -947,3 +947,37 @@ fn try_walk_ends_at_the_break() { assert_eq!(flow, ControlFlow::Break(NodeId(3))); assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]); } + +/// After an edit of one node in a list of 1,000, `changed_nodes` gives that node and a new one +/// with their counterparts, and looks a counterpart up for those two only: the 999 nodes that are +/// the same nodes in the same places are passed over by their pointers. +#[test] +fn changed_nodes_looks_up_only_the_nodes_that_changed() { + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let before: Vec> = (0..1000).map(leaf).collect(); + let mut after = before.clone(); + let mut edited = (*after[500]).clone(); + edited.name = Some("edited".into()); + after[500] = Arc::new(edited); + after.push(leaf(5000)); + COUNTERPART_LOOKUPS.with(|c| c.set(0)); + let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect(); + assert_eq!(changed, [(500, NodeId(500), Some(NodeId(500))), (1000, NodeId(5000), None)]); + assert_eq!(COUNTERPART_LOOKUPS.with(|c| c.get()), 2); +} + +/// A node that moved to another place in the list is paired with itself by its id and left out +/// when it is the same node; a changed node that moved is paired with its old node, and a node +/// that is gone from the list gives nothing. +#[test] +fn changed_nodes_pairs_moved_nodes_by_id() { + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let before = vec![leaf(1), leaf(2), leaf(3), leaf(4)]; + let mut edited = (*before[0]).clone(); + edited.locked = true; + let after = vec![Arc::clone(&before[2]), Arc::clone(&before[1]), Arc::new(edited)]; + let changed: Vec<_> = changed_nodes(&before, &after).map(|(i, a, b)| (i, a.id, b.map(|b| b.id))).collect(); + assert_eq!(changed, [(2, NodeId(1), Some(NodeId(1)))]); + assert!(changed_nodes(&[], &after).map(|(_, _, b)| b).all(|b| b.is_none()), "every node is new against an empty list"); + assert_eq!(changed_nodes(&[], &after).count(), 3); +} diff --git a/crates/engine/src/cmd/addons/image/mask.rs b/crates/engine/src/cmd/addons/image/mask.rs index 7fdb0c5c3e..a46818befb 100644 --- a/crates/engine/src/cmd/addons/image/mask.rs +++ b/crates/engine/src/cmd/addons/image/mask.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch}; -use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::Affine; use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process}; @@ -367,14 +367,7 @@ fn stale_in(doc: &Document, n: &Arc, old: Option<&Arc>) -> bool { } let Some(children) = n.children() else { return false }; let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice); - let mut by_id: Option>> = None; - children.iter().enumerate().any(|(i, c)| { - let b = match before.get(i) { - Some(b) if b.id == c.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), - }; - stale_in(doc, c, b) - }) + changed_nodes(before, children).any(|(_, c, b)| stale_in(doc, c, b)) } /// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 81909da76f..7bef1cbc69 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; -use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign}; +use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign, changed_nodes}; use super::{ Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json, @@ -226,15 +226,7 @@ fn refresh_symbols(before: &Document, doc: &mut Document) { /// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity /// mask art holds such instances (`masked`). fn changed_instances(before: &[Arc], after: &[Arc], natural: &HashMap, ids: &mut Vec, masked: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) { masked.push(a.id); } @@ -423,15 +415,7 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { /// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the /// walk stops: [`keep_pixel_aligned`] visits what it holds. fn changed_aligned(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) { out.push(a.id); } else if let Some(children) = a.children() { diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs index 7dc8aec1c9..299ed5f49c 100644 --- a/crates/engine/src/cmd/objects_on_path.rs +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -25,12 +25,12 @@ //! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and //! the objects that move up the path after it; Expand). -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::objects_on_path::{CENTER, Held, ObjectsOnPath, attachable_path, held, is_objects_on_path, place}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::Rect; use super::edit::{roots_of, selected_roots}; @@ -499,15 +499,7 @@ fn place_in(doc: &mut Document, id: NodeId) -> bool { /// The Objects on Path groups among `after` and inside them that are not the same nodes as before /// (`before`: the same list before the edit), outer ones first. fn changed_groups(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if is_objects_on_path(a) { out.push(a.id); } diff --git a/crates/engine/src/cmd/shaper.rs b/crates/engine/src/cmd/shaper.rs index 228251fa13..93e479033f 100644 --- a/crates/engine/src/cmd/shaper.rs +++ b/crates/engine/src/cmd/shaper.rs @@ -6,12 +6,9 @@ use super::{ CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, number_or, object_param, point_param, }; use serde_json::{Value, json}; -use std::{ - collections::{BTreeMap, HashMap}, - sync::Arc, -}; +use std::{collections::BTreeMap, sync::Arc}; use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind, changed_nodes}; use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _}; use vectorcraft_pathops as po; use vectorcraft_tools::builder::{self as b, BuilderMap}; @@ -392,15 +389,7 @@ fn generated(d: &mut Document, src: &[Arc], spec: &ShaperSpec, map: &Build } fn changed_shaper_groups(before: &[Arc], after: &[Arc], out: &mut Vec) { - let mut by_id: Option>> = None; - for (i, a) in after.iter().enumerate() { - let b = match before.get(i) { - Some(b) if b.id == a.id => Some(b), - _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), - }; - if b.is_some_and(|b| Arc::ptr_eq(b, a)) { - continue; - } + for (_, a, b) in changed_nodes(before, after) { if a.extras().shaper.is_some() { out.push(a.id); } From 867a6788e467a5b3fd5d09f7a5431d8c91ec05e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:03:38 -0800 Subject: [PATCH 20/22] Tests: a held stored load waits for the test instead of a yield count HeldLoad in the plug-in tests held a stored module's load for at most 1,000,000 yield_now calls and then let it go on its own. On a busy test host that limit passed before the test released it, so the held file loaded early: a_grant_given_elsewhere_since_the_load_removed_one_is_kept and a_stored_module_without_permissions_ends_its_grant_when_it_installs failed in a full engine run and passed alone. - The hook now waits on a condition variable that release() and the drop set. A load that runs on the test's own thread is not held and sets gave_up, so a load that is no longer in the background still fails the test instead of hanging it. - stored_plugins_load_without_holding_the_plugin_changes_lock waited at most 100,000 yields for the plug-in changes lock to be free; it now waits until it is free. - canceled_loads_forget_the_grants_of_what_they_installed releases the held load before canceling, since cancel waits for a running load up to its 10 second deadline. - a_query_runs_while_the_plugins_load checks which commands wait for the loads before it runs document.info. --- crates/engine/src/tests/plugins.rs | 48 +++++++++++++++++------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 6cd51a5a1d..4ecff31b3b 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2347,29 +2347,35 @@ static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(()); struct HeldLoad { _lock: std::sync::MutexGuard<'static, ()>, entered: std::sync::Arc, - go: std::sync::Arc, + go: std::sync::Arc<(std::sync::Mutex, std::sync::Condvar)>, gave_up: std::sync::Arc, } impl HeldLoad { - /// Holds the load of the file at `path`. A load the test never lets go gives up after a - /// million yields (so a test of code that waits for it ends) and says so in `gave_up`. + /// Holds the load of the file at `path` until [`HeldLoad::release`] or the drop. A load that + /// runs on the thread that made this one is not held, since nothing could let it go: it goes + /// ahead at once and says so in `gave_up`. fn new(path: std::path::PathBuf) -> HeldLoad { - use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Condvar, Mutex}; let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()); - let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false))); + let (entered, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false))); + let go = Arc::new((Mutex::new(false), Condvar::new())); let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone()); + let test_thread = std::thread::current().id(); *crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| { if p != path { return; } e.store(true, Ordering::SeqCst); - if !(0..1_000_000).any(|_| { - std::thread::yield_now(); - g.load(Ordering::SeqCst) - }) { + if std::thread::current().id() == test_thread { q.store(true, Ordering::SeqCst); + return; + } + let (open, opened) = &*g; + let mut open = open.lock().unwrap_or_else(|e| e.into_inner()); + while !*open { + open = opened.wait(open).unwrap_or_else(|e| e.into_inner()); } })); HeldLoad { _lock: lock, entered, go, gave_up } @@ -2380,7 +2386,9 @@ impl HeldLoad { } fn release(&self) { - self.go.store(true, std::sync::atomic::Ordering::SeqCst); + let (open, opened) = &*self.go; + *open.lock().unwrap_or_else(|e| e.into_inner()) = true; + opened.notify_all(); } fn gave_up(&self) -> bool { @@ -2904,6 +2912,7 @@ fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() { #[test] fn a_query_runs_while_the_plugins_load() { let id = "test.engine.background.query"; + assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info")); let (folder, path) = store_with("plugin-background-query", id); let held = HeldLoad::new(path); let mut s = session(); @@ -2917,7 +2926,6 @@ fn a_query_runs_while_the_plugins_load() { let waited = held.gave_up() || !s.plugins_loading(); held.release(); assert!(!waited, "document.info waited for the plug-ins to load"); - assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info")); s.finish_plugin_loads(); assert!(vectorcraft_plugins::registry::remove(id)); } @@ -2935,18 +2943,14 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() { while !held.entered() && !held.gave_up() { std::thread::yield_now(); } - // Other tests take the lock for a moment; the load holding it would hold it throughout (a - // tenth of the yields the held load waits before it gives up). - let free = (0..100_000).any(|_| { + // A load run on this thread isn't held, so a free lock then shows nothing. + assert!(!held.gave_up(), "the module loaded on the test's thread"); + // Other tests take the lock for a moment; the held load holding it would hold it until it is let go. + while !crate::cmd::plugin::plugin_changes_free() { std::thread::yield_now(); - crate::cmd::plugin::plugin_changes_free() - }); - // A load that gave up waiting no longer holds anything, so a free lock then shows nothing. - let gave_up = held.gave_up(); + } held.release(); s.finish_plugin_loads(); - assert!(!gave_up, "the held load gave up before the lock was looked at"); - assert!(free, "the lock was held while the module loaded"); assert!(vectorcraft_plugins::registry::remove(id)); } @@ -2974,6 +2978,10 @@ fn canceled_loads_forget_the_grants_of_what_they_installed() { std::thread::yield_now(); } assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads"); + assert!(s.plugins_loading(), "the second module is still loading"); + // Canceling waits for a running load until its deadline; the second module, let go, loads + // while the cancel runs or before it, and doesn't install either way. + held.release(); s.cancel_plugin_loads(); // The file goes once it holds no grant. let listed: Vec = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default(); From 2960e55b6c38ff109e56ce1879a142a4ee929294 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:40:43 -0800 Subject: [PATCH 21/22] Match Objects: a stacking match keeps clipping paths and settles Intertwine groups Merging main made DIALOGS one entry short: Offset Objects and Match Objects both joined it, so vectorcraft-ui-egui did not compile. The table now declares seven entries. A stacking match moved a clipping path out of its clip position and could move a member out of an Intertwine group with its old overlap tiers. It now refuses to move a clipping path, refuses a destination that would nest Intertwine art, and clears the tiers of members that leave their group. A stacking or rotate-only match no longer needs bounds on the source. A size match measures each target after it is sized and turned, in its final frame, and is refused when a target can't take the requested size, instead of reporting success with the size unchanged. A target with no bounds that needs to turn is refused. --- crates/engine/src/cmd/addons/arrange.rs | 74 ++++++-- crates/engine/src/cmd/addons/arrange/tests.rs | 173 +++++++++++++++++- crates/ui-egui/src/addons/arrange.rs | 2 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 5 files changed, 238 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 6ded16116a..136ec7ffbf 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target turns, clockwise or counter-clockwise, to the source's bounding-box angle), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target turns, clockwise or counter-clockwise, to the source's bounding-box angle), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -418,8 +418,13 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { if targets.is_empty() { return Err(bad(C, "select at least two objects")); } - let sb = box_of(s, source)?; - let (w, h) = (sb.rect.width(), sb.rect.height()); + // Only sizing measures the source; a stacking or rotate match doesn't need its bounds. + let (w, h) = if size == "none" { + (0.0, 0.0) + } else { + let sb = box_of(s, source)?; + (sb.rect.width(), sb.rect.height()) + }; let wanted = match size { "width" if w < LEAST => return Err(bad(C, "the source object has no width")), "height" if h < LEAST => return Err(bad(C, "the source object has no height")), @@ -432,7 +437,16 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let angle = s.doc()?.doc.bbox_angle(&[source]); let mut xfs = Vec::with_capacity(targets.len()); for &id in &targets { - let Some(b) = s.transform_box(&[id]) else { continue }; + let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 }; + let Some(b) = s.transform_box(&[id]) else { + if wanted.is_some() { + return Err(bad(C, format!("object {} has no bounds to size", id.0))); + } + if turn.abs() > 1e-9 { + return Err(bad(C, format!("object {} has no bounds to rotate", id.0))); + } + continue; + }; let mut xf = Affine::IDENTITY; if let Some(q) = &wanted { let mut q = q.clone(); @@ -440,13 +454,33 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { q["strokes"] = json!(strokes); xf = object_bounds_transform(s, &q, id)?; } - if rotate { - // Turned about the reference point, which the sizing keeps in place; angles are - // counter-clockwise and y is down. - let turn = vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])); - if turn.abs() > 1e-9 { - let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); - xf = Affine::rotate_about(-turn.to_radians(), at) * xf; + if turn.abs() > 1e-9 { + // Rotation uses the reference point that sizing keeps in place. + let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + xf = Affine::rotate_about(-turn.to_radians(), at) * xf; + } + if wanted.is_some() { + let sc = scaling(s, &json!({ "strokes": strokes })); + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let measure = |xf| { + d.node(id).and_then(|n| { + let mut n = n.clone(); + transform_node(&mut n, xf, sc, true); + let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO }; + effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure()) + }) + }; + let misses = |measured: Option| { + measured.is_none_or(|r| match size { + "width" => (r.width() - w).abs() > 1e-6, + "height" => (r.height() - h).abs() > 1e-6, + _ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6, + }) + }; + // The sized and turned object, measured in its final frame, must have the size asked for. + if misses(measure(xf)) { + return Err(bad(C, format!("object {} can't take the requested size", id.0))); } } xfs.push((id, xf)); @@ -454,6 +488,22 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9); xfs.retain(|(_, xf)| !still(xf)); let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets); + let (mut placed, mut left) = (vec![], vec![]); + if restack { + let d = &s.doc()?.doc; + // In a clip group or a clipping layer the bottom child is the clipping path: it stays there. + let is_clip = + |id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips); + if targets.iter().any(is_clip) { + return Err(bad(C, "a clipping path can't change its place in the stacking order")); + } + let parent = d.parent_of(source); + if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) { + return Err(bad(C, format!("{what} can't be intertwined"))); + } + placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::)>>(); + left = crate::cmd::intertwine::groups_of(d, &targets); + } let count = json!({ "source": source.0, "count": targets.len() }); if xfs.is_empty() && !restack { return Ok(count); @@ -471,6 +521,8 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { if restack { let moved = d.remove_many(&targets)?; d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?; + // Targets moved out of an Intertwine group leave it as ordinary art. + crate::cmd::intertwine::settle_members(d, &placed, &left)?; } Ok(()) })?; diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index ea5d4aca06..265ab50a6a 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -424,6 +424,65 @@ fn match_turns_the_others_to_the_sources_angle() { assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6); } +#[test] +fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() { + for size in ["width", "height", "both"] { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + select(&mut s, &[target]); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5); + select(&mut s, &[source]); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let wanted = s.transform_box(&[source]).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap(); + assert_eq!(r, json!({"source": source.0, "count": 1})); + let measured = s.transform_box(&[target]).unwrap(); + assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}"); + assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}"); + assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}"); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } +} + +#[test] +fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() { + for angle in [0, 30] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[a]); + s.execute("edit.clear", &json!({})).unwrap(); + let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.rotate", &json!({"angle": angle})).unwrap(); + select(&mut s, &[b]); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.transform_box(&[target]).is_none()); + assert!(s.transform_box(&[source]).is_none()); + assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let result = s.execute("addon.arrange.match", &json!({"rotate": true})); + if angle == 0 { + assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1})); + } else { + let error = result.unwrap_err().to_string(); + assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); + } +} + #[test] fn match_puts_the_others_directly_above_the_source() { let mut s = session(); @@ -514,10 +573,122 @@ fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) { s.execute("edit.undo", &json!({})).unwrap(); s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap(); select(&mut s, &[a, b]); - s.execute(&id, &q).unwrap(); + s.replay(&id, &q).unwrap(); assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s)); } +#[test] +fn match_stacking_leaves_a_clipping_path_in_place() { + let mut s = session(); + let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0); + select(&mut s, &[art, mask]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + select(&mut s, &[mask, x]); + s.execute("select.key", &json!({"id": x.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]); +} + +#[test] +fn match_size_refuses_a_target_with_no_width() { + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[line, b]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]); + // Its height can still take the source's. + s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap(); + assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line)); +} + +#[test] +fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[line]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap(); + let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0); + select(&mut s, &[b]); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + select(&mut s, &[line, b]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap(); + let measured = s.transform_box(&[line]).unwrap().rect; + let wanted = s.transform_box(&[b]).unwrap().rect; + assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}"); + assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}"); + select(&mut s, &[b]); + s.execute("object.setBounds", &json!({"width": 4})).unwrap(); + select(&mut s, &[line, b]); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]); +} + +#[test] +fn match_stacking_takes_a_member_out_of_its_intertwine_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0); + select(&mut s, &[a, b]); + let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap"); + let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, c]); + s.execute("select.key", &json!({"id": c.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group"); + let e = d.node(a).unwrap().extras(); + assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group"); +} + +#[test] +fn match_stacking_needs_no_bounds_on_the_source() { + let mut s = session(); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + select(&mut s, &[b, g]); + s.execute("select.key", &json!({"id": g.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group"); +} + +#[test] +fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0); + let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0); + select(&mut s, &[source, b]); + let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[a]); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(s.transform_box(&[source]).is_none()); + assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent)); + let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0); + select(&mut s, &[c, d]); + let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string(); + assert!(error.contains("can't be intertwined"), "{error}"); + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); +} + #[test] fn match_replays_with_the_stroke_scaling_it_ran_with() { replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 3c8483000d..a05d713244 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -30,7 +30,7 @@ const MATCH: &str = "addon.arrange.match"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 6] = [ +const DIALOGS: [(&str, &str); 7] = [ (GRID, "Arrange in Grid"), (OFFSET, "Offset Objects"), (REPLACE, "Replace with Top Object"), diff --git a/docs/mcp.md b/docs/mcp.md index 42bd2ef607..a9e9d9649a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17581,7 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source does not have, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bde309e3c9..395fdda4de 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3148,7 +3148,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` ## Arrange Tools add-on: Match Objects (2026-11-29) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had. Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (a clipping path keeps its place, so such a match is refused). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) From 4f95a30c987126e25cdba53122228708a29f25c9 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Sun, 29 Nov 2026 18:22:52 -0800 Subject: [PATCH 22/22] Images: a selected image's color mode is read from its file header (#10167) --- crates/engine/src/cmd/place.rs | 24 ++++++++++---- crates/engine/src/tests/place.rs | 56 ++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 58612c744c..ba2b523f62 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -1231,12 +1231,24 @@ fn queue(s: &mut Session, p: &Value) -> Result { // ---------- queries ---------- -/// The colour mode an image file stores its pixels in. -fn color_mode(bytes: &[u8]) -> &'static str { - match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) { - Some(craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA) => "Grayscale", - Some(craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA) => "CMYK", - _ => "RGB", +/// The colour mode an image file stores its pixels in. A PNG, JPEG, TIFF, PSD, GIF or BMP file's +/// header says it and a WebP file is always RGB, so their pixels are not decoded; the Control bar +/// and the Properties panel ask `image.info` again after every change, each step of a drag +/// included. A file in another format is decoded. +pub(crate) fn color_mode(bytes: &[u8]) -> &'static str { + use craft_image_codecs::{ChannelLayout as L, RasterColorType as T}; + match craft_image_codecs::inspect_raster(bytes) { + Ok(Some(i)) => match i.color_type { + T::Bitmap | T::Gray | T::GrayAlpha => "Grayscale", + T::Cmyk | T::CmykAlpha => "CMYK", + _ => "RGB", + }, + _ if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::WebP) => "RGB", + _ => match craft_image_codecs::decode(bytes).ok().map(|img| img.layout()) { + Some(L::Gray | L::GrayA) => "Grayscale", + Some(L::Cmyk | L::CmykA) => "CMYK", + _ => "RGB", + }, } } diff --git a/crates/engine/src/tests/place.rs b/crates/engine/src/tests/place.rs index 94da32aa01..c38dd53452 100644 --- a/crates/engine/src/tests/place.rs +++ b/crates/engine/src/tests/place.rs @@ -247,6 +247,62 @@ fn replace_keeps_the_transform_and_the_stacking_place() { assert_eq!(top_children(&s)[0].id.0, first.as_u64().unwrap(), "one undo step brings the old image back"); } +/// `image.info` reads a PNG's colour mode from its header without decoding its pixels: a grayscale +/// PNG whose compressed pixel data is unreadable still says Grayscale. The Control bar asks again +/// after every step of a drag, so a decode there redid a large image's whole decode each step. +#[test] +fn image_color_mode_reads_the_header_without_decoding_the_pixels() { + let raw: Vec = (0..64u32 * 64).map(|i| (i * 7 % 251) as u8).collect(); + let gray = craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap(); + let mut png = craft_image_codecs::encode(&gray, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + assert_eq!(cmd::place::color_mode(&png), "Grayscale"); + // Each IDAT chunk's data zeroed (an invalid zlib stream) under a correct CRC. + let mut at = 8; + let mut idat = 0; + while at + 12 <= png.len() { + let len = u32::from_be_bytes(png[at..at + 4].try_into().unwrap()) as usize; + if &png[at + 4..at + 8] == b"IDAT" { + png[at + 8..at + 8 + len].fill(0); + let crc = crc32fast::hash(&png[at + 4..at + 8 + len]); + png[at + 8 + len..at + 12 + len].copy_from_slice(&crc.to_be_bytes()); + idat += 1; + } + at += 12 + len; + } + assert!(idat > 0, "the PNG has pixel data"); + assert!(craft_image_codecs::decode(&png).is_err(), "the pixels no longer decode"); + assert_eq!(cmd::place::color_mode(&png), "Grayscale", "the header alone gives the colour mode"); +} + +/// The colour mode read from a file's header is the one its decoded pixels have, in every format +/// and channel layout the codecs write. +#[test] +fn image_color_mode_from_the_header_matches_the_decoded_pixels() { + use craft_image_codecs::{ChannelLayout as L, Format as F}; + let decoded = |bytes: &[u8]| match craft_image_codecs::decode(bytes).map(|i| i.layout()) { + Ok(L::Gray | L::GrayA) => "Grayscale", + Ok(L::Cmyk | L::CmykA) => "CMYK", + Ok(_) => "RGB", + Err(e) => panic!("the written file decodes: {e}"), + }; + let mut seen = std::collections::BTreeSet::new(); + let mut checked = 0; + for format in [F::Png, F::Jpeg, F::Tiff, F::Gif, F::Bmp, F::WebP] { + for layout in [L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk] { + let n = 16 * 16 * layout.channels(); + let raw: Vec = (0..n).map(|i| (i * 13 % 256) as u8).collect(); + let img = craft_image_codecs::Image::from_raw(16, 16, layout, craft_image_codecs::SampleType::U8, raw).unwrap(); + let Ok(bytes) = craft_image_codecs::encode(&img, format, &craft_image_codecs::EncodeOptions::default()) else { continue }; + let want = decoded(&bytes); + assert_eq!(cmd::place::color_mode(&bytes), want, "{format:?} written from {layout:?}"); + seen.insert(want); + checked += 1; + } + } + assert!(checked >= 12, "{checked} files written"); + assert_eq!(seen.into_iter().collect::>(), ["CMYK", "Grayscale", "RGB"]); +} + #[test] fn replace_needs_exactly_one_selected_object() { let mut s = session();