diff --git a/ROADMAP.md b/ROADMAP.md index 6d322dba24..84e40bc444 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -183,6 +183,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. +- 2026-12-01: Common Tangents and Smooth Bridge are one dialog, Common Tangents… (#10465): Connect tangents joins the two tangents of each kind into one closed shape, and with External, Straight or Curved picks between the tangent lines and Smooth Bridge's curved outline, with Radius, Constant Gap, Reach and Keep Originals; the Smooth Bridge… menu item is gone, and `addon.pathtools.bridge` still runs and opens the dialog with External and Curved (`connect` and `curved` on `addon.pathtools.commonTangents`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 4b660854f6..118a78006c 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -553,10 +553,9 @@ fn the_saved_engine_preference_is_found() { let saved = prefs.to_json(); assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power); } - // Every choice Preferences offer means something here. - for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES { - assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}"); - } + // Preferences offer the three choices read above, and no other. + let offered: Vec<&str> = vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES.iter().map(|(value, _)| *value).collect(); + assert_eq!(offered, ["automatic", "lowPower", "highPerformance"]); } #[test] diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 01821a08f1..7abfb33a4e 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2220,7 +2220,10 @@ fn brushes_without_modes_vary_randomly_as_before() { serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"]) ); - assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id())); + let ids: Vec<&str> = Variation::ALL.iter().map(|v| v.id()).collect(); + assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(ids), "saved names are the ids"); + assert_eq!(Variation::parse("stylusWheel"), Some(Variation::StylusWheel)); + assert_eq!(Variation::parse("wheel"), None); assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel)); } @@ -2228,6 +2231,7 @@ fn brushes_without_modes_vary_randomly_as_before() { #[test] fn junk_pressure_brushes_draw_finite_art() { let bp = preview_path(120.0, 24.0); + let mut drawn = 0; for (size, var) in [(1e308, 1e308), (-1e308, 1e308), (0.0, -1e308), (f64::MAX, f64::MAX)] { for profile in [vec![], vec![(0.0, 2.0), (0.0, -1.0), (5.0, 0.5)], vec![(1.0, 1.0), (0.0, 0.0)]] { let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(size, var), &bp, &pressed(profile)); @@ -2236,8 +2240,10 @@ fn junk_pressure_brushes_draw_finite_art() { all_points(n, &mut pts); } assert!(pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{size} {var}"); + drawn += usize::from(!pts.is_empty()); } } + assert_eq!(drawn, 12, "brushes that draw"); } /// A scatter brush of 10 × 4 pt rectangles whose size goes from `lo` % to `hi` % as `mode` says. diff --git a/crates/cad/src/hpgl/tests.rs b/crates/cad/src/hpgl/tests.rs index 9a350707a6..fdc31cb6cf 100644 --- a/crates/cad/src/hpgl/tests.rs +++ b/crates/cad/src/hpgl/tests.rs @@ -131,7 +131,7 @@ fn pens_pick_colors_and_widths() { let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;"); let widths: Vec = leaves(&i.document).iter().map(|n| stroke(n).width).collect(); let want = [MM, 2.0 * MM, MM, 0.35 * MM]; - assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); + assert!(widths.len() == want.len() && widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}"); } #[test] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 6140395323..16f4f97082 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1448,7 +1448,8 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() { let art = path(&mut d, shapes::rectangle(Rect::new(100.0, 50.0, 140.0, 90.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Far".into(), art: Arc::new(art) }); let o = DxfOptions { crop: true, ..opts(&d) }; - assert!(!kinds(&export(&d, &o).unwrap()).is_empty()); + // The red fill: its outline and its hatch. + assert_eq!(kinds(&export(&d, &o).unwrap()), ["LWPOLYLINE", "HATCH"]); } /// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it. diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 5982e37552..0f520b2f9d 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -464,9 +464,10 @@ impl Gradient { self.repeats.clamp(1, MAX_REPEATS) } /// Does it paint something other than its end colors past the ends of its stops, or run its - /// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects? + /// stops more than once: a linear, radial, conic or diamond gradient with stops that repeats or + /// reflects? One without stops paints as one that pads. pub fn is_spread(&self) -> bool { - !self.spread.is_pad() && self.kind != GradientKind::Freeform + !self.spread.is_pad() && self.kind != GradientKind::Freeform && !self.stops.is_empty() } /// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever /// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal diff --git a/crates/color/src/gradient/spread/tests.rs b/crates/color/src/gradient/spread/tests.rs index ab088293da..c42b1acd61 100644 --- a/crates/color/src/gradient/spread/tests.rs +++ b/crates/color/src/gradient/spread/tests.rs @@ -36,6 +36,10 @@ fn spread_maps_the_parameter_to_a_place_along_the_stops() { let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3); assert_eq!(free.spread_param(0.7), 0.7); assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread()); + // Without stops it paints as one that pads. + let empty = Gradient { stops: vec![], ..repeat.clone() }; + assert!(!empty.is_spread()); + assert_eq!(empty.painted_spread(), (GradientSpread::Pad, 1)); assert!(repeat.spread_param(f64::NAN).is_nan()); // A count out of range (set in code) counts as the nearest one in range. assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1); diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 2770471f70..7c40d9d133 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2784,10 +2784,13 @@ mod tests { Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() }))) }; let Paint::Gradient(m) = lerp_paint(&spot_gradient(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&tinted(0.2), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot") && (s.tint - 0.6).abs() < 1e-6), "{:?}", m.gradient.stops); let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &spot_gradient(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none()), "{:?}", m.gradient.stops); } @@ -2840,6 +2843,7 @@ mod tests { let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]); let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]); let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2848,6 +2852,7 @@ mod tests { // Without plates on either side the steps print the spot ink alone, as before. let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]); let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -2882,10 +2887,12 @@ mod tests { let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]); let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops); m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05])); // The ends keep their own plates. let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops); // Another swatch, or an unlinked stop: process steps with no plates, as before. @@ -2897,6 +2904,7 @@ mod tests { let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]); for b in [&other, &plain] { let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } } @@ -2906,11 +2914,14 @@ mod tests { let p = [0.4, 0.8, 0.0, 0.2]; let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]); let Paint::Gradient(g) = &gradient else { panic!() }; - assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none())); + let linked = solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient); + assert_eq!(linked.stops.len(), 2); + assert!(linked.stops.iter().all(|s| s.plates.is_none() && s.swatch.as_deref() == Some("Spot") && s.tint == 0.2), "{:?}", linked.stops); let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 }; // The solid's end has no plates: they grow from none toward the gradient's, both ways round. for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] { let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); for s in &m.gradient.stops { assert_eq!(s.swatch.as_deref(), Some("Spot")); assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint); @@ -2919,6 +2930,7 @@ mod tests { } // A process solid unlinks the steps, and they take no plates. let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() }; + assert_eq!(m.gradient.stops.len(), 2); assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops); } @@ -3401,7 +3413,8 @@ mod tests { #[test] fn odd_dash_blends_to_solid_with_closed_gaps() { let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); - assert!(d.pattern.iter().skip(1).step_by(2).all(|g| *g == 0.0), "{:?}", d.pattern); + // Doubled to dash, gap, dash, gap, dash, gap; each dash takes the gap after it. + assert_eq!(d.pattern, [5.0, 0.0, 6.0, 0.0, 7.0, 0.0]); } #[test] @@ -3412,7 +3425,8 @@ mod tests { let mid = lerp_node(&a, &b, 0.4); let mut ids = vec![]; mid.walk(&mut |n| ids.push(n.id)); - assert!(ids.iter().all(|i| *i == NodeId(0)), "{ids:?}"); + // The step and its two members, all of them new. + assert_eq!(ids, [NodeId(0); 3]); } /// A blend of `a` and `b` spaced by `spacing`. diff --git a/crates/doc/src/compound_shape.rs b/crates/doc/src/compound_shape.rs index 3b36ff86dd..f3f4b83939 100644 --- a/crates/doc/src/compound_shape.rs +++ b/crates/doc/src/compound_shape.rs @@ -64,11 +64,10 @@ mod tests { #[test] fn modes_read_back_and_unknown_ones_are_add() { - for m in ShapeMode::ALL { - let v = serde_json::to_value(m).unwrap(); - assert_eq!(v, serde_json::json!(m.name())); - assert_eq!(serde_json::from_value::(v).unwrap(), m); - } + assert_eq!(serde_json::to_value(ShapeMode::Subtract).unwrap(), serde_json::json!("subtract")); + assert_eq!(serde_json::from_value::(serde_json::json!("exclude")).unwrap(), ShapeMode::Exclude); + assert_eq!(ShapeMode::parse("intersect"), Some(ShapeMode::Intersect)); + assert_eq!(ShapeMode::parse("Intersect"), None); for v in [serde_json::json!("divide"), serde_json::json!(3), serde_json::json!(null), serde_json::json!({"a": [1]})] { assert_eq!(serde_json::from_value::(v).unwrap(), ShapeMode::Add); } diff --git a/crates/doc/src/depth.rs b/crates/doc/src/depth.rs index c846dfc1c6..3872e16a54 100644 --- a/crates/doc/src/depth.rs +++ b/crates/doc/src/depth.rs @@ -613,6 +613,7 @@ mod tests { d.limit_depth_noting(&mut warnings); assert_eq!(warnings, [symbols_note()]); assert!(!d.too_deep(None), "{count} {last}"); + assert_eq!(d.symbols.len(), count, "every symbol is kept"); assert!(d.symbols.iter().all(|s| s.art.children().is_some()), "the art is still a group"); } // An edit that makes one hold itself is seen, whatever else stayed as it was. diff --git a/crates/doc/src/symbol_overrides.rs b/crates/doc/src/symbol_overrides.rs index 241c61fba8..d9017815c7 100644 --- a/crates/doc/src/symbol_overrides.rs +++ b/crates/doc/src/symbol_overrides.rs @@ -253,6 +253,7 @@ mod tests { let mut a = Node::group(NodeId(1), vec![Arc::new(text)]); apply(&mut a, &[SymbolOverride { path: vec![0], stroke: Some(red.clone()), ..Default::default() }]); let Some(NodeKind::Text(t)) = part(&a, &[0]).map(|n| &n.kind) else { panic!("type") }; + assert_eq!(t.runs.len(), 1); assert!(t.runs.iter().all(|r| r.style.stroke == red && r.style.stroke_width == 1.0), "the stroke draws at 1 pt"); // A path whose stroke has neither paint nor weight gets 1 pt too. diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 9371947565..607fa12238 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -217,11 +217,10 @@ fn indic_digits_map_to_their_scripts_block() { assert_eq!(map(d, "a-Z ٪"), "a-Z ٪"); } assert_eq!(map(Digits::Devanagari, "page 12"), "page १२"); - for d in Digits::ALL { - assert_eq!(serde_json::to_value(d).unwrap(), d.id()); - assert_eq!(serde_json::from_value::(d.id().into()).unwrap(), d); - assert_eq!(Digits::from_id(d.id()), Some(d)); - } + assert_eq!(serde_json::to_value(Digits::Devanagari).unwrap(), "devanagari"); + assert_eq!(serde_json::from_value::("farsi".into()).unwrap(), Digits::Farsi); + assert_eq!(Digits::Malayalam.id(), "malayalam"); + assert_eq!(Digits::from_id("default"), Some(Digits::Default)); assert_eq!(Digits::from_id("roman"), None); assert!(serde_json::from_value::("roman".into()).is_err()); } diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index a2d17cc990..f462e18300 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -98,11 +98,10 @@ mod tests { #[test] fn ids_round_trip_and_unknown_views_show_the_result() { - for v in TraceView::ALL { - assert_eq!(TraceView::from_id(v.id()), Some(v)); - assert_eq!(TraceView::from_id(&v.id().to_ascii_uppercase()), Some(v)); - assert!(v.shows_result() || v.shows_outlines() || v.shows_source(), "{v:?} shows something"); - } + assert_eq!(TraceView::Source.id(), "sourceImage"); + assert_eq!(TraceView::from_id("outlinesWithSourceImage"), Some(TraceView::OutlinesWithSource)); + assert_eq!(TraceView::from_id("TRACINGRESULT"), Some(TraceView::Result), "case does not matter"); + assert_eq!(TraceView::from_id("tracing"), None); let mut g = Node::group(crate::NodeId(1), vec![]); assert_eq!(g.trace_view(), TraceView::Result); g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "outlines"}))); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8e8d96ea66..d2dc185222 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -1002,7 +1002,8 @@ pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). -pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; +pub const ALIASES: &[(&str, &str)] = + &[("object.convertDocumentColorMode", "file.documentColorMode"), ("addon.pathtools.bridge", "addon.pathtools.commonTangents")]; /// Is `id` an [`ALIASES`] entry? pub fn is_alias(id: &str) -> bool { diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 2f56079b18..6e02292917 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -32,15 +32,15 @@ pub(super) fn specs() -> Vec { vec![cmd!( "addon.pathtools.bridge", "Smooth Bridge", - ["Object", "Plug-ins", "Path Precision Tools"], + [], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. An object that is not a circle is an error that says why (an ellipse whose width and height differ, a compound path, a hidden or locked object, or another object). One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles (kept for older scripts: Common Tangents makes the same outline with `curved`, and the command palette leaves this command out)", has_selection, bridge )] } -fn bridge(s: &mut Session, p: &Value) -> Result { +pub(super) fn bridge(s: &mut Session, p: &Value) -> Result { let percent = given(p, "radius", Some(RADII), C)?; let gap = given(p, "gap", Some(GAPS), C)?; let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index e47c009062..372ceb6e12 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -31,7 +31,7 @@ pub(super) fn specs() -> Vec { "Common Tangents", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), connect?: bool (false: true joins the two tangents of each kind into one closed path, along the chords between where they touch each path; a kind with one tangent stays a line), curved?: bool (false: true joins the selected circles into one outline along concave arcs that touch both, as `addon.pathtools.bridge` does, in place of the external tangents; `tangents` other than \"external\", `centerline` and `connect: false` are then an error), radius?: % 1..1000 (100; with curved, as for `addon.pathtools.bridge`), gap?: pt 0..1000 (with curved, instead of radius), reach?: pt 0..10000 (10; with curved, for three or more circles), keepOriginals?: bool (false; with curved), ids?: [id, id] (default: the selection; with curved, two or more circles)} add the common tangent lines of two convex closed paths (with curved, join circles with a smooth bridge into metaball, aka meatball, shapes instead) as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is at most a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, at most the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}, or with curved `addon.pathtools.bridge`'s {ids, alone, id?}", has_selection, common_tangents )] @@ -71,9 +71,36 @@ fn refusal(e: pt::OutlineError) -> EngineError { ) } +/// The parameters that shape a curved bridge. +const CURVED_KEYS: [&str; 4] = ["radius", "gap", "reach", "keepOriginals"]; + fn common_tangents(s: &mut Session, p: &Value) -> Result { const C: &str = COMMON_TANGENTS; - let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null()); + let kinds = choice(p, C, "tangents", &KINDS)?; + let connect = if given("connect") { Some(switch_or(p, "connect", false, C)?) } else { None }; + if switch_or(p, "curved", false, C)? { + if kinds.is_some_and(|k| k != "external") { + return Err(bad(C, "`curved` joins the circles along their external tangents: give `tangents` \"external\" or leave it out")); + } + if given("centerline") { + return Err(bad(C, "`centerline` applies to the tangent lines: leave it out with `curved`")); + } + if connect == Some(false) { + return Err(bad(C, "a curved bridge is always connected: leave `connect` out or set it true")); + } + // The outline is Smooth Bridge's. + let mut bridged = serde_json::Map::new(); + for key in CURVED_KEYS.iter().chain(&["ids"]).filter(|k| given(k)) { + bridged.insert((*key).to_owned(), p[*key].clone()); + } + return super::bridge::bridge(s, &Value::Object(bridged)); + } + if let Some(key) = CURVED_KEYS.iter().find(|k| given(k)) { + return Err(bad(C, format!("`{key}` applies to a curved bridge: give `curved` with it"))); + } + let kinds = kinds.unwrap_or("all"); + let connect = connect.unwrap_or(false); let centerline = switch_or(p, "centerline", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; @@ -105,6 +132,33 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { _ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)), }; let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + // With `connect`, the two tangents of each kind and the chords between their ends on each path make one closed + // shape; a kind with one tangent (paths that touch) keeps it as a line. A point's lines are all one kind. + let shapes: Vec<(Vec, bool)> = if connect { + let mut out = vec![]; + for kind in [pt::TangentKind::External, pt::TangentKind::Internal] { + let of: Vec<&pt::Tangent> = kept.iter().copied().filter(|t| point || t.kind == kind).collect(); + match of.as_slice() { + [l, m] => { + // A point's two lines share the point, which then closes the ring once. + let same = |q: Point, p: Point| (q - p).hypot() <= 1e-9 * a.size().max(b.size()); + let mut ring = vec![l.from, l.to, m.to, m.from]; + ring.dedup_by(|q, p| same(*q, *p)); + if ring.len() > 2 && same(ring[0], ring[ring.len() - 1]) { + ring.pop(); + } + out.push((ring, true)); + } + _ => out.extend(of.iter().map(|t| (vec![t.from, t.to], false))), + } + if point { + break; + } + } + out + } else { + lines.iter().map(|&(from, to)| (vec![from, to], false)).collect() + }; if lines.is_empty() && point { // Written as `EngineError::Other` so that the i18n message scan finds it. let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into()); @@ -133,13 +187,14 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; let mut ids = vec![]; let mut center_id = None; - for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let center = center.map(|(from, to)| (vec![from, to], false)); + for (k, (points, closed)) in shapes.iter().cloned().chain(center).enumerate() { let id = d.alloc_id(); - let path = PathData::single(SubPath::polyline(&[from, to], false)); + let path = PathData::single(SubPath::polyline(&points, closed)); let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); look.apply(d, &mut n); d.insert(parent, idx + 1 + k, n)?; - if k == lines.len() { + if k == shapes.len() { center_id = Some(id); } ids.push(id); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 7ab6b32838..1653089520 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -354,3 +354,113 @@ fn bad_selections_and_params_are_refused() { let g = group_of(&mut s, &[b]); assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); } + +/// The one closed outline of path `id`. +fn outline(s: &Session, id: NodeId) -> vectorcraft_geom::SubPath { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + let [sp] = path.subpaths.as_slice() else { panic!("{} subpaths", path.subpaths.len()) }; + assert!(sp.closed); + sp.clone() +} + +/// The anchors of path `id`'s one closed outline. +fn corners(s: &Session, id: NodeId) -> Vec { + outline(s, id).anchors.iter().map(|a| a.p).collect() +} + +#[test] +fn connect_joins_the_external_tangents_and_the_chords_into_one_closed_shape_in_one_step() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + let (before, count) = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"tangents": "external", "connect": true, "ids": [a.0, b.0]})).unwrap(); + assert_eq!(steps(&s), before + 1, "one undo step"); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1, "one shape in place of two lines"); + assert_eq!(s.doc().unwrap().doc.node_count(), count + 1, "the circles stay"); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 4); + // The tangents above and below both circles, joined by each circle's vertical diameter. + for p in [Point::new(100.0, 80.0), Point::new(200.0, 80.0), Point::new(200.0, 120.0), Point::new(100.0, 120.0)] { + assert!(found.iter().any(|&q| near(p, q)), "{p:?} in {found:?}"); + } + // In order around the band, not crossing itself: the area is the 100 by 40 rectangle's. + let area = found.iter().zip(found.iter().cycle().skip(1)).map(|(p, q)| p.x * q.y - q.x * p.y).sum::() / 2.0; + assert!((area.abs() - 4000.0).abs() < 1e-6, "area {area} of {found:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +#[test] +fn connect_with_all_makes_one_shape_of_each_kind_and_a_point_makes_a_triangle() { + let mut s = session(); + let (ca, cb) = ((Point::new(100.0, 100.0), 20.0), (Point::new(220.0, 140.0), 40.0)); + let (a, b) = (circle(&mut s, ca.0.x, ca.0.y, ca.1), circle(&mut s, cb.0.x, cb.0.y, cb.1)); + let r = s.execute(C, &json!({"connect": true, "centerline": true, "ids": [a.0, b.0]})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(ids.len(), 3, "an external shape, an internal shape and the centerline"); + for &id in &ids[..2] { + let found = corners(&s, id); + assert_eq!(found.len(), 4); + let on = |(c, r): (Point, f64)| found.iter().filter(|p| ((**p - c).hypot() - r).abs() < 1e-6).count(); + assert_eq!((on(ca), on(cb)), (2, 2), "two corners where the tangents touch each circle: {found:?}"); + } + assert_ne!(corners(&s, ids[0]), corners(&s, ids[1])); + assert_eq!(r["centerline"], json!(ids[2].0)); + + let mut s = session(); + let (p, c) = (point(&mut s, 0.0, 100.0), circle(&mut s, 100.0, 100.0, 20.0)); + let r = s.execute(C, &json!({"connect": true, "ids": [p.0, c.0]})).unwrap(); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let found = corners(&s, NodeId(ids[0].as_u64().unwrap())); + assert_eq!(found.len(), 3, "the point and where its two lines touch the circle: {found:?}"); + assert!(found.iter().any(|&q| near(q, Point::new(0.0, 100.0)))); +} + +#[test] +fn curved_makes_the_bridge_the_smooth_bridge_command_makes() { + let build = || { + let mut s = session(); + let ids = [circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 150.0, 100.0, 20.0), circle(&mut s, 125.0, 140.0, 20.0)]; + select(&mut s, &ids); + s + }; + for (merged, old) in [ + (json!({"curved": true}), json!({})), + ( + json!({"tangents": "external", "connect": true, "curved": true, "gap": 5, "reach": 30, "keepOriginals": true}), + json!({"gap": 5, "reach": 30, "keepOriginals": true}), + ), + ] { + let (mut s, mut t) = (build(), build()); + let r = s.execute(C, &merged).unwrap(); + let q = t.execute("addon.pathtools.bridge", &old).unwrap(); + assert_eq!(r, q, "{merged}"); + let kinds = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.kind.clone()).collect::>(); + assert_eq!(kinds(&s), kinds(&t), "{merged}"); + } +} + +#[test] +fn options_of_the_other_mode_are_refused() { + let mut s = session(); + let (a, b) = (circle(&mut s, 100.0, 100.0, 20.0), circle(&mut s, 200.0, 100.0, 20.0)); + select(&mut s, &[a, b]); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + for (p, says) in [ + (json!({"connect": "yes"}), "connect"), + (json!({"curved": true, "tangents": "all"}), "external"), + (json!({"curved": true, "centerline": true}), "centerline"), + (json!({"curved": true, "connect": false}), "connected"), + (json!({"radius": 50}), "curved"), + (json!({"connect": true, "keepOriginals": true}), "curved"), + (json!({"curved": true, "radius": 50, "gap": 2}), "not both"), + (json!({"curved": true, "radius": 0}), "radius"), + ] { + assert!(err(&mut s, p.clone()).contains(says), "{p}: {}", err(&mut s, p.clone())); + } + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); +} diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 8264d2f27e..7c1a46350d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -388,6 +388,7 @@ const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ ("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids"), ("addon.pathtools.bridge", "radius", "gap"), + ("addon.pathtools.commonTangents", "radius", "gap"), ("links.unembed", "id", "ids"), ("links.unembed", "path", "folder"), ]; diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 9ff294a878..c6f02b9240 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -929,7 +929,20 @@ fn mutate_text(src: &str, cut: usize, edits: &[(usize, char)]) -> String { fn svg_type_shifted_two_billion_points_exports_to_pdf() { let svg = r#"f"#; let d = vectorcraft_svg::import(svg).unwrap(); - assert!(vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).is_ok()); + // The type opens with its shift, so the export below meets a glyph that far out. + let mut shifts = Vec::new(); + d.walk(|n| { + if let vectorcraft_doc::NodeKind::Text(t) = &n.kind { + shifts.extend(t.runs.iter().map(|r| r.style.baseline_shift)); + } + }); + assert!(shifts.iter().any(|&s| s.abs() > 2e9), "baseline shifts read: {shifts:?}"); + let pdf = vectorcraft_engine::export_pdf(&d, &vectorcraft_pdf::PdfOptions::default()).unwrap(); + // The PDF leaves the type out: reading it back finds no type. + let back = vectorcraft_pdf::import(&pdf).unwrap(); + let mut text = 0; + back.walk(|n| text += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)))); + assert_eq!(text, 0, "type left out of the page"); } proptest! { @@ -8630,6 +8643,16 @@ fn a_long_thin_shape_with_a_shadow_renders_and_exports() { let stream = canvas_stream(vec![with_effects(rectangle(10, (0.0, 0.0), (3_276_800.0, 50.0)), vec![shadow()])]); let bytes = affinity_sample_file(&stream, None); let doc = vectorcraft_engine::cmd::fileio::load("long.af", &bytes).unwrap().doc; + // The shape opens whole, with its shadow, so the exports below draw the shadow that far out. + let mut shadowed = Vec::new(); + doc.walk(|n| { + if n.appearance.effects.iter().any(|e| e.id == "stylize.dropShadow") { + shadowed.push(n.id); + } + }); + assert_eq!(shadowed.len(), 1, "one shape with a drop shadow"); + let width = doc.bounds_of(&shadowed, false).map(|r| r.width()); + assert!(width.is_some_and(|w| w > 3_000_000.0), "the shape is {width:?} pt wide"); survive("long shape", || Some(doc)).unwrap(); } diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 9e8a77e5dc..8e2a46c852 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -873,6 +873,7 @@ mod tests { } r.entry(&[V::Num(0.0), name("E")], Affine::IDENTITY); let mesh = r.one_mesh().unwrap(); + assert_eq!(mesh.points.len(), 9, "{mesh:?}"); assert!(mesh.points.iter().all(|q| q.p.x.is_finite() && q.p.y.is_finite() && q.handles.iter().all(|h| h.x.is_finite() && h.y.is_finite()))); } @@ -962,6 +963,7 @@ mod tests { assert!(!reader.unread, "{with_opacity} {data_first}"); let mesh = reader.one_mesh().unwrap(); let want = if with_opacity { 0.25 } else { 1.0 }; + assert_eq!(mesh.points.len(), 4, "{with_opacity} {data_first}: {mesh:?}"); assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}"); } } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index bb5343e4f4..0b6ac8b9dd 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -2217,7 +2217,8 @@ mod tests { let ap = styled(&image, &look, &st, &paints).expect("an image takes one Warp"); let ids: Vec<&str> = ap.effects.iter().map(|e| e.id.as_str()).collect(); assert_eq!(ids, ["warp.arc"]); - assert!(ap.items.iter().all(|i| i.paint().is_none()), "{ap:?}"); + // The image's own look: none of the look's fills and strokes. + assert!(ap.items.is_empty(), "{ap:?}"); // Not on a path, nor on an image with an opacity mask. assert!(styled(&square(3, Paint::None), &look, &st, &paints).is_none()); let mut masked = image.clone(); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 0d09cf8dab..9ef4cbc840 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -291,6 +291,7 @@ fn object_tags_without_an_object_before_them_tag_nothing() { let doc = read7(&layer7("L", &body)).doc; let mut all = art(&doc); all.extend(all.iter().flat_map(|n| n.children().cloned().unwrap_or_default()).collect::>()); + assert!(!all.is_empty(), "{body}: no art"); assert!(all.iter().all(|n| n.extras().attrs.is_none()), "{body}"); } for bad in ["(x) (y) XT\n", "/id 3 XT\n", "XT\n"] { diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 6830fb5b41..e7fd734240 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -241,6 +241,7 @@ fn cmyk_jpegs_keep_their_ink_amounts() { /ImageMatrix [2 0 0 -2 0 2] /DataSource currentfile /ASCIIHexDecode filter /DCTDecode filter >> image\n{data}>" )); let got = inks(&r).data; + assert_eq!(got.len(), want.len(), "{decode}: {got:?}"); assert!(got.iter().zip(&want).all(|(a, b)| a.abs_diff(*b) <= 3), "{decode}: {got:?}"); } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index c5b6b61d58..9fdeba9ff5 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8238,6 +8238,7 @@ fn type_with_a_distort_effect_comes_in_as_type_with_it_live() { // An angle that isn't a number: the drawing as paths, and no effect on the type. let (texts, paths) = open("Adobe Twirl", "NaN /Real (angle) ,\n"); assert_eq!(paths, 1, "{texts:?}"); + assert_eq!(texts.len(), 1, "{texts:?}"); assert!(texts.iter().all(|(_, effects)| effects.is_empty()), "{texts:?}"); } diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 3b45578deb..dc40025954 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -301,12 +301,23 @@ fn spread_gradients_are_written_with_their_stops_repeated() { fn a_spread_gradient_without_stops_is_written() { use vectorcraft_color::GradientSpread; for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { - let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) }); - let paint = Paint::Gradient(Box::new(g)); - let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]); - export(&d, &opts(&d), None, None).unwrap(); - export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap(); - crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap(); + let doc = |spread: GradientSpread| { + let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) }); + let paint = Paint::Gradient(Box::new(g)); + doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), paint.clone(), paint, 4.0)]) + }; + let (d, pad) = (doc(GradientSpread::Repeat), doc(GradientSpread::Pad)); + assert_eq!(page_of(&d, &opts(&d)), page_of(&pad, &opts(&pad)), "{kind:?}: EPS"); + assert_eq!( + export_legacy_ai(&d, &LegacyAiOptions::default()).unwrap().bytes, + export_legacy_ai(&pad, &LegacyAiOptions::default()).unwrap().bytes, + "{kind:?}: legacy .ai" + ); + assert_eq!( + crate::export_ai_editing(&d, &crate::AiEditingOptions::default()).unwrap().program, + crate::export_ai_editing(&pad, &crate::AiEditingOptions::default()).unwrap().program, + "{kind:?}: .ai editing data" + ); } } @@ -2359,15 +2370,15 @@ fn symbol_art_effects_are_written_where_they_draw() { #[test] fn level_preview_and_overprint_ids_read_back() { - for l in Level::ALL { - assert_eq!(Level::from_id(l.id()), Some(l)); - } + assert_eq!(Level::from_id("3"), Some(Level::Three)); assert_eq!(Level::from_id("LanguageLevel 2"), Some(Level::Two)); assert_eq!(Level::from_id("1"), None); - for p in Preview::ALL { - assert_eq!(Preview::from_id(p.id()), Some(p)); - } + assert_eq!(Level::from_id("23"), None); + assert_eq!(Preview::from_id(" TIFFCOLOR "), Some(Preview::TiffColor)); + assert_eq!(Preview::from_id("tiffBw"), Some(Preview::TiffBlackWhite)); + assert_eq!(Preview::from_id("tiff"), None); assert_eq!(Overprint::from_id("DISCARD"), Some(Overprint::Discard)); + assert_eq!(Overprint::from_id(""), None); } #[test] diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 346df8ab64..6852f317b3 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1543,7 +1543,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs index 2b2fd9512e..f1eaa29283 100644 --- a/crates/pathops/src/addons/pathtools/bridge.rs +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -816,11 +816,14 @@ mod tests { // Squaring these lengths overflows f64. let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153)); let sp = smooth_bridge(a, b, 5e153).unwrap(); + // At least one anchor for each of the two circles and the two arcs. + assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len()); assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); assert_smooth(&sp); // The two radius sums fit in f64, but not their total. let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307)); let sp = smooth_bridge(a, b, 1.5e308).unwrap(); + assert!(sp.closed && sp.anchors.len() >= 4, "{}", sp.anchors.len()); assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); // The arcs' centers would lie beyond the largest f64. let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308)); diff --git a/crates/pathops/src/addons/pathtools/shapes.rs b/crates/pathops/src/addons/pathtools/shapes.rs index e0ecc241be..dc61429c34 100644 --- a/crates/pathops/src/addons/pathtools/shapes.rs +++ b/crates/pathops/src/addons/pathtools/shapes.rs @@ -609,12 +609,12 @@ mod tests { fn each_kind_draws_a_closed_outline_in_its_box() { for kind in ShapeKind::ALL { let s = shape(kind); - assert_eq!(ShapeKind::parse(kind.id()), Some(kind)); assert_eq!(s.check(), Ok(()), "{kind:?}"); let p = s.path().unwrap(); assert!(closed(&p) && within_box(&p, &s), "{kind:?}: {:?}", p.bounds()); assert!(p.anchors().all(|(_, _, a)| a.p.x.is_finite() && a.p.y.is_finite())); } + assert_eq!(ShapeKind::parse("gear"), Some(ShapeKind::Gear)); assert_eq!(ShapeKind::parse("cloud"), None); } diff --git a/crates/pathops/src/addons/pathtools/shared_edge/tests.rs b/crates/pathops/src/addons/pathtools/shared_edge/tests.rs index 38e7c49e3b..ef84d72f83 100644 --- a/crates/pathops/src/addons/pathtools/shared_edge/tests.rs +++ b/crates/pathops/src/addons/pathtools/shared_edge/tests.rs @@ -262,9 +262,7 @@ fn a_smooth_end_whose_handles_part_turns_into_a_corner() { } #[test] -fn follow_names_round_trip() { - for f in Follow::ALL { - assert_eq!(Follow::parse(f.id()), Some(f)); - } +fn follow_names_parse() { + assert_eq!(Follow::parse("b"), Some(Follow::Second)); assert_eq!(Follow::parse("up"), None); } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index e26d0e69e9..504d8af795 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -738,6 +738,8 @@ fn simplify_levels_and_auto_simplify() { #[test] fn smooth_rounds_corners() { let s = smooth(&rect(0.0, 0.0, 10.0, 10.0), 1.0); + // The four corners stay, each made smooth. + assert_eq!(s.anchor_count(), 4, "{s:?}"); assert!(s.anchors().all(|(_, _, a)| a.has_in() && a.has_out())); let same = smooth(&rect(0.0, 0.0, 10.0, 10.0), 0.0); assert_eq!(same, rect(0.0, 0.0, 10.0, 10.0)); @@ -959,7 +961,7 @@ fn grid_split() { } #[test] -#[ignore] +#[ignore = "benchmark: prints how long Unite takes on 1000 circles; run by hand with --ignored"] fn timing_unite_1000_circles() { let mut seed = 0x1234_5678_u64; let mut rnd = || { @@ -971,8 +973,8 @@ fn timing_unite_1000_circles() { let circles: Vec = (0..1000).map(|i| shape(circle(rnd() * 1000.0, rnd() * 1000.0, 5.0 + rnd() * 30.0), i)).collect(); let t = std::time::Instant::now(); let r = pathfinder(PathfinderOp::Unite, &circles); + assert_eq!(r.len(), 1, "Unite gives one compound shape"); println!("unite 1000 circles: {} ms, {} anchors", t.elapsed().as_millis(), r[0].path.anchor_count()); - assert!(!r.is_empty()); } #[test] diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index bdf51da6f8..d6d68ee02b 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -915,6 +915,7 @@ mod tests { let (inks, alpha) = resampled_inks(inks, Some(alpha.clone()), &rule(&c, Kind::Color), (4, 1)).unwrap(); let alpha = alpha.unwrap(); let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8; + assert_eq!((inks.as_chunks::<4>().0.len(), alpha.len()), (4, 4), "{method}"); for (p, &a) in inks.as_chunks::<4>().0.iter().zip(&alpha) { assert!(a > 0 && p.iter().zip([40, 80, 120, 160]).all(|(&c, want)| m(c, a).abs_diff(m(want, a)) <= 1), "{method}: {p:?} at {a}"); } diff --git a/crates/pdf/src/tests/mesh_export.rs b/crates/pdf/src/tests/mesh_export.rs index cf8ad25e3b..b2e8ecb2f6 100644 --- a/crates/pdf/src/tests/mesh_export.rs +++ b/crates/pdf/src/tests/mesh_export.rs @@ -73,11 +73,14 @@ fn a_cmyk_mesh_is_written_smooth_in_its_inks() { let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); let (meshes, paths) = kinds(&back); assert!(meshes >= 1 && paths <= 4, "meshes {meshes}, paths {paths}"); + let mut points = vec![]; back.walk(|n| { if let NodeKind::Mesh(m) = &n.kind { - assert!(m.points.iter().all(|p| matches!(p.color, Color::Cmyk { .. })), "{:?}", m.points); + points.extend(m.points.iter().map(|p| p.color)); } }); + assert!(!points.is_empty(), "the meshes have points"); + assert!(points.iter().all(|c| matches!(c, Color::Cmyk { .. })), "{points:?}"); assert_similar(&render_artboard(&d), &render_artboard(&back), 6.0, 0.02); } diff --git a/crates/pdf/src/tests/spread.rs b/crates/pdf/src/tests/spread.rs index ebfe655f9a..0a852ba664 100644 --- a/crates/pdf/src/tests/spread.rs +++ b/crates/pdf/src/tests/spread.rs @@ -236,17 +236,21 @@ fn a_perceptual_spot_gradient_too_long_once_repeated_is_an_image() { } } -/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked. +/// A gradient that repeats with no stops (a file can hold one) exports, filled and stroked, as the +/// same gradient that pads does. #[test] fn a_spread_gradient_without_stops_exports() { for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] { - let g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(kind, vec![]) }); - let paint = Paint::Gradient(Box::new(g)); - let mut d = Document::new(200.0, 200.0); - let (l, id) = (d.layers[0].id, d.alloc_id()); - let ap = Appearance::basic(paint.clone(), paint, 4.0); - d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap(); - export(&d, &PdfOptions::default()).unwrap(); + let written = |spread: GradientSpread| { + let g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(kind, vec![]) }); + let paint = Paint::Gradient(Box::new(g)); + let mut d = Document::new(200.0, 200.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let ap = Appearance::basic(paint.clone(), paint, 4.0); + d.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 180.0)), ap)).unwrap(); + uncompressed(&d, &PdfOptions { created: Some(0), ..PdfOptions::uncompressed() }) + }; + assert_eq!(written(GradientSpread::Repeat), written(GradientSpread::Pad), "{kind:?}"); } } diff --git a/crates/pdf/src/tests/stroke.rs b/crates/pdf/src/tests/stroke.rs index d57cbc42d0..881ebd4a4c 100644 --- a/crates/pdf/src/tests/stroke.rs +++ b/crates/pdf/src/tests/stroke.rs @@ -90,5 +90,6 @@ fn line_and_head_share_one_opacity_group() { _ => {} }); assert!(group_opacity.is_some_and(|o| (o - 0.5).abs() < 0.01), "{group_opacity:?}"); + assert!(!leaf_opacities.is_empty(), "the line and its head come back as paths"); assert!(leaf_opacities.iter().all(|o| (o - 1.0).abs() < 1e-3), "{leaf_opacities:?}"); } diff --git a/crates/pdf/src/tests/text_placement.rs b/crates/pdf/src/tests/text_placement.rs index 31ea411840..f64f8c4173 100644 --- a/crates/pdf/src/tests/text_placement.rs +++ b/crates/pdf/src/tests/text_placement.rs @@ -745,7 +745,7 @@ fn text_heavy(columns: usize, rows: usize) -> Vec { /// How long a text-heavy file takes to open as type (run by hand: `-- --ignored --nocapture`). #[test] -#[ignore] +#[ignore = "timing, run by hand"] fn perf_text_heavy_open() { let bytes = text_heavy(20, 200); for _ in 0..2 { diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index a78aeec09b..f7cf875a6c 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -330,13 +330,11 @@ mod tests { use super::*; #[test] - fn names_round_trip_and_serialize_as_names() { - for p in ALL { - assert_eq!(Permission::parse(p.name()), Some(p)); - assert_eq!(serde_json::to_value(p).unwrap(), serde_json::json!(p.name())); - } + fn names_parse_and_serialize_as_names() { + assert_eq!(serde_json::to_value(ALL).unwrap(), serde_json::json!(names(&ALL)), "saved names are the names"); + assert_eq!(Permission::parse("doc.write"), Some(Permission::DocWrite)); assert_eq!(Permission::parse("document.read"), None); - assert!(RESERVED.iter().all(|r| Permission::parse(r).is_none()), "reserved names are not granted"); + assert!(!RESERVED.is_empty() && RESERVED.iter().all(|r| Permission::parse(r).is_none()), "reserved names are not granted"); } #[test] diff --git a/crates/render/src/encode/tests_bmp.rs b/crates/render/src/encode/tests_bmp.rs index f458c1999b..64d3ecdb55 100644 --- a/crates/render/src/encode/tests_bmp.rs +++ b/crates/render/src/encode/tests_bmp.rs @@ -133,6 +133,7 @@ fn greys_and_impossible_combinations() { let px = art(w, h); for depth in [8, 24] { let img = decode(&bmp(&px, w, h, &BmpOptions { depth, gray: true, ..Default::default() }), craft_image_codecs::Format::Bmp); + assert_eq!(img.dimensions(), (w, h), "depth {depth}"); assert!(img.pixels().all(|p| p[0] == p[1] && p[1] == p[2]), "depth {depth}: greys"); } let bad = [ diff --git a/crates/render/src/encode/tests_jpeg.rs b/crates/render/src/encode/tests_jpeg.rs index 413781de13..375dcaf15a 100644 --- a/crates/render/src/encode/tests_jpeg.rs +++ b/crates/render/src/encode/tests_jpeg.rs @@ -164,15 +164,18 @@ fn colour_models_write_their_components_and_profiles() { #[test] fn model_and_method_ids_round_trip() { - for m in ColorModel::ALL { - assert_eq!(ColorModel::from_id(m.id()), Some(m)); - assert_eq!(ColorModel::from_id(m.label()), Some(m)); - } + // Saved options name a model or a method by id or label, in any case. + assert_eq!(ColorModel::from_id("cmyk"), Some(ColorModel::Cmyk)); + assert_eq!(ColorModel::from_id("RGB"), Some(ColorModel::Rgb)); + assert_eq!(ColorModel::from_id("gray"), Some(ColorModel::Gray)); + assert_eq!(ColorModel::from_id("Grayscale"), Some(ColorModel::Gray)); assert_eq!(ColorModel::from_id("grey"), Some(ColorModel::Gray)); - for m in Method::ALL { - assert_eq!(Method::from_id(m.id()), Some(m)); - } + assert_eq!(ColorModel::from_id("lab"), None); + assert_eq!(Method::from_id("optimized"), Some(Method::Optimized)); + assert_eq!(Method::from_id("baseline optimized"), Some(Method::Optimized)); + assert_eq!(Method::from_id("Progressive"), Some(Method::Progressive)); assert_eq!(Method::from_id("bogus"), None); + assert_eq!(Method::from_id(""), None); } /// A 20×10 pt document: a black-ink rectangle on the left half, an RGB red one on the right. diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 837c62f359..d4067fc743 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -245,12 +245,17 @@ fn gif_decodes() { #[test] fn ids_round_trip() { - for r in Reduction::ALL { - assert_eq!(Reduction::from_id(r.id()), Some(r)); - } - for d in Dither::ALL { - assert_eq!(Dither::from_id(d.id()), Some(d)); - } + // Saved options name a reduction or a dither by id or label, in any case. + assert_eq!(Reduction::from_id("blackWhite"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("blackwhite"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("Black & White"), Some(Reduction::BlackWhite)); + assert_eq!(Reduction::from_id("selective"), Some(Reduction::Selective)); + assert_eq!(Reduction::from_id("restrictive"), None); + assert_eq!(Dither::from_id("none"), Some(Dither::None)); + assert_eq!(Dither::from_id("No Dither"), Some(Dither::None)); + assert_eq!(Dither::from_id("PATTERN"), Some(Dither::Pattern)); + assert_eq!(Dither::from_id("bayer"), None); + assert_eq!(Dither::from_id(""), None); } /// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`. diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 757290ed1f..f843ce01f7 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -371,9 +371,16 @@ fn per_stroke_raster_effects_use_the_single_threaded_pipeline() { } d.remove(id).unwrap(); d.insert(Some(l), 0, n).unwrap(); - let mut r = Renderer::new(); - r.threads = 4; - let _ = r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + let draw = |threads| { + let mut r = Renderer::new(); + r.threads = threads; + r.render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()) + }; + let (threaded, single) = (draw(4), draw(1)); + // The stroke's glow shows outside it: red, where nothing else is drawn. + let glow = threaded.pixel(40, 14); + assert!(glow[3] > 0 && glow[0] > glow[1] && glow[0] > glow[2], "{glow:?}"); + assert!(threaded.pixels == single.pixels, "four threads draw what one does"); } #[test] @@ -1966,7 +1973,7 @@ fn rasters_made_over_moved_rasters_count_as_moved() { /// Reproduce #1257's moving, filtered rectangle: the first frame renders as before a drag, /// and the next eight render as the canvas renders a drag's frames (`interacting`). Then the /// eighth position renders as the canvas renders the frame after the drag, and that frame -/// renders once more with every raster cached. +/// renders once more with every raster cached. Both draw what a fresh renderer draws. /// Run with `cargo test -p vectorcraft-render texture_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] @@ -2004,10 +2011,12 @@ fn texture_drag_perf() { } let mut time = |o: &RenderOptions| { let start = std::time::Instant::now(); - std::hint::black_box(r.render(&doc, 1800, 1500, view, o)); - start.elapsed().as_secs_f64() * 1000.0 + let image = r.render(&doc, 1800, 1500, view, o); + (start.elapsed().as_secs_f64() * 1000.0, image.pixels) }; - let (after, again) = (time(&opts), time(&opts)); + let ((after, after_px), (again, again_px)) = (time(&opts), time(&opts)); + let fresh = Renderer::new().render(&doc, 1800, 1500, view, &opts).pixels; + assert!(after_px == fresh && again_px == fresh, "{effect}: the frame after the drag draws what a fresh renderer draws"); ms.sort_by(f64::total_cmp); println!( "{effect}: moved CMYK rounded rectangle at 190.07%, DPI 1.5, 1800x1500: median {:.2} ms; samples {ms:?}; the frame after the drag {after:.2} ms, that frame again {again:.2} ms", @@ -2020,7 +2029,7 @@ fn texture_drag_perf() { /// view centered on the rectangle: the first frame renders as before a drag, and the next eight /// render as a drag's frames, once with `interacting` alone and once with `dragging` as well (as /// the canvas renders them). Then the eighth position renders as the canvas renders the frame -/// after the drag. The hashes of that frame and of a fresh renderer's frame compare builds. +/// after the drag, which draws what a fresh renderer draws. /// Run with `cargo test -p vectorcraft-render zoomed_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] @@ -2030,12 +2039,6 @@ fn zoomed_drag_perf() { ("Gaussian Blur 8 pt", vec![("blur.gaussian", json!({"radius": 8}))]), ("Drop Shadow and Craquelure", vec![("stylize.dropShadow", json!({"blur": 7})), ("texture.craquelure", json!({}))]), ]; - let hash = |px: &[u8]| { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - px.hash(&mut h); - h.finish() - }; for (name, effects) in sets { for zoom in [1.0, 4.0, 16.0, 64.0] { let base = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), effects.clone()); @@ -2062,15 +2065,14 @@ fn zoomed_drag_perf() { let still = r.render(&doc, 2560, 1440, view, &opts); let after = start.elapsed().as_secs_f64() * 1000.0; let fresh = Renderer::new().render(&doc, 2560, 1440, view, &opts); + assert!(still.pixels == fresh.pixels, "{name} at {zoom}x, dragging {dragging}: the frame after the drag"); ms.sort_by(f64::total_cmp); println!( - "{name} at {:.0}%, dragging {dragging}: drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms; hashes {:016x} {:016x}", + "{name} at {:.0}%, dragging {dragging}: drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms", zoom * 100.0, (ms[3] + ms[4]) * 0.5, ms[0], ms[7], - hash(&still.pixels), - hash(&fresh.pixels) ); } } diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index a69ac094ae..28adeba7c2 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -275,12 +275,19 @@ fn short_dashed_strokes_are_outlined_whole() { let one = BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(100.0, 100.0))]); let mut dot = one.clone(); dot.line_to((100.0, 100.0)); - for (what, bp) in - [("empty", BezPath::new()), ("one anchor", one), ("one anchor, closed on itself", dot), ("a ring of 40 anchors", ring(40, 80.0))] - { + // The ring is outlined once; the degenerate paths only have to draw what a whole outline draws. + for (what, bp, ring_of_40) in [ + ("empty", BezPath::new(), false), + ("one anchor", one, false), + ("one anchor, closed on itself", dot, false), + ("a ring of 40 anchors", ring(40, 80.0), true), + ] { let d = doc(&bp, st.clone()); let mut r = Renderer::new(); let img = render(&mut r, &d, Point::new(100.0, 100.0)); + if ring_of_40 { + assert_eq!(r.strokes.len(), 1, "{what}: one outline"); + } assert!(r.strokes.values().all(|e| e.crop.is_none()), "{what}: outlined whole"); assert!(img.pixels == whole(&d, Point::new(100.0, 100.0)).pixels, "{what}: the same pixels"); } @@ -393,6 +400,7 @@ fn a_stroke_a_wide_stroke_crosses_over_stays_whole() { let at = Point::new(20_000.0, 2.0); let mut r = Renderer::new(); let img = render(&mut r, &d, at); + assert_eq!(r.strokes.len(), 1, "one outline"); assert!(r.strokes.values().all(|e| e.crop.is_none())); assert!(img.pixels == whole(&d, at).pixels); } diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index d5009c2072..8579c314b8 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2662,6 +2662,7 @@ fn a_reduced_cmyk_image_paints_its_own_inks() { let d = cmyk_doc_with("inks", blob, 8, 8); let on = RenderOptions { image_mips: true, ..Default::default() }; let inks = Renderer::new().render_region_inks(&d, Rect::new(0.0, 0.0, 8.0, 8.0), 0.25, &on); + assert_eq!(inks.len(), 2 * 2 * 4, "2 × 2 pixels of four inks"); for px in inks.as_chunks::<4>().0 { assert!(px.iter().zip(ink).all(|(a, b)| a.abs_diff(b) <= 1), "{px:?} vs {ink:?}"); } @@ -2805,6 +2806,7 @@ fn a_tiled_image_draws_what_the_whole_image_draws() { let plane = |ink| ink::ink_image(&key, &full, ink, d.images.get("seams"), false).1; let bytes = |pm: &Pixmap| pm.data().iter().flat_map(|p| [p.r, p.g, p.b, p.a]).collect::>(); let whole = ink::amounts(&bytes(&plane(Ink::Cmy)), &bytes(&plane(Ink::K))); + assert_eq!(drawn.len(), 300 * 40 * 4, "300 × 40 pixels of four inks"); for (i, got) in drawn.as_chunks::<4>().0.iter().enumerate() { let (x, y) = (x0 as usize + i % 300, i / 300); let want = &whole[(y * w as usize + x) * 4..][..4]; diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 0087c1a4a8..0a69d9ba3c 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -420,18 +420,11 @@ fn a_shadow_over_a_cropped_shadow_keeps_to_the_earlier_ones_margin() { /// Time a drag of the square over each backdrop in a 2560 × 1440 view: the first frame renders as /// before a drag, the next eight as a drag's frames (`interacting` and `dragging`, as the canvas -/// renders them), then the frame after the drag. The hashes of that frame and of a fresh renderer's -/// frame compare builds. +/// renders them), then the frame after the drag, which draws what a fresh renderer draws. /// Run with `cargo test --release -p vectorcraft-render backdrop_drag_perf -- --ignored --nocapture`. #[test] #[ignore = "manual timing probe; wall-clock performance depends on machine load"] fn backdrop_drag_perf() { - let hash = |px: &[u8]| { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - px.hash(&mut h); - h.finish() - }; let size = (2560, 1440); for (name, effects, zoom) in cases() { let (base, id) = backdrop(&effects); @@ -455,15 +448,14 @@ fn backdrop_drag_perf() { let still = r.render(&doc, size.0, size.1, xf, &opts); let after = start.elapsed().as_secs_f64() * 1000.0; let fresh = Renderer::new().render(&doc, size.0, size.1, xf, &opts); + assert!(still.pixels == fresh.pixels, "{name} at {zoom}x: the frame after the drag"); ms.sort_by(f64::total_cmp); println!( - "{name} at {:.0}%: first frame {first:.1} ms; drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms; hashes {:016x} {:016x}", + "{name} at {:.0}%: first frame {first:.1} ms; drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms", zoom * 100.0, (ms[3] + ms[4]) * 0.5, ms[0], ms[7], - hash(&still.pixels), - hash(&fresh.pixels) ); } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index ea745aaebf..1edd1480f6 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -2697,6 +2697,8 @@ fn a_file_two_branches_include_is_followed_from_the_shallower_one() { ]); let limits = Limits { include_depth: 3, ..Limits::default() }; let r = check("main.jsx", b"#include 'a.jsxinc'\n#include 'b.jsxinc'\n", Some(&mut m), &limits); + // One row per #include line: main's two, a's, b's, c's and shared's. + assert_eq!(r.includes.len(), 6, "{:?}", includes(&r)); assert!(r.includes.iter().all(|i| i.status == IncludeStatus::Checked), "{:?}", includes(&r)); assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["network"]); } diff --git a/crates/svg/src/import/convert.rs b/crates/svg/src/import/convert.rs index 676708a09d..a5e7bc3e63 100644 --- a/crates/svg/src/import/convert.rs +++ b/crates/svg/src/import/convert.rs @@ -297,3 +297,40 @@ pub(super) fn rule(r: usvg::FillRule) -> FillRule { usvg::FillRule::EvenOdd => FillRule::EvenOdd, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Clip paths are shared, so children that each name the next one multiply at every level: ten + /// children on seven levels would take 10^7 reads unbounded. The paths read stay within ten (the + /// children of one clip path) per clip path read, and the clip still has shapes. + #[test] + fn clip_paths_whose_children_fan_out_are_read_a_bounded_number_of_times() { + let mut defs = String::from(r#""#); + for n in 1..8 { + let kids = format!(r#""#, n - 1).repeat(10); + defs += &format!(r#"{kids}"#); + } + let svg = format!( + r#"{defs}"# + ); + let tree = usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap(); + let cp = tree + .root() + .children() + .iter() + .find_map(|c| match c { + usvg::Node::Group(g) => g.clip_path(), + _ => None, + }) + .unwrap(); + let visits = std::cell::Cell::new(0usize); + let shapes = clip_shapes(cp, Affine::IDENTITY, &|_, _| { + visits.set(visits.get() + 1); + None + }); + assert!(!shapes.is_empty()); + assert!(visits.get() <= 10 * MAX_CLIP_READS, "{} paths read", visits.get()); + } +} diff --git a/crates/svg/tests/convolve_overflow.rs b/crates/svg/tests/convolve_overflow.rs index 4c080e1944..2971027a67 100644 --- a/crates/svg/tests/convolve_overflow.rs +++ b/crates/svg/tests/convolve_overflow.rs @@ -8,8 +8,17 @@ // Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use vectorcraft_doc::NodeKind; use vectorcraft_svg::import; +/// How many paths `svg` imports as: each file here holds one filtered rectangle. +fn paths(svg: &str) -> usize { + let d = import(svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + let mut n = 0; + d.walk(|node| n += usize::from(matches!(node.kind, NodeKind::Path { .. }))); + n +} + /// An overflowing `order` with a `kernelMatrix` that parses (usvg `parser/filter.rs`). #[test] fn convolve_matrix_overflowing_order_with_kernel_is_refused() { @@ -44,7 +53,7 @@ fn convolve_matrix_large_but_fitting_order_still_imports() { let svg = format!( r#""# ); - assert!(import(&svg).is_ok(), "order={order} fits the u32 multiply and must keep importing"); + assert_eq!(paths(&svg), 1, "order={order} fits the u32 multiply and must keep importing"); } } @@ -56,7 +65,7 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() { let svg = format!( r#""# ); - assert!(import(&svg).is_ok(), "order={order} is usvg's pass-through and must keep importing"); + assert_eq!(paths(&svg), 1, "order={order} is usvg's pass-through and must keep importing"); } } @@ -65,18 +74,18 @@ fn convolve_matrix_nonpositive_or_unparseable_order_still_imports() { #[test] fn convolve_matrix_unparseable_or_mismatched_kernel_still_imports() { let mismatched = r#""#; - assert!(import(mismatched).is_ok(), "a kernel of the wrong length is usvg's pass-through"); + assert_eq!(paths(mismatched), 1, "a kernel of the wrong length is usvg's pass-through"); let unparseable = r#""#; - assert!(import(unparseable).is_ok(), "an unparseable kernel is usvg's pass-through"); + assert_eq!(paths(unparseable), 1, "an unparseable kernel is usvg's pass-through"); } /// Sane kernels keep importing: 3×3, 2×2, and a defaulted order. #[test] fn sane_convolve_matrices_still_import() { let three = r#""#; - assert!(import(three).is_ok(), "an ordinary filter must still import"); + assert_eq!(paths(three), 1, "an ordinary filter must still import"); let two = r#""#; - assert!(import(two).is_ok(), "a small kernel must still import"); + assert_eq!(paths(two), 1, "a small kernel must still import"); let defaulted = r#""#; - assert!(import(defaulted).is_ok(), "a filter without order must still import"); + assert_eq!(paths(defaulted), 1, "a filter without order must still import"); } diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index a4046e3fe7..c96dd72adb 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -552,21 +552,6 @@ fn clip_path_child_with_chained_clip_path_intersects() { assert_eq!(mine.over_white(100, 25), [255, 255, 255], "top right is cut by inner clip"); } -/// Clip paths are shared, so children that each name the next one multiply at every level: ten -/// children on seven levels would take 10^7 reads unbounded. The import must still finish. -#[test] -fn clip_paths_whose_children_fan_out_still_import() { - let mut defs = String::from(r#""#); - for n in 1..8 { - let kids = format!(r#""#, n - 1).repeat(10); - defs += &format!(r#"{kids}"#); - } - let svg = format!( - r#"{defs}"# - ); - assert!(import_with_report(&svg).is_ok()); -} - #[test] fn clip_path_deep_chain_preserves_art() { let mut defs = String::from(r#""#); diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index c8a1cfd4ed..9c1cac5890 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -226,7 +226,10 @@ fn a_use_of_a_text_passes_its_properties_on_to_the_text() { #[test] fn a_use_inside_the_text_it_shows_opens() { let d = open(r##"HI"##); - assert!(texts(&d).iter().all(|t| close(t.first_style().size, 20.0, 1e-9)), "{:?}", texts(&d)); + let t = texts(&d); + assert_eq!(t.len(), 1, "{t:?}"); + assert_eq!(t[0].plain_text(), "HI"); + assert!(close(t[0].first_style().size, 20.0, 1e-9), "{t:?}"); } /// Past 1 MiB of text built for `` elements, the rest show their text with its own properties. @@ -1232,6 +1235,7 @@ fn vertical_writing_mode_runs_down_a_path() { let b = path.bounds().unwrap(); assert!(close(b.x0, b.x1, 1e-9) && close(b.y0, 20.0, 1e-9) && b.height() > 20.0, "{b:?}"); let o = glyph_origins(t); + assert_eq!(o.len(), 4, "{o:?}"); assert!(o.windows(2).all(|w| w[1].y > w[0].y), "glyphs step down: {o:?}"); // The em box is centred on the column. let lay = layout(FontDb::global(), t); diff --git a/crates/svg/tests/it/svg_glyphs.rs b/crates/svg/tests/it/svg_glyphs.rs index 3e4ba8b697..b48c486446 100644 --- a/crates/svg/tests/it/svg_glyphs.rs +++ b/crates/svg/tests/it/svg_glyphs.rs @@ -56,6 +56,7 @@ fn current_color_and_context_colours_are_the_texts() { let (art, _) = glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap(); let mut strokes = vec![]; art.walk(&mut |c| strokes.push(c.appearance.stroke_paint())); + assert_eq!(strokes.len(), seen.len(), "the same art without the text's stroke: {strokes:?}"); assert!(strokes.iter().all(|p| *p == Paint::None), "no stroke without the text's: {strokes:?}"); let plain = r##""##; assert!(!glyph_art(plain.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1, "a document in its own colours"); diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 1d1b4cc712..05e70265fa 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -554,7 +554,10 @@ fn symbols_inside_themselves_end() { d.symbols.push(Symbol { dynamic: false, name: "Loop".into(), art: Arc::new(g) }); instance(&mut d, "Loop", Affine::translate((20.0, 20.0))); let svg = export(&d, &ExportOptions::default()); - assert!(import(&svg).is_ok(), "{svg}"); + // The symbol that holds itself is not written into itself; the other one still comes back. + assert!(svg.matches(" = star.iter().map(|p| (p.x, p.y)).collect(); let spans = invert_wrap_spans(&contour, 1.0, 10.0, 90.0); + assert!(!spans.is_empty(), "the line still meets the shape"); assert!(spans.iter().all(|&(a, b)| a >= 4.0 && b <= 96.0), "{spans:?}"); let square = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)]; assert_spans(&invert_wrap_spans(&square, f64::NAN, 45.0, 55.0), &invert_wrap_spans(&square, 0.0, 45.0, 55.0)); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 40b29331f9..eb81d3c096 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1028,6 +1028,7 @@ fn whitespace_the_primary_font_lacks_takes_the_fallback_face() { assert!((width - 60.0).abs() < 0.01, "あ あ sets at 3 em: {:?}", l.glyphs.iter().map(|g| g.advance).collect::>()); assert_ne!(l.glyphs[1].font_id, primary.id()); let l = layout(db(), &point("a\tb", style(20.0))); + assert_eq!(l.glyphs.len(), 3, "{:?}", l.glyphs); assert!(l.glyphs.iter().all(|g| g.font_id == primary.id())); } @@ -2649,6 +2650,8 @@ fn thai_loanwords_stay_whole() { let lines: Vec<&str> = l.lines.iter().map(|ln| &text[ln.start..ln.end]).collect(); // No line ends inside the word, whatever the Thai font's widths put beside it. let word = text.find("โปรแกรม").unwrap(); + assert!(lines.len() > 1, "70 pt wraps the sentence: {lines:?}"); + assert!(lines.iter().any(|ln| ln.contains("โปรแกรม")), "one line holds the word: {lines:?}"); assert!(l.lines.iter().all(|ln| ln.end <= word || ln.end >= word + "โปรแกรม".len()), "{lines:?}"); } diff --git a/crates/text/src/tests/bidi.rs b/crates/text/src/tests/bidi.rs index a8f035aa6e..bf47f56d5a 100644 --- a/crates/text/src/tests/bidi.rs +++ b/crates/text/src/tests/bidi.rs @@ -253,10 +253,15 @@ fn paragraph_direction_is_independent_and_neutrals_do_not_force_ltr() { #[test] fn hebrew_marks_stay_with_base_clusters() { let s = "שָׁלוֹם"; - let l = text_layout(s); - for g in &l.glyphs { - assert!(s.get(g.byte..g.byte + g.len).is_some()); + if FontDb::global().face_covering('ש').is_none_or(|face| !['ל', 'ו', 'ם'].into_iter().all(|c| face.covers(c))) { + eprintln!("SKIPPED: hebrew_marks_stay_with_base_clusters; no installed font covers Hebrew shin, lamed, vav and final mem"); + return; } + let l = text_layout(s); + // Each glyph's source starts at one of the four letters, never at a point after one. + let starts: std::collections::BTreeSet = l.glyphs.iter().map(|g| g.byte).collect(); + assert_eq!(starts, [0, 6, 8, 12].into(), "{:?}", l.glyphs.iter().map(|g| (g.byte, g.len)).collect::>()); + assert_source_coverage(s, &l); assert!(l.glyphs.iter().all(|g| g.rtl)); } @@ -413,6 +418,10 @@ fn bidi_isolates_numbers_and_brackets_keep_valid_clusters() { for g in &l.glyphs { assert!(s.get(g.byte..g.byte + g.len).is_some()); } + // Every character but the isolate marks is drawn by a glyph whose source holds it. + for (i, c) in s.char_indices().filter(|&(_, c)| !matches!(c, '\u{2067}' | '\u{2069}')) { + assert!(l.glyphs.iter().any(|g| (g.byte..g.byte + g.len).contains(&i)), "{s}: {c:?} at {i} has no glyph"); + } assert!(!selection_quads(&l, 0, s.len()).is_empty()); } } @@ -432,6 +441,7 @@ fn right_aligned_wrapped_rtl_keeps_trailing_spaces_outside_content() { #[test] fn visual_arrows_cross_rtl_paragraph_boundaries() { let l = text_layout("שלום\nעולם"); + assert_eq!(l.lines.len(), 2); assert!(l.lines.iter().all(|l| l.rtl)); assert_eq!(caret_horizontal(&l, 8, false), 9); assert_eq!(caret_horizontal(&l, 9, true), 8); @@ -492,6 +502,7 @@ fn paragraph_direction_overrides_the_first_strong_character() { #[test] fn left_to_right_text_is_untouched() { let l = text_layout("Plain text, 123 (and more)."); + assert_eq!((l.glyphs.len(), l.lines.len()), ("Plain text, 123 (and more).".len(), 1)); assert!(l.glyphs.iter().all(|g| !g.rtl) && l.lines.iter().all(|l| !l.rtl)); let bytes: Vec<_> = l.glyphs.iter().map(|g| g.byte).collect(); assert!(bytes.windows(2).all(|w| w[0] < w[1])); diff --git a/crates/text/src/tests/ligature_carets.rs b/crates/text/src/tests/ligature_carets.rs index 9189bc2f0b..392c1295a6 100644 --- a/crates/text/src/tests/ligature_carets.rs +++ b/crates/text/src/tests/ligature_carets.rs @@ -529,7 +529,8 @@ fn manual_kerning_moves_a_right_to_left_ligature_stop_with_the_glyph() { fn a_letter_and_its_mark_has_no_inner_stop() { let db = FontDb::with_font_dirs(vec![]); let l = layout(&db, &point("e\u{0301}", "Source Sans 3")); - assert!(l.glyphs.iter().all(|g| g.carets.is_empty()), "{:?}", l.glyphs); + assert!(!l.glyphs.is_empty()); + assert!(l.glyphs.iter().all(|g| (g.byte, g.len) == (0, 3) && g.carets.is_empty()), "{:?}", l.glyphs); } /// On a path, a click on either half of the ligature goes to its nearer stop, and the selection of diff --git a/crates/text/src/tests/path_joins.rs b/crates/text/src/tests/path_joins.rs index 1ac96e3f0f..467b107b9d 100644 --- a/crates/text/src/tests/path_joins.rs +++ b/crates/text/src/tests/path_joins.rs @@ -3,7 +3,7 @@ //! stroke, is the measure. Fonts are installed ones (none is kept in the repository): the tests //! that need an Arabic font say so and stop without one. use crate::*; -use kurbo::{Affine, BezPath, Point, Shape}; +use kurbo::{BezPath, Point, Shape}; use std::sync::Arc; use vectorcraft_doc::{CharStyle, TextKind}; @@ -20,90 +20,6 @@ fn circle(r: f64) -> vectorcraft_geom::PathData { vectorcraft_geom::PathData::from_bezpath(&kurbo::Circle::new((0.0, 0.0), r).to_path(1e-3)) } -/// Type `s` in `style` on a circle of radius `r`, the whole loop for it. -fn on_circle(s: &str, style: CharStyle, r: f64) -> TextLayout { - let mut t = TextObject::point(Point::ZERO, s, style); - t.kind = TextKind::OnPath { path: circle(r), start: 0.25, end: None }; - layout(FontDb::global(), &t) -} - -/// For each pair of neighbouring glyphs on the line (in visual order, inside a word), how far -/// apart the right edge of the left one and the left edge of the right one are, at the baseline -/// and `h` above it. -fn gaps(l: &TextLayout, text: &str, h: f64) -> Vec<(f64, f64)> { - // Visual order: the glyphs as placed, sorted along the line by where their left edge is on it. - let edges: Vec<(Point, Point, Point, Point, usize)> = l - .glyphs - .iter() - .filter(|g| text.get(g.byte..g.byte + g.len).is_some_and(|c| !c.trim().is_empty())) - .map(|g| { - let [a, b, ..] = g.xf.as_coeffs(); - let sx = a.hypot(b); - let w = g.advance / sx; - let up = h / sx; - (g.xf * Point::new(0.0, 0.0), g.xf * Point::new(w, 0.0), g.xf * Point::new(0.0, -up), g.xf * Point::new(w, -up), g.byte) - }) - .collect(); - // Which word a byte is in: the spaces before it. - let word = |b: usize| text.get(..b).map_or(0, |t| t.chars().filter(|c| c.is_whitespace()).count()); - edges.windows(2).filter(|w| word(w[0].4) == word(w[1].4)).map(|w| ((w[0].1 - w[1].0).hypot(), (w[0].3 - w[1].2).hypot())).collect() -} - -/// The largest gaps (baseline, joining height) of type `s` on a circle of radius `r` at `size`. -fn worst(face: &FontFace, s: &str, size: f64, r: f64) -> (f64, f64) { - let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size, ..CharStyle::default() }; - let l = on_circle(s, style, r); - gaps(&l, s, size * 0.25).into_iter().fold((0.0, 0.0), |(a, b), (x, y)| (f64::max(a, x), f64::max(b, y))) -} - -/// The measure, printed: joined Arabic and separate Latin on circles at three sizes. -#[test] -fn joins_on_a_circle_are_measured() { - let Some(face) = arabic_face() else { - eprintln!("SKIPPED: joins_on_a_circle_are_measured; no installed font covers Arabic"); - return; - }; - eprintln!("ASSERTIONS RUN: joins_on_a_circle_are_measured; Arabic font {} {}", face.family, face.style); - for size in [12.0, 29.0, 72.0] { - for r in [60.0, 110.0, 300.0] { - let (b, j) = worst(&face, "سلسلة متصلة", size, r); - let (lb, lj) = worst(&face, "minimum", size, r); - eprintln!("size {size:>4} r {r:>5}: arabic baseline {b:.4} join {j:.4} | latin baseline {lb:.4} at {lj:.4}"); - } - } - let _ = BezPath::new(); - let _ = Affine::IDENTITY; -} - -/// Chord placement, worked out here only (not in the layout): each glyph's baseline ends on the -/// circle, the glyph turned to the chord between them. Neighbours then meet at the baseline, and `h` -/// above it they stand apart by `h` times the angle between their chords, (a_i + a_{i+1}) / 2R. -#[test] -fn chord_placement_leaves_the_join_gap_above_the_baseline() { - let Some(face) = arabic_face() else { - eprintln!("SKIPPED: chord_placement_leaves_the_join_gap_above_the_baseline; no installed font covers Arabic"); - return; - }; - let (size, r) = (29.0, 110.0); - let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size, ..CharStyle::default() }; - let s = "سلسلة"; - let l = on_circle(s, style, r); - let h = size * 0.25; - let advances: Vec = l.glyphs.iter().map(|g| g.advance).filter(|a| *a > 1e-6).collect(); - let mut worst: f64 = 0.0; - for w in advances.windows(2) { - let (a, b) = (w[0], w[1]); - // The chords' directions differ by the angle between their middles on the circle. - let turn = (a + b) / (2.0 * r); - let gap = 2.0 * h * (turn * 0.5).sin(); - let predicted = h * (a + b) / (2.0 * r); - assert!((gap - predicted).abs() < 0.01, "{gap} vs {predicted}"); - worst = worst.max(gap); - } - eprintln!("chord placement at {size} pt on radius {r}: baseline gap 0, join-height gap {worst:.3}"); - assert!(worst > 0.5, "chord placement alone leaves a visible gap: {worst}"); -} - /// A circle of radius `r` run the other way (clockwise): type on it stands on the inside, its /// tops towards the centre, as Flip puts it. fn circle_reversed(r: f64) -> vectorcraft_geom::PathData { diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 246f589518..66ae287023 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -1151,6 +1151,7 @@ fn thai_falls_back_to_a_font_made_for_thai() { let l = layout(db, &TextObject::point(kurbo::Point::ZERO, "Thai ภาษาไทย", st)); let family = |g: &PositionedGlyph| db.face_by_id(g.font_id).map(|f| f.family.clone()).unwrap_or_default(); let (latin, thai_glyphs) = l.glyphs.split_at(5); + assert_eq!(thai_glyphs.len(), "ภาษาไทย".chars().count(), "a glyph for each Thai letter"); assert!(latin.iter().all(|g| family(g) == FALLBACK_FAMILY), "{:?}", latin.iter().map(family).collect::>()); let first = crate::fontdb::THAI_FAMILIES.iter().find(|f| thai_glyphs.iter().all(|g| family(g).eq_ignore_ascii_case(f))); assert!(first.is_some(), "Thai drawn in {:?}; {thai} is installed", thai_glyphs.iter().map(family).collect::>()); diff --git a/crates/three-d/src/shadow/tests.rs b/crates/three-d/src/shadow/tests.rs index f6f9806a43..790d5491c6 100644 --- a/crates/three-d/src/shadow/tests.rs +++ b/crates/three-d/src/shadow/tests.rs @@ -209,7 +209,7 @@ fn every_effect_casts_a_shadow() { assert!(plane.path(Shadow::default()).is_some()); let mut inflate = ShadowCaster::new(); let results = inflate.inflate(&[(&path, FillRule::NonZero)], &[true], bounds, Inflate::default(), View::default()); - assert!(results.iter().all(Result::is_ok)); + assert!(results.len() == 1 && results[0].is_ok(), "one result for the one path"); assert!(inflate.path(Shadow::default()).is_some()); let mut revolve = ShadowCaster::new(); revolve.revolve(&path, FillRule::NonZero, bounds, Revolve::default()).unwrap(); diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index a4db35adb0..570ea28d4d 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -880,7 +880,7 @@ fn inflate_cells_across_a_hole_edge_are_cut_to_the_shape() { let (p, r) = shape(&b); let v = View { rotation_x: -21.88, rotation_y: -23.4, rotation_z: 9.06, ..front() }; let f = inflate(&p, FillRule::EvenOdd, r, Inflate::default(), v).unwrap(); - assert!(f.iter().all(|f| f.contours.len() == 1), "every facet is one piece of the surface"); + assert!(!f.is_empty() && f.iter().all(|f| f.contours.len() == 1), "every facet is one piece of the surface"); // Straight on, the facets still cover exactly the shape. let flat = inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).unwrap(); assert!(close(area(&flat), 220.0 * 220.0 - 100.0 * 90.0, 1e-3), "{}", area(&flat)); diff --git a/crates/three-d/src/solid/tests_face_map.rs b/crates/three-d/src/solid/tests_face_map.rs index ebbe95448a..b0fb4d4717 100644 --- a/crates/three-d/src/solid/tests_face_map.rs +++ b/crates/three-d/src/solid/tests_face_map.rs @@ -77,7 +77,8 @@ fn a_plane_has_only_a_front_and_a_hollow_solid_none() { let hollow = Extrude { cap: false, ..Extrude::default() }; assert_eq!(extrude_face_map(bounds, hollow, view, PlanarFace::Front), None); let facets = extrude(&path, FillRule::NonZero, bounds, hollow, view).unwrap(); - assert!(facets.iter().all(|f| f.end.is_none())); + // A hollow extrusion still draws its sides, and none of them is an end. + assert!(!facets.is_empty() && facets.iter().all(|f| f.end.is_none())); } #[test] diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index 069013c808..46cf515f08 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -181,7 +181,7 @@ fn perspective_runs_0_to_160_degrees_with_the_eye_outside_the_object() { assert!(eyes.windows(2).all(|w| w[0] > w[1]), "{eyes:?}"); let (p, b) = cylinder(); let wide = revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 160.0, ..Default::default() }).unwrap(); - assert!(wide.iter().flat_map(|f| &f.points).all(|q| q.x.is_finite() && q.y.is_finite())); + assert!(!wide.is_empty() && wide.iter().flat_map(|f| &f.points).all(|q| q.x.is_finite() && q.y.is_finite())); assert_eq!(wide, revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 400.0, ..Default::default() }).unwrap()); } #[test] diff --git a/crates/three-d/src/tests/classic.rs b/crates/three-d/src/tests/classic.rs index f460297453..fc0b703741 100644 --- a/crates/three-d/src/tests/classic.rs +++ b/crates/three-d/src/tests/classic.rs @@ -87,10 +87,8 @@ fn blend_steps_round_the_shading_to_that_many_levels() { } #[test] -fn surfaces_round_trip_through_their_ids() { - for surface in ClassicSurface::ALL { - assert_eq!(ClassicSurface::parse(surface.id()), Some(surface)); - } +fn surfaces_parse_from_their_ids() { + assert_eq!(ClassicSurface::parse("none"), Some(ClassicSurface::NoShading)); assert_eq!(ClassicSurface::parse("glossy"), None); assert_eq!(ClassicSurface::default(), ClassicSurface::Plastic); } diff --git a/crates/tools/src/distort/arap.rs b/crates/tools/src/distort/arap.rs index 10c355544c..4740bf556a 100644 --- a/crates/tools/src/distort/arap.rs +++ b/crates/tools/src/distort/arap.rs @@ -758,11 +758,12 @@ mod tests { }; // One pin, held at 0.4 rad: the whole shape turns rigidly around it. let d = deform(&m, &[Pin { angle: Some(0.4), ..Pin::new(c, c) }]); + assert!(!m.verts.is_empty() && d.len() == m.verts.len(), "{} of {}", d.len(), m.verts.len()); let err = m.verts.iter().zip(&d).map(|(a, b)| rot(*a).distance(*b)).fold(0.0, f64::max); assert!(err < 0.05, "{err}"); // A free pin alone leaves the shape where it is. let d = deform(&m, &[Pin::new(c, c)]); - assert!(m.verts.iter().zip(&d).all(|(a, b)| a.distance(*b) < 1e-3)); + assert!(d.len() == m.verts.len() && m.verts.iter().zip(&d).all(|(a, b)| a.distance(*b) < 1e-3)); // Held ends: the turned end turns, the other end stays. let left = Point::new(10.0, 50.0); let pins = [Pin { angle: Some(0.5), ..Pin::new(left, left) }, Pin::new(Point::new(190.0, 50.0), Point::new(190.0, 50.0))]; diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index c8aa002add..41e378649c 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3752,7 +3752,8 @@ fn the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_durin press(&mut t, upright, 0.5, PointerKind::Drag, 150.0); near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); let released = t.stroke_json(); - assert!(released.as_array().is_some_and(|a| a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); + // One entry per press so far (the press and two drags), each of three numbers. + assert!(released.as_array().is_some_and(|a| a.len() == 3 && a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); press(&mut t, upright, 0.5, PointerKind::Up, 150.0); } diff --git a/crates/tools/src/params.rs b/crates/tools/src/params.rs index c7a205a19e..9fe1fb2138 100644 --- a/crates/tools/src/params.rs +++ b/crates/tools/src/params.rs @@ -79,7 +79,7 @@ pub fn gradient_params(g: &GradientPaint) -> Value { v["method"] = json!(g.gradient.method.id()); } // A freeform gradient has no ends to spread past (`paint.setFill` refuses a spread for one). - if g.gradient.is_spread() { + if !g.gradient.spread.is_pad() && g.gradient.kind != vectorcraft_color::GradientKind::Freeform { v["spread"] = json!(g.gradient.spread.label().to_lowercase()); } // A gradient that pads keeps its count for later. diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 34311e9d96..f182ce3787 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -139,9 +139,7 @@ fn actions_cycle_and_name_themselves() { assert_eq!(Stroke::Line.next(), Stroke::ContinuousArc); assert_eq!(Stroke::ContinuousArc.next(), Stroke::SharpArc); assert_eq!(Stroke::SharpArc.next(), Stroke::Line); - for s in Stroke::ALL { - assert_eq!(Stroke::parse(s.name()), Some(s)); - } + assert_eq!(Stroke::parse("sharpArc"), Some(Stroke::SharpArc)); assert_eq!(Stroke::parse("arc"), None); } diff --git a/crates/trace/src/group.rs b/crates/trace/src/group.rs index a0e3b85020..1050166631 100644 --- a/crates/trace/src/group.rs +++ b/crates/trace/src/group.rs @@ -451,7 +451,9 @@ mod tests { let want = parents_by_pairs(&paths, 200, 200, stacked); let pairs = BOX_TESTS.with(std::cell::Cell::get); assert_eq!(found, want, "stacked {stacked}"); - assert!(want.iter().skip(1).all(Option::is_some), "stacked {stacked}: {want:?}"); + // Each disc lies inside the one below it, the smallest that holds it. + let chain: Vec> = (0..paths.len()).map(|i| i.checked_sub(1)).collect(); + assert_eq!(want, chain, "stacked {stacked}"); assert!(tests <= pairs, "stacked {stacked}: {tests} box tests, {pairs} by pairs"); } } diff --git a/crates/trace/src/logo/restore.rs b/crates/trace/src/logo/restore.rs index 984a073f64..908d98923d 100644 --- a/crates/trace/src/logo/restore.rs +++ b/crates/trace/src/logo/restore.rs @@ -189,7 +189,13 @@ mod tests { } let (r, step) = resample_closed(&pts, 0.12).expect("resample"); let s0 = smooth_closed(&r, 0.18 / step); - let _ = restore_corners(&r, &s0, step, &RestoreParams { min_turn: 30.0, ..RestoreParams::default() }); + // The bend at (20, 0) is a candidate (turn 10), and only the minimum turn decides it. + let bend = |min_turn: f64| { + let (out, forced) = restore_corners(&r, &s0, step, &RestoreParams { turn: 10.0, min_turn, ..RestoreParams::default() }); + forced.iter().map(|&i| out[i].distance(Point::new(20.0, 0.0))).fold(f64::MAX, f64::min) + }; + assert!(bend(30.0) > 1.0, "a 20 degree bend under a 30 degree minimum: {} px from a corner", bend(30.0)); + assert!(bend(10.0) < 0.1, "under a 10 degree minimum it is one: {} px off", bend(10.0)); } #[test] diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 3fd5c2000b..b834ea4b4a 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -912,11 +912,11 @@ fn snap_curves_to_lines_straightens_near_lines() { #[test] fn presets_resolve() { - assert_eq!(presets().len(), 15); - for n in PRESET_NAMES { - assert!(preset(n).is_some(), "{n}"); - } - assert!(preset("[Default]").is_some()); + // Every name resolves: `presets` leaves out a name `preset` does not know. + assert_eq!(PRESET_NAMES.len(), 15); + assert_eq!(presets().len(), PRESET_NAMES.len()); + assert_eq!(preset("[Default]"), preset("Default")); + assert_eq!(preset(" Line Art "), preset("line art")); assert_eq!(preset("16 colors").unwrap().colors, 16); assert_eq!(preset("Shades of Gray").unwrap().mode, Mode::Grayscale); assert_eq!(preset("flat logo").unwrap().mode, Mode::Logo); diff --git a/crates/ui-egui/src/addons/cutting/tests.rs b/crates/ui-egui/src/addons/cutting/tests.rs index b177f72604..a22e907c04 100644 --- a/crates/ui-egui/src/addons/cutting/tests.rs +++ b/crates/ui-egui/src/addons/cutting/tests.rs @@ -35,10 +35,6 @@ fn rect(app: &mut VectorcraftApp, x: f64, y: f64, width: f64, height: f64) -> u6 id_of(app.run("shape.rectangle", json!({"x": x, "y": y, "width": width, "height": height})).unwrap()) } -fn circle(app: &mut VectorcraftApp, cx: f64, cy: f64, r: f64) -> u64 { - id_of(app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) -} - fn select(app: &mut VectorcraftApp, ids: &[u64]) { app.run("select.set", json!({ "ids": ids })).unwrap(); } @@ -224,35 +220,6 @@ fn each_addon_dialog_opens_on_its_items_values_and_runs_its_command() { assert!(b > a, "the second object lies right of the first: {a}, {b}"); }, }, - Row { - name: "common tangents", - menu: "Path Precision Tools", - label: "Common Tangents…", - command: crate::addons::pathtools::COMMON_TANGENTS, - setup: |app| { - let (a, b) = (circle(app, 60.0, 150.0, 20.0), circle(app, 220.0, 150.0, 40.0)); - select(app, &[a, b]); - }, - opens: || json!({"tangents": "all", "centerline": false}), - set: || json!({}), - check: |app, start| { - assert_eq!(nodes(app), start.node_count() + 4, "four tangent lines"); - // Each kind the list offers is one the command takes. - for (_, kind) in crate::addons::pathtools::TANGENT_KINDS { - let params = json!({"tangents": kind}); - assert!(vectorcraft_engine::check_params(crate::addons::pathtools::COMMON_TANGENTS, ¶ms).is_ok(), "{kind}"); - } - // A circle inside another: nothing changes, and a message says why. - let ids = children(start); - let inner = circle(app, 220.0, 150.0, 10.0); - select(app, &[ids[1], inner]); - let (n, count) = (steps(app), nodes(app)); - open_item(app, "Path Precision Tools", "Common Tangents…"); - answer(app, true); - assert_eq!((steps(app), nodes(app)), (n, count)); - assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); - }, - }, Row { name: "add bounding rectangle", menu: "Path Precision Tools", diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 4abd73e430..a607911e16 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -104,7 +104,8 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option Result = match id { pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, - pathtools::bridge::COMMAND => pathtools::bridge::open, + pathtools::COMMON_TANGENTS => pathtools::tangents::open, + pathtools::tangents::BRIDGE => pathtools::tangents::open_connected, pathtools::tangent_circle::COMMAND => pathtools::tangent_circle::open, typetools::COMMAND => typetools::open, color::legend::COMMAND => color::legend::open, diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index c0d1c572f2..dc2372552e 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -183,10 +183,10 @@ fn rows() -> Vec { }, Row { group: "Path Precision Tools", - label: "Smooth Bridge…", + label: "Common Tangents…", setup: two_circles, refused: Vec::new, - values: || vec![("keepOriginals", json!(true))], + values: || vec![("tangents", json!("external")), ("sides", json!("curved")), ("keepOriginals", json!(true))], check: |app| assert_eq!(count(app), 3, "the circles and the outline above them"), }, Row { diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 324f907615..2cb01c3e29 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Common Tangents… (the tangent lines, or circles connected along them, [`tangents`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog @@ -8,7 +8,6 @@ //! dialog draws its circle with `shape.circleThroughPoints`. Canceling an Anchor Inspector field edit restores its //! opening value: an anchor edit is one undo step that the cancel takes back. -pub mod bridge; pub mod corner; pub mod dashes; pub mod set_corners; @@ -16,6 +15,7 @@ pub mod shape; pub mod shared_edge; pub mod tangent_circle; pub mod tangent_circle_radius; +pub mod tangents; use craft::behavior::{ColumnWidth, EditEvents}; use craft::menu::Node; @@ -45,7 +45,7 @@ use crate::{VectorcraftApp, fields}; pub const ID: &str = "anchorInspector"; /// The tools' options dialog. pub const KIND: &str = "pathToolOptions"; -/// Common Tangents' command, whose menu item opens the command dialog with a Preview. +/// Common Tangents' command, whose menu item opens its dialog ([`tangents`]). pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; /// The kinds of tangent Common Tangents' `tangents` picks, and their labels. pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; @@ -143,10 +143,9 @@ pub fn menu() -> Vec { cp("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), c("Divide into Dashes…", dashes::COMMAND), cp("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), - c("Smooth Bridge…", bridge::COMMAND), cp("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), c("Tangent Circle…", tangent_circle::COMMAND), - cp("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), + c("Common Tangents…", COMMON_TANGENTS), cp("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), cp("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), cp("Add Inscribed Circle", INSCRIBED_CIRCLE, json!({})), diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs deleted file mode 100644 index 5ddeee621b..0000000000 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller -//! circle's radius, or with Constant Gap that radius plus a gap; the reach, unavailable with two -//! circles selected; Keep Originals), which previews on the canvas and runs -//! `addon.pathtools.bridge` on OK. - -use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; -use craft::ui::runtime::env::UnitKind; -use serde_json::{Value, json}; - -use crate::VectorcraftApp; -use crate::addons::dialogs::{self, Spec}; -use crate::canvas::rulers::general_lengths; - -/// The command. -pub const COMMAND: &str = "addon.pathtools.bridge"; -/// The radius the command takes (%), and its default. -const RADII: std::ops::RangeInclusive = 1.0..=1000.0; -const RADIUS: f64 = 100.0; -/// The gap the command takes (pt), and the dialog's first one. -const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; -const GAP: f64 = 4.0; -/// The reach the command takes (pt), and its default. -const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; -const REACH: f64 = 10.0; - -/// How the dialog's values reach the command. -pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None }; - -/// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap. -fn params(fields: &DialogFields) -> Value { - let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); - if fields.bool("constantGap").unwrap_or(false) { - json!({ "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) - } else { - json!({ "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) - } -} - -/// Opens Smooth Bridge's dialog on the command's defaults. -pub(crate) fn open(app: &mut VectorcraftApp) -> Result { - // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview - // replaces the selection with its result, with a selected group counting the objects inside it. - let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); - let fields = DialogFields::from_pairs([ - ("radius", FieldValue::Number(RADIUS)), - ("constantGap", FieldValue::Bool(false)), - ("gap", FieldValue::Number(GAP)), - ("reach", FieldValue::Number(REACH)), - ("keepOriginals", FieldValue::Bool(false)), - ("many", FieldValue::Bool(many)), - ]); - let lengths = general_lengths(app); - dialogs::open(app, &SPEC, fields, move |fields| { - let rows = vec![ - Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)), - Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) - .length(lengths) - .bounds(Some(*GAPS.start()), Some(*GAPS.end())) - .visible_when("constantGap", FieldValue::Bool(true)), - Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) - .unit(UnitKind::Percent) - .bounds(Some(*RADII.start()), Some(*RADII.end())) - .visible_when("constantGap", FieldValue::Bool(false)), - Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) - .length(lengths) - .bounds(Some(*REACHES.start()), Some(*REACHES.end())) - .enabled_when("many", FieldValue::Bool(true)), - Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)), - ]; - ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields)) - }) -} - -/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the -/// objects inside it, at any depth; an object given twice, or with its group, counts once. -fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { - fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet) { - match &n.kind { - vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), - _ => { - out.insert(n.id); - } - } - } - let mut out = std::collections::BTreeSet::new(); - for n in ids.iter().filter_map(|&id| doc.node(id)) { - visit(n, &mut out); - } - out.len() -} - -#[cfg(test)] -mod tests { - use serde_json::{Value, json}; - use vectorcraft_engine::Session; - - use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; - use crate::{VectorcraftApp, menus}; - - fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { - app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() - } - - fn bridge_app(xs: &[f64]) -> VectorcraftApp { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({"ids": ids})).unwrap(); - app - } - - fn geometry(app: &VectorcraftApp) -> Vec { - app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() - } - - fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) { - panel.click(label); - panel.key(egui::Key::A, egui::Modifiers::COMMAND); - panel.type_text(text); - panel.key(egui::Key::Tab, egui::Modifiers::NONE); - panel.frame(); - } - - #[test] - fn real_bridge_controls_change_the_preview_and_confirmed_geometry() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs); - let before = panel.app().session.doc().unwrap().history.undo.len(); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); - panel.click("Keep Originals"); - type_number(&mut panel, "Radius", "150"); - let id = dialog_id(&panel.app()); - assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); - - panel.click("Constant Gap"); - type_number(&mut panel, "Gap", "6"); - let params = read(&panel.app(), id, super::params); - assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true})); - let mut expected = bridge_app(&[100.0, 124.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - let preview = geometry(&panel.app()); - assert_eq!(preview, geometry(&expected)); - panel.click("OK"); - panel.frame(); - assert_eq!(geometry(&panel.app()), preview); - assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1); - assert!(!panel.app().any_dialog_open()); - } - - #[test] - fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { - use crate::tests::panel_harness::Panel; - - let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs); - let original = geometry(&panel.app()); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(panel.enabled("Reach")); - type_number(&mut panel, "Reach", "5"); - let id = dialog_id(&panel.app()); - let params = read(&panel.app(), id, super::params); - assert_eq!(params["reach"], 5.0); - let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]); - expected.session.execute(super::COMMAND, ¶ms).unwrap(); - assert_eq!(geometry(&panel.app()), geometry(&expected)); - panel.click("Cancel"); - panel.frame(); - assert_eq!(geometry(&panel.app()), original); - } - - #[test] - fn reach_counts_the_circles_inside_a_selected_group() { - use crate::tests::panel_harness::Panel; - - for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { - let mut app = bridge_app(xs); - let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); - let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [group]})).unwrap(); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); - panel.click("OK"); - panel.frame(); - let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); - assert_eq!(inside, 1, "the circles in the group became one shape"); - } - // A group of two circles selected together with one of them: still two circles. - let mut app = bridge_app(&[100.0, 124.0]); - let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); - let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); - } - - #[test] - fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - // Three circles 4 apart in a row and one far off. - let ids: Vec = [100.0, 124.0, 148.0, 300.0].iter().map(|&x| circle(&mut app, x, 10.0)).collect(); - app.run("select.set", json!({ "ids": ids })).unwrap(); - menus::invoke(&mut app, super::COMMAND, Value::Null); - let dialog = dialog_id(&app); - set(&app, dialog, "constantGap", json!(true)); - // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the - // four circles the command still bridges. - frame(&mut app); - assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); - let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); - assert_eq!(many, Some(true), "Reach available for four circles"); - assert_eq!(params, json!({"gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); - assert!(confirm(&app, dialog), "OK is on"); - frame(&mut app); - let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); - assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); - } - - #[test] - fn the_status_line_says_why_an_ellipse_is_refused() { - use crate::tests::panel_harness::Panel; - - let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let a = circle(&mut app, 100.0, 10.0); - let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); - app.run("select.set", json!({"ids": [a, oval]})).unwrap(); - let original = geometry(&app); - let mut panel = Panel::new(app, crate::tests::picks::dialogs); - let before = panel.app().session.doc().unwrap().history.undo.len(); - menus::invoke(&mut panel.app(), super::COMMAND, Value::Null); - panel.frame(); - let why = "an ellipse whose width and height differ is not a circle"; - assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); - panel.click("OK"); - panel.frame(); - assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); - assert_eq!(geometry(&panel.app()), original); - assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before, "no undo step"); - } -} diff --git a/crates/ui-egui/src/addons/pathtools/tangents.rs b/crates/ui-egui/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..1c1587a0d5 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents.rs @@ -0,0 +1,150 @@ +//! Common Tangents in the interface: one dialog for the tangent lines of two shapes and for circles joined by a smooth +//! bridge. It picks the kind of tangent, the centerline and Connect tangents (the two tangents of each kind joined into +//! one closed shape). With External, Straight keeps the tangent lines and Curved joins the circles along concave arcs +//! instead (the arcs' radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a +//! gap; the reach, unavailable with two circles selected; Keep Originals), as `addon.pathtools.bridge` does. It +//! previews on the canvas and runs `addon.pathtools.commonTangents` on OK. Smooth Bridge's command id opens the same +//! dialog with External and Curved on. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; +use craft::ui::runtime::env::UnitKind; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::{self, Spec}; +use crate::canvas::rulers::general_lengths; + +use super::{COMMON_TANGENTS, TANGENT_KINDS}; + +/// Smooth Bridge's command, which opens this dialog with External and Curved on. +pub const BRIDGE: &str = "addon.pathtools.bridge"; +/// The kind of tangent the dialog opens with. +const TANGENTS: &str = "all"; +/// The tangents that Curved replaces with arcs. +const EXTERNAL: &str = "external"; +/// What joins the circles with External, and its labels; the first is the default. +const SIDES: [(&str, &str); 2] = [("straight", "Straight"), ("curved", "Curved")]; +/// The radius the command takes (%), and its default. +const RADII: std::ops::RangeInclusive = 1.0..=1000.0; +const RADIUS: f64 = 100.0; +/// The gap the command takes (pt), and the dialog's first one. +const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; +const GAP: f64 = 4.0; +/// The reach the command takes (pt), and its default. +const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; +const REACH: f64 = 10.0; + +/// How the dialog's values reach the command. +pub(crate) static SPEC: Spec = Spec { command: COMMON_TANGENTS, params, found: None }; + +/// Whether the fields ask for a curved bridge: External with Curved. +fn curved(fields: &DialogFields) -> bool { + fields.text("tangents") == Some(EXTERNAL) && fields.text("sides") == Some("curved") +} + +/// The command's parameters from the dialog's fields: the tangent lines' kind, centerline and Connect tangents, or for +/// a curved bridge the radius (or with Constant Gap the gap), the reach and Keep Originals. +fn params(fields: &DialogFields) -> Value { + if !curved(fields) { + return json!({ + "tangents": fields.text("tangents").unwrap_or(TANGENTS), + "centerline": fields.bool("centerline").unwrap_or(false), + "connect": fields.bool("connect").unwrap_or(false), + }); + } + let (reach, keep) = (fields.number("reach").unwrap_or(REACH), fields.bool("keepOriginals").unwrap_or(false)); + if fields.bool("constantGap").unwrap_or(false) { + json!({ "tangents": EXTERNAL, "curved": true, "gap": fields.number("gap").unwrap_or(GAP), "reach": reach, "keepOriginals": keep }) + } else { + json!({ "tangents": EXTERNAL, "curved": true, "radius": fields.number("radius").unwrap_or(RADIUS), "reach": reach, "keepOriginals": keep }) + } +} + +/// Opens Common Tangents' dialog for the tangent lines. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + open_with(app, false) +} + +/// Opens Common Tangents' dialog with External and Curved on, for Smooth Bridge's command. +pub(crate) fn open_connected(app: &mut VectorcraftApp) -> Result { + open_with(app, true) +} + +fn open_with(app: &mut VectorcraftApp, bridge: bool) -> Result { + // The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview + // replaces the selection with its result, with a selected group counting the objects inside it. + let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true); + let fields = DialogFields::from_pairs([ + ("tangents", FieldValue::from(if bridge { EXTERNAL } else { TANGENTS })), + ("centerline", FieldValue::Bool(false)), + ("connect", FieldValue::Bool(bridge)), + ("sides", FieldValue::from(if bridge { "curved" } else { "straight" })), + ("constantGap", FieldValue::Bool(false)), + ("radius", FieldValue::Number(RADIUS)), + ("gap", FieldValue::Number(GAP)), + ("reach", FieldValue::Number(REACH)), + ("keepOriginals", FieldValue::Bool(false)), + ("many", FieldValue::Bool(many)), + ]); + let lengths = general_lengths(app); + dialogs::open(app, &SPEC, fields, move |fields| { + let kinds = TANGENT_KINDS.iter().map(|(label, id)| ((*id).to_owned(), tl!(label).into())).collect(); + let sides = SIDES.iter().map(|(id, label)| ((*id).to_owned(), tl!(label).into())).collect(); + let curved = || ["curved"]; + // Picking another kind of tangent goes back to Straight, so Curved only holds while External does. + let rows = vec![ + Param::new("tangents", tl!("Tangents:"), ParamKind::choice(kinds, Some(TANGENTS.to_owned()))).resets(["sides"]), + Param::new("centerline", tl!("Centerline"), ParamKind::bool(false)).enabled_when("sides", "straight"), + // A curved bridge is always connected. + Param::new("connect", tl!("Connect tangents"), ParamKind::bool(false)).enabled_when("sides", "straight").disabled_value(true), + Param::new("sides", tl!("Sides"), ParamKind::radio(sides, Some(SIDES[0].0.to_owned()))).visible_when("tangents", EXTERNAL), + Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + Param::number("gap", tl!("Gap:"), GAP, 1.0, 2) + .length(lengths) + .bounds(Some(*GAPS.start()), Some(*GAPS.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [true]) + .enabled_when_in("sides", curved()), + Param::number("radius", tl!("Radius:"), RADIUS, 1.0, 0) + .unit(UnitKind::Percent) + .bounds(Some(*RADII.start()), Some(*RADII.end())) + .visible_when("tangents", EXTERNAL) + .visible_when_in("constantGap", [false]) + .enabled_when_in("sides", curved()), + Param::number("reach", tl!("Reach:"), REACH, 1.0, 2) + .length(lengths) + .bounds(Some(*REACHES.start()), Some(*REACHES.end())) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()) + .and_enabled_when_in("many", [true]), + Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)) + .visible_when("tangents", EXTERNAL) + .enabled_when_in("sides", curved()), + ]; + ParamDialog::new(COMMON_TANGENTS, tl!("Common Tangents"), rows).previews(true).values(Bind::bound(fields)) + }) +} + +/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the +/// objects inside it, at any depth; an object given twice, or with its group, counts once. +fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize { + fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet) { + match &n.kind { + vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)), + _ => { + out.insert(n.id); + } + } + } + let mut out = std::collections::BTreeSet::new(); + for n in ids.iter().filter_map(|&id| doc.node(id)) { + visit(n, &mut out); + } + out.len() +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/pathtools/tangents/tests.rs b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..c3f1b84163 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangents/tests.rs @@ -0,0 +1,244 @@ +//! Common Tangents' dialog: the tangent lines, Connect tangents, External's Straight or Curved bridge, Smooth +//! Bridge's command opening it curved, the reach's availability, Cancel and the refusals on the status line. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::{BRIDGE, COMMON_TANGENTS}; +use crate::addons::dialogs::tests::{confirm, dialog_id, frame, read, set}; +use crate::tests::panel_harness::Panel; +use crate::{VectorcraftApp, menus}; + +fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() +} + +fn circles_app(xs: &[f64]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + app +} + +fn geometry(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +fn type_number(panel: &mut Panel, label: &str, text: &str) { + panel.click(label); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); +} + +/// The geometry the command makes on `xs`'s circles with `params`. +fn expected(xs: &[f64], params: &Value) -> Vec { + let mut app = circles_app(xs); + app.session.execute(COMMON_TANGENTS, params).unwrap(); + geometry(&app) +} + +#[test] +fn the_menu_item_adds_the_tangent_lines_and_only_their_options_take_input() { + let xs = [100.0, 200.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + assert!(panel.enabled("Centerline") && panel.enabled("Tangents") && panel.enabled("Connect tangents")); + assert!(!panel.shows("Radius") && !panel.shows("Straight"), "the bridge's options wait for External"); + panel.click("Centerline"); + panel.frame(); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "all", "centerline": true, "connect": false})); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms), "the preview"); + assert_eq!(geometry(&panel.app()).len(), 2 + 5, "four tangents and the centerline beside the circles"); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn external_shows_straight_or_curved_and_curved_takes_the_bridge_options() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + let id = dialog_id(&panel.app()); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + assert!(panel.shows("Straight") && panel.shows("Radius"), "External shows the bridge's options"); + assert!(!panel.enabled("Radius") && !panel.enabled("Keep Originals"), "Straight keeps them unavailable"); + panel.click("Connect tangents"); + panel.frame(); + let straight = read(&panel.app(), id, super::params); + assert_eq!(straight, json!({"tangents": "external", "centerline": false, "connect": true})); + assert_eq!(geometry(&panel.app()), expected(&xs, &straight)); + assert_eq!(geometry(&panel.app()).len(), 3, "the circles and one closed shape"); + + panel.click("Curved"); + panel.frame(); + assert!(panel.enabled("Radius") && panel.enabled("Keep Originals") && !panel.enabled("Centerline")); + let curved = read(&panel.app(), id, super::params); + assert_eq!(curved, json!({"tangents": "external", "curved": true, "radius": 100.0, "reach": 10.0, "keepOriginals": false})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, &curved)); + assert_eq!(preview.len(), 1, "the bridge replaces the circles"); + + // Another kind of tangent goes back to Straight and the lines' options. + set(&panel.app(), id, "tangents", json!("internal")); + panel.frame(); + assert!(panel.enabled("Centerline") && !panel.shows("Curved")); + assert_eq!(read(&panel.app(), id, super::params)["tangents"], "internal"); + set(&panel.app(), id, "tangents", json!("external")); + panel.frame(); + panel.click("Curved"); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1, "one undo step"); +} + +#[test] +fn the_bridge_command_opens_the_dialog_connected_and_its_controls_reach_the_command() { + let xs = [100.0, 124.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Radius"), "External and Curved are on"); + assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance"); + panel.click("Keep Originals"); + type_number(&mut panel, "Radius", "150"); + let id = dialog_id(&panel.app()); + assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0)); + let mut old = circles_app(&xs); + old.session.execute(BRIDGE, &json!({"radius": 150, "keepOriginals": true})).unwrap(); + assert_eq!(geometry(&panel.app()), geometry(&old), "the same outline Smooth Bridge makes"); + assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge"); + + panel.click("Constant Gap"); + type_number(&mut panel, "Gap", "6"); + let params = read(&panel.app(), id, super::params); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 6.0, "reach": 10.0, "keepOriginals": true})); + let preview = geometry(&panel.app()); + assert_eq!(preview, expected(&xs, ¶ms)); + panel.click("OK"); + panel.frame(); + assert_eq!(geometry(&panel.app()), preview); + assert_eq!(steps(&panel.app()), before + 1); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn a_reach_edit_reaches_the_command_and_cancel_restores_the_originals() { + let xs = [100.0, 124.0, 148.0, 300.0]; + let mut panel = Panel::new(circles_app(&xs), crate::tests::picks::dialogs); + let original = geometry(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(panel.enabled("Reach")); + type_number(&mut panel, "Reach", "5"); + let id = dialog_id(&panel.app()); + let params = read(&panel.app(), id, super::params); + assert_eq!(params["reach"], 5.0); + assert_eq!(geometry(&panel.app()), expected(&xs, ¶ms)); + panel.click("Cancel"); + panel.frame(); + assert_eq!(geometry(&panel.app()), original); +} + +#[test] +fn reach_counts_the_circles_inside_a_selected_group() { + for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] { + let mut app = circles_app(xs); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len()); + panel.click("OK"); + panel.frame(); + let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len(); + assert_eq!(inside, 1, "the circles in the group became one shape"); + } + // A group of two circles selected together with one of them: still two circles. + let mut app = circles_app(&[100.0, 124.0]); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + assert!(!panel.enabled("Reach"), "a circle selected with its group counts once"); +} + +#[test] +fn constant_gap_bridges_many_circles_within_reach() { + let mut app = circles_app(&[100.0, 124.0, 148.0, 300.0]); + let ids: Vec = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + menus::invoke(&mut app, BRIDGE, Value::Null); + let dialog = dialog_id(&app); + set(&app, dialog, "constantGap", json!(true)); + // A preview leaves two objects selected (one shape and the far circle); Reach stays available for the four + // circles the command still bridges. + frame(&mut app); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); + let (many, params) = read(&app, dialog, |fields| (fields.bool("many"), (super::SPEC.params)(fields))); + assert_eq!(many, Some(true), "Reach available for four circles"); + assert_eq!(params, json!({"tangents": "external", "curved": true, "gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); + assert!(confirm(&app, dialog), "OK is on"); + frame(&mut app); + let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); +} + +#[test] +fn the_status_line_says_why_a_selection_is_refused() { + // Connected: an ellipse is not a circle. + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = circle(&mut app, 100.0, 10.0); + let oval = app.run("shape.ellipse", json!({"x": 130, "y": 90, "width": 20, "height": 21})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, oval]})).unwrap(); + let original = geometry(&app); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + menus::invoke(&mut panel.app(), BRIDGE, Value::Null); + panel.frame(); + let why = "an ellipse whose width and height differ is not a circle"; + assert!(panel.app().ui.status.contains(why), "the preview's refusal: {}", panel.app().ui.status); + panel.click("OK"); + panel.frame(); + assert!(panel.app().ui.status.contains(why), "OK's refusal: {}", panel.app().ui.status); + assert_eq!(geometry(&panel.app()), original); + assert_eq!(steps(&panel.app()), before, "no undo step"); + + // The lines: a circle inside another has none, and the warning says so. + let mut app = circles_app(&[150.0]); + let outer = app.run("shape.ellipse", json!({"x": 100, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let inner = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + app.run("select.set", json!({"ids": [inner, outer]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + let count = geometry(&panel.app()).len(); + menus::invoke(&mut panel.app(), COMMON_TANGENTS, Value::Null); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(steps(&panel.app()), before); + assert_eq!(geometry(&panel.app()).len(), count); + assert!(panel.app().ui.status.contains("inside the other"), "{}", panel.app().ui.status); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6d8741d342..6be16732f6 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -349,8 +349,7 @@ fn heading_in(lang: crate::i18n::Lang, label: &str) -> String { /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and /// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path -/// Precision Tools › Common Tangents and the bounding shapes (Add Bounding Rectangle… and Add -/// Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) +/// Precision Tools' bounding shapes (Add Bounding Rectangle… and Add Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) fn previews(command: &str, opening: &Map) -> bool { match command { "object.repeat.options" => opening.contains_key("gridType"), @@ -361,7 +360,6 @@ fn previews(command: &str, opening: &Map) -> bool { | crate::addons::cutting::WEED | crate::addons::cutting::BANNER | crate::addons::cutting::NEST - | crate::addons::pathtools::COMMON_TANGENTS | crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => true, _ => false, @@ -465,7 +463,6 @@ fn order(command: &str) -> &'static [&'static str] { } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], - crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], "object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"], _ => &[], @@ -484,7 +481,6 @@ fn choices(command: &str, key: &str) -> Option { ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), (crate::addons::cutting::WEED, "direction") => Some(crate::addons::cutting::WEED_DIRECTIONS), - (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), ("object.rasterize", "antiAlias") => Some(RASTERIZE_ANTI_ALIAS), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fefe9f05aa..b4cf91497d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1544,7 +1544,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 017486e7ad..98f7ac967d 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -2786,4 +2786,17 @@ mod tests { } } } + + /// Smooth Bridge is part of Common Tangents (#10465): the palette lists Common Tangents once, a search for + /// "metaball" or "smooth bridge" finds it, and Smooth Bridge's own command is no result. + #[test] + fn a_search_for_metaball_finds_common_tangents_and_not_smooth_bridge() { + let app = app_on(Session::new()); + let built = built_for(&app); + assert!(built.entries.iter().all(|e| !e.ids().iter().any(|id| id == "addon.pathtools.bridge")), "Smooth Bridge is no result"); + for query in ["metaball", "smooth bridge"] { + let found = ranked(&built, query); + assert_eq!(found.first().map(String::as_str), Some(crate::addons::pathtools::COMMON_TANGENTS), "{query}: {found:?}"); + } + } } diff --git a/crates/ui-egui/src/panels/actions/tests_files.rs b/crates/ui-egui/src/panels/actions/tests_files.rs index a88cbc36fe..396c3d6af9 100644 --- a/crates/ui-egui/src/panels/actions/tests_files.rs +++ b/crates/ui-egui/src/panels/actions/tests_files.rs @@ -53,12 +53,24 @@ fn browser_picks_load_and_replace_action_sets_without_a_file_reader() { } } +/// Each built-in action plays on a selection it applies to (text for Outline Text, two +/// overlapping rectangles otherwise) and edits the drawing, so its commands and their +/// parameters are ones the engine accepts. #[test] -fn defaults_are_valid_commands() { - for a in default_sets().actions { - for step in a.steps { - assert!(vectorcraft_engine::find_command(&step.command).is_some(), "{}", step.command); - } +fn built_in_actions_play_and_edit_the_drawing() { + for (idx, a) in default_sets().actions.iter().enumerate() { + let mut app = new_app(); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let ids: Vec = if a.steps.iter().any(|s| s.command.starts_with("type.")) { + vec![app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab"})).unwrap()["id"].clone()] + } else { + [10, 30].iter().map(|x| app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].clone()).collect() + }; + app.run("select.set", json!({ "ids": ids })).unwrap(); + app.ui.actions = default_list(); + let before = undo_steps(&app); + play(&mut app, 0, idx).unwrap_or_else(|e| panic!("{}: {e}", a.name)); + assert!(undo_steps(&app) > before, "{} edits the drawing", a.name); } } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 6713eb3033..d1f6be332e 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -7,6 +7,18 @@ use vectorcraft_doc::text::TypeAntiAlias; use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; use vectorcraft_engine::Session; +/// The different values in `items`, in the order they first appear: `[v]` when every item is `v`, +/// and empty when there are no items. +fn distinct(items: impl IntoIterator) -> Vec { + let mut out = Vec::new(); + for item in items { + if !out.contains(&item) { + out.push(item); + } + } + out +} + /// `value` is `want` (the panel's fields are single precision). fn near(value: Option, want: f64) -> bool { value.is_some_and(|v| (f64::from(v) - want).abs() < 1e-6) @@ -844,14 +856,16 @@ fn underline_command_underlines_a_mixed_selection() { let id = app.run("text.create", json!({"x": 20, "y": 50, "text": "AB", "size": 12})).unwrap()["id"].as_u64().unwrap(); app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 1, "underline": true})).unwrap(); app.run("select.set", json!({"ids": [id]})).unwrap(); + // The underlined characters, in order. let underlined = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { - NodeKind::Text(t) => t.runs.iter().map(|r| r.style.underline).collect::>(), + NodeKind::Text(t) => t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect::(), _ => panic!("text"), }; + assert_eq!(underlined(&app), "A"); assert_eq!(super::toggle_underline(&mut app), Ok(json!(true))); - assert!(underlined(&app).iter().all(|u| *u), "{:?}", underlined(&app)); + assert_eq!(underlined(&app), "AB"); assert_eq!(super::toggle_underline(&mut app), Ok(json!(false))); - assert!(underlined(&app).iter().all(|u| !*u), "{:?}", underlined(&app)); + assert_eq!(underlined(&app), ""); } /// At a caret in text the Type tool edits, with no characters selected, the Character @@ -902,15 +916,15 @@ fn kashidas_menu_item_handles_default_and_mixed_ranges() { assert!(!state(&app, &row).1); fire(&mut app, &row); assert!(state(&app, &row).1); - let kashidas = |app: &VectorcraftApp| story_frame(app, id).runs.iter().map(|r| r.style.kashidas).collect::>(); - assert!(kashidas(&app).iter().all(|v| *v)); + let kashidas = |app: &VectorcraftApp| distinct(story_frame(app, id).runs.iter().map(|r| r.style.kashidas)); + assert_eq!(kashidas(&app), [true]); app.select_tool("type"); app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); app.session.set_tool_option("select", &json!({"start": 1, "end": 1})); assert!(!state(&app, &row).0, "disabled at an empty caret"); // The result is not the point: a disabled row must leave the text as it was. let _ = run(&mut app, &row.id, &row.params); - assert!(kashidas(&app).iter().all(|v| *v), "an empty caret leaves all characters unchanged"); + assert_eq!(kashidas(&app), [true], "an empty caret leaves all characters unchanged"); } /// Reset Panel sets every character attribute the panel shows, except the font family, style @@ -1112,7 +1126,7 @@ fn select_all_in_threaded_text_formats_and_copies_the_whole_story() { crate::panels::paragraph::run_on_paragraphs(&mut app, "text.setFormat", json!({"spaceBefore": 4})).unwrap(); for id in [a, b] { let t = frame(&app, id); - assert!(t.runs.iter().all(|r| (r.style.size - 9.0).abs() < 1e-9), "every character of frame {id} is 9 pt"); + assert_eq!(distinct(t.runs.iter().map(|r| r.style.size)), [9.0], "every character of frame {id} is 9 pt"); assert!((t.para_at(0).space_before - 4.0).abs() < 1e-9, "frame {id}'s paragraphs take the space"); } assert!(intercept_text_command(&mut app, "edit.copy").is_some()); @@ -1174,9 +1188,9 @@ fn story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_lea assert_eq!(text_story(&app), Some(vec![NodeId(b), NodeId(c)])); format(&mut app, json!({"size": 9})); - assert!(story_sizes(&app, a).iter().all(|s| (*s - 12.0).abs() < 1e-9), "the frame that left keeps its size"); + assert_eq!(distinct(story_sizes(&app, a)), [12.0], "the frame that left keeps its size"); for id in [b, c] { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size"); + assert_eq!(distinct(story_sizes(&app, id)), [9.0], "frame {id} takes the size"); } } @@ -1262,26 +1276,28 @@ fn selection_tool_changes_reach_every_frame_of_the_story() { style(&mut app, json!({"size": 9})); assert_eq!(undo_steps(&app), steps + 1, "one undo step"); for id in frames { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 9.0).abs() < 1e-9), "frame {id} takes the size"); + assert_eq!(distinct(story_sizes(&app, id)), [9.0], "frame {id} takes the size"); } - assert!(story_sizes(&app, other).iter().all(|s| (*s - 12.0).abs() < 1e-9), "other type keeps its size"); + assert_eq!(distinct(story_sizes(&app, other)), [12.0], "other type keeps its size"); app.run("edit.undo", json!({})).unwrap(); for id in frames { - assert!(story_sizes(&app, id).iter().all(|s| (*s - 12.0).abs() < 1e-9), "undo gives frame {id} its size back"); + assert_eq!(distinct(story_sizes(&app, id)), [12.0], "undo gives frame {id} its size back"); } format(&mut app, json!({"underline": true})); + let underline = |app: &VectorcraftApp, id: u64| distinct(story_frame(app, id).runs.iter().map(|r| r.style.underline)); for id in frames { - assert!(story_frame(&app, id).runs.iter().all(|r| r.style.underline), "frame {id} is underlined"); + assert_eq!(underline(&app, id), [true], "frame {id} is underlined"); } - assert!(story_frame(&app, other).runs.iter().all(|r| !r.style.underline)); + assert_eq!(underline(&app, other), [false]); // Tate-chu-yoko Settings and Warichu Settings set their values through `run_format`. run_format(&mut app, json!({"tcyUpDown": 2})).unwrap(); + let up_down = |app: &VectorcraftApp, id: u64| distinct(story_frame(app, id).runs.iter().map(|r| r.style.tcy_up_down)); for id in frames { - assert!(story_frame(&app, id).runs.iter().all(|r| (r.style.tcy_up_down - 2.0).abs() < 1e-9), "frame {id} takes Up/Down"); + assert_eq!(up_down(&app, id), [2.0], "frame {id} takes Up/Down"); } - assert!(story_frame(&app, other).runs.iter().all(|r| r.style.tcy_up_down.abs() < 1e-9)); + assert_eq!(up_down(&app, other), [0.0]); } /// The fields show a value only when every frame of the selected story has it: a hidden frame that diff --git a/crates/ui-egui/src/panels/glyphs/tests.rs b/crates/ui-egui/src/panels/glyphs/tests.rs index 0886975276..e8eae923bd 100644 --- a/crates/ui-egui/src/panels/glyphs/tests.rs +++ b/crates/ui-egui/src/panels/glyphs/tests.rs @@ -208,9 +208,7 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { assert!(!rows(&app).contains(&form_ref(GlyphForm::Jis78)), "hidden without Show East Asian Options"); app.session.prefs.show_east_asian_options = true; let shown = rows(&app); - for form in GlyphForm::ALL { - assert!(shown.contains(&form_ref(form)), "{form:?} in {shown:?}"); - } + assert!(shown.contains(&form_ref(GlyphForm::Jis78)), "shown with Show East Asian Options: {shown:?}"); const FAMILY: &str = "BIZ UDMincho"; if FontDb::global().face(FAMILY, "Regular").is_none_or(|f| f.family != FAMILY) { eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); @@ -231,7 +229,7 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": fallback})).unwrap(); select(&mut app, 0, 6); choose(&mut app, GlyphForm::Jis83); - assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Jis83), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Jis83), "亜唖", "{:?}", forms(&app)); app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "font": FAMILY})).unwrap(); app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "default"})).unwrap(); select(&mut app, 3, 6); @@ -244,7 +242,12 @@ fn east_asian_glyph_forms_in_the_panel_menu_set_the_selected_characters_form() { assert_eq!(undo_len(&app), n); assert_eq!(forms(&app)[1].1, GlyphForm::Jis78); choose(&mut app, GlyphForm::Default); - assert!(forms(&app).iter().all(|(_, f)| *f == GlyphForm::Default), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Default), "亜唖", "{:?}", forms(&app)); +} + +/// The characters of `runs` (text and form) drawn in `form`, in order. +fn in_form(runs: &[(String, GlyphForm)], form: GlyphForm) -> String { + runs.iter().filter(|(_, f)| *f == form).map(|(text, _)| text.as_str()).collect() } /// At a caret the glyph form rows act on all the text of the object, so they are checked, and skipped as changing nothing, by @@ -256,14 +259,14 @@ fn glyph_form_items_at_a_caret_follow_all_the_text() { app.session.prefs.show_east_asian_options = true; let node = NodeId(id.as_u64().unwrap_or(0)); let forms = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(node).unwrap().kind { - NodeKind::Text(t) => t.runs.iter().map(|r| r.style.glyph_form).collect::>(), + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.glyph_form)).collect::>(), _ => panic!("text"), }; app.run("text.setRangeStyle", json!({"id": id, "start": 0, "end": 3, "glyphForm": "jis78"})).unwrap(); select(&mut app, 6, 6); assert_eq!(selection_glyph_form(&app), None, "the caret's form is not every character's"); choose(&mut app, GlyphForm::Default); - assert!(forms(&app).iter().all(|f| *f == GlyphForm::Default), "{:?}", forms(&app)); + assert_eq!(in_form(&forms(&app), GlyphForm::Default), "亜唖", "{:?}", forms(&app)); app.run("text.setRangeStyle", json!({"id": id, "glyphForm": "jis78"})).unwrap(); select(&mut app, 6, 6); assert_eq!(selection_glyph_form(&app), Some(GlyphForm::Jis78)); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index e6668323a8..7d59220a48 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1756,7 +1756,8 @@ mod tests { let app = panel.app(); let names: Vec> = app.session.documents().iter().map(|st| st.doc.graphic_styles.iter().map(|g| g.name.clone()).collect()).collect(); - assert!(names.iter().all(|n| n.iter().any(|g| g == "Mine")), "no style is renamed: {names:?}"); + let kept = names.iter().filter(|n| n.iter().any(|g| g == "Mine")).count(); + assert_eq!(kept, 2, "both documents keep their style named Mine: {names:?}"); } /// The New and Delete buttons name what an Alt-click does, and an Alt-click does it: New asks for a name, Delete diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 7650b4d79c..2e0c5b2c57 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -292,6 +292,15 @@ mod tests { use crate::tests::panel_harness::Panel; use craft::ui::contract::Role; + /// English and two translated interface languages, one of them with another script. + fn some_languages() -> [crate::i18n::Lang; 3] { + [ + crate::i18n::Lang::EN, + crate::i18n::Lang::from_code("de").expect("de registered"), + crate::i18n::Lang::from_code("ja").expect("ja registered"), + ] + } + /// A step named after a style lists the template's translation with the style's name in it as /// the document holds it, also when the name looks like a template, like a step with a row of /// its own (`Apply Brush`) or like another template's name; the Normal style's name is @@ -338,7 +347,7 @@ mod tests { /// plain row, else the menu item's row without the ellipsis; a name with no row has none. #[test] fn plain_steps_read_the_menu_row_and_unknown_steps_have_no_name() { - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { let menu_row = crate::i18n::has(lang, "Clean Up…").then(|| crate::i18n::tr(lang, "Clean Up…").trim_end_matches('…').to_string()); let plain_row = crate::i18n::has(lang, "Clean Up").then(|| crate::i18n::tr(lang, "Clean Up").to_string()); assert_eq!(step_name(lang, "Clean Up"), plain_row.or(menu_row), "{}", lang.code()); @@ -347,7 +356,7 @@ mod tests { assert_eq!(step_name(ja, "No Such Step"), None); } - /// Every built-in effect has one name in each language: History (and Edit › Undo and Redo) + /// Every built-in effect has one name in each language checked: History (and Edit › Undo and Redo) /// names the step that applied it, and the Appearance panel its row, with the text of its /// Effect menu item without the ellipsis, which is the effect's `@id` row or the row of its /// menu label with the ellipsis. @@ -366,7 +375,7 @@ mod tests { } assert!(steps.len() * 2 > vectorcraft_effects::effect_catalog().len(), "only {} effects applied", steps.len()); let mut differ = Vec::new(); - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { crate::i18n::set_current(lang); for (e, h) in &steps { let cmd = if e.defaults.as_object().is_some_and(|o| o.is_empty()) { "effect.apply" } else { "effect.dialog" }; @@ -385,14 +394,14 @@ mod tests { } /// A step another command names like an effect (Object › Transform's `Transform`, the name of - /// Distort & Transform › Transform) keeps its own name in every language. + /// Distort & Transform › Transform) keeps its own name in each language checked. #[test] fn a_step_named_like_an_effect_keeps_its_own_name() { let mut app = app_with_two_rectangles(); app.session.execute("object.transform", &json!({ "matrix": [1, 0, 0, 1, 5, 0] })).unwrap(); let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); assert_eq!((h.label.as_str(), h.effect()), ("Transform", None)); - for lang in crate::i18n::Lang::all() { + for lang in some_languages() { assert_eq!(entry_name(lang, &h), step_name(lang, "Transform"), "{}", lang.code()); } } diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 1c7a51edc3..7a1085a152 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1280,11 +1280,7 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { assert_eq!(undo(&panel.app()), steps, "not traced yet"); { let mut app = panel.app(); - let t0 = std::time::Instant::now(); - while !app.trace_runs.running.is_empty() && t0.elapsed() < std::time::Duration::from_secs(30) { - crate::trace_runs::poll(&mut app); - std::thread::sleep(std::time::Duration::from_millis(5)); - } + crate::trace_runs::finish_all(&mut app); assert_eq!(undo(&app), steps + 1, "one undo step"); assert_eq!(param(&app, "strokes"), Some(json!(true))); let st = &app.ui.image_trace_panel.shown; diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index d61efcb289..43174d8f9e 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -887,6 +887,7 @@ mod tests { let r = toggle_ref(tag); assert!(rows.iter().any(|row| matches!(row, PanelRow::Submenu(_, sub) if has_row(sub, &r))), "the submenu has a row for {tag}"); } + // Only an installed face without bundled fonts can offer no set; the rows above are checked. let Some((first, flag, _)) = sets.first() else { return }; let (label, tag) = (set_label(first), flag.tag().unwrap()); set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); @@ -972,7 +973,9 @@ mod tests { assert_eq!(state_of(&app, &toggle_ref(tag)), Some(toggled(label, false)), "{label}"); run(&mut app, TOGGLE, &json!({"tag": tag})).unwrap().unwrap(); let runs = run_features(&mut app, &id, 8); - assert!(runs.iter().all(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))), "{label}: {runs:?}"); + let tagged: String = + runs.iter().filter(|(_, f)| f.as_array().is_some_and(|f| f.iter().any(|x| x == tag))).map(|(t, _)| t.as_str()).collect(); + assert_eq!(tagged, "かなAB", "{label}: {runs:?}"); } } @@ -1023,6 +1026,11 @@ mod tests { } } + /// The characters of `runs` ([`metrics_runs`]) whose Proportional Metrics and features `keep` accepts. + fn text_where(runs: &[(String, bool, Vec)], keep: impl Fn(bool, &[String]) -> bool) -> String { + runs.iter().filter(|(_, on, f)| keep(*on, f)).map(|(t, _, _)| t.as_str()).collect() + } + /// Where the panel menu's top-level rows list the command `r`. fn row_index(rows: &[PanelRow], r: &CommandRef) -> Option { rows.iter().position(|row| matches!(row, PanelRow::Command(c) if c == r)) @@ -1068,13 +1076,14 @@ mod tests { assert_eq!(run(&mut app, METRICS, &json!({})), Some(Ok(json!({"on": true})))); assert_eq!(undo_steps(&app), undo + 1); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); - assert_eq!(runs.iter().map(|(t, _, f)| (t.as_str(), f.clone())).collect::>(), [("か", vec!["smcp".to_string()]), ("なAB", vec![])]); + assert_eq!(runs, [("か".to_string(), true, vec!["smcp".to_string()]), ("なAB".to_string(), true, vec![])]); assert_eq!(state_of(&app, &metrics), Some(toggled("Proportional Metrics", true))); assert_eq!(run(&mut app, METRICS, &json!({})), Some(Ok(json!({"on": false})))); assert_eq!(undo_steps(&app), undo + 2); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, f)| !*on && (f.is_empty() || *f == ["smcp"])), "{runs:?}"); + assert_eq!(text_where(&runs, |on, _| on), "", "{runs:?}"); + assert_eq!(text_where(&runs, |_, f| f == ["smcp"]), "か", "each run keeps its features: {runs:?}"); + assert_eq!(text_where(&runs, |_, f| f.is_empty()), "なAB", "{runs:?}"); } /// With the Selection tool, Proportional Metrics turns on for the whole selected object. At a @@ -1089,7 +1098,7 @@ mod tests { let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "かなAB"})).unwrap()["id"].clone(); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); run(&mut app, METRICS, &json!({})).unwrap().unwrap(); - assert!(metrics_runs(&app, &id).iter().all(|(_, on, _)| *on), "{:?}", metrics_runs(&app, &id)); + assert_eq!(text_where(&metrics_runs(&app, &id), |on, _| on), "かなAB"); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.prefs.show_east_asian_options = true; @@ -1104,7 +1113,7 @@ mod tests { assert_eq!(state_of(&app, &CommandRef::new(METRICS)), Some(toggled("Proportional Metrics", false))); run(&mut app, METRICS, &json!({})).unwrap().unwrap(); let runs = metrics_runs(&app, &id); - assert!(runs.iter().all(|(_, on, _)| *on), "{runs:?}"); + assert_eq!(text_where(&runs, |on, _| on), "かなAB", "{runs:?}"); } /// With Real-time Drawing off, Proportional Metrics and H or V Style decide from the text with diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 75310b3f35..8d2ea06ab8 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -282,7 +282,7 @@ fn kinsoku_set_shows_a_custom_set_by_name() { } /// The Mojikumi Set menu lists None, the four other predefined sets and Line-end Punctuation Half -/// Width, each under its own label in every interface language. Each entry sets the selected +/// Width, each under its own label in English and in Japanese. Each entry sets the selected /// paragraphs' set in one undo step and is shown as the current set; paragraphs with different /// sets show a blank menu, and Reset Panel gives them Line-end Punctuation Half Width. #[test] @@ -290,7 +290,7 @@ fn mojikumi_menu_offers_and_sets_every_predefined_set() { let keys: Vec<&str> = mojikumi_sets().iter().map(|s| s.2).collect(); assert_eq!(keys, ["none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku", "lineEndHalf"]); use crate::i18n::LangExt as _; - for lang in crate::i18n::Lang::all() { + for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_code("ja").expect("ja registered")] { crate::i18n::set_current(lang); let labels: std::collections::BTreeSet<&str> = mojikumi_sets().iter().map(|s| s.0).collect(); crate::i18n::set_current(crate::i18n::Lang::EN); @@ -680,10 +680,8 @@ fn the_numbered_list_button_and_its_presets_set_the_list_and_reset_panel_clears_ assert_eq!(lists(&app), (numbered(NumberStyle::Arabic), None), "the caret's paragraph"); assert_eq!(numbers_shown(&app), Some(Some(NumberStyle::Arabic)), "the button shows pressed"); assert_eq!(number_sample(NumberStyle::UpperRoman, 3), "I, II, III"); - for style in NumberStyle::ALL { - set_number_style(&mut app, Some(style)); - assert_eq!(lists(&app), (numbered(style), None), "{}", number_sample(style, 3)); - } + set_number_style(&mut app, Some(NumberStyle::UpperRoman)); + assert_eq!(lists(&app), (numbered(NumberStyle::UpperRoman), None), "a preset picks its style"); set_number_style(&mut app, None); assert_eq!(lists(&app), (None, None)); app.session.set_tool_option("selectAll", &json!(true)); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 3ee8c24ce5..06d19cd822 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -29,6 +29,10 @@ pub struct PropertiesUi { quick_actions: Option<(u64, Vec)>, /// The [`content_key`] the sections were last shown for. content: Option, + /// The document (uid, revision) the sections were last shown for. + revision: Option<(u64, u64)>, + /// An edit made during a drag whose sections are not measured yet. + measure_pending: bool, } /// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). @@ -66,7 +70,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let guides = super::transform::selected_guides(app); let header = heading(first.as_deref(), n_sel, editing_artboards, guides.is_some()); let content = content_key(app); - let changed = app.ui.properties_panel.content.replace(content) != Some(content); + let revision = app.session.active().map(|st| (st.uid, st.revision)); + let content_changed = app.ui.properties_panel.content.replace(content) != Some(content); + let edited = std::mem::replace(&mut app.ui.properties_panel.revision, revision) != revision; + // A drag on the canvas, or a scrubbed field, moves the revision on every pointer move without changing which + // sections show: the sections are measured again for an edit once the drag ends, not on each move. The edit stays + // pending until then, also when the release itself does not move the revision. + let dragging = app.session.active().is_some_and(|st| st.interaction.is_some() || st.undo_group.is_some()); + let pending = app.ui.properties_panel.measure_pending || edited; + let changed = content_changed || (pending && !dragging); + app.ui.properties_panel.measure_pending = pending && !changed; let mut sections = |ui: &mut Ui, _: &mut BodyCx<'_>| { // The reference panel's labels end in a colon beside fields that keep their own width. Stack::new().fill_width().labels(LabelScheme::Form).show(ui, |ui, _| { @@ -87,19 +100,21 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut panel = Panel::new(header).titled().strength(HeaderStrength::Quiet).labels(LabelScheme::Inspector).pad(Pad::None); panel = panel.id_salt(egui::IdSalt::new(key)); if changed { + #[cfg(test)] + SECTION_MEASURES.with(|n| n.set(n.get() + 1)); let _ = panel.measure_in(ui, Proposal::Size(ui.available_size()), &mut sections); } panel.show(ui, sections); } -/// What the sections show: the document and its revision, the selection, the tool and isolation mode. +/// What the sections show besides the document's revision: the document, the selection, the tool and isolation mode. fn content_key(app: &VectorcraftApp) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); app.session.tool_id().hash(&mut h); if let Some(st) = app.session.active() { let selection = &st.selection; - (st.uid, st.revision, st.isolation, &selection.objects, selection.key, selection.target, &selection.slices).hash(&mut h); + (st.uid, st.isolation, &selection.objects, selection.key, selection.target, &selection.slices).hash(&mut h); for (id, anchors) in &selection.anchors { (id, anchors.len()).hash(&mut h); } @@ -223,6 +238,8 @@ fn quick_actions_key(app: &VectorcraftApp) -> u64 { thread_local! { /// How many times this thread has listed the Quick Actions. pub(crate) static QUICK_ACTION_LISTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times this thread has measured the panel's sections before showing them. + pub(crate) static SECTION_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`quick_actions`], listed again only when [`quick_actions_key`] changed. diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 97c9f1e9bb..dea62a6dfa 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -190,6 +190,94 @@ fn a_selection_change_draws_the_window_in_one_pass() { } } +/// Dragging the selected object with the Selection tool, with the Properties panel docked, does not measure the +/// panel's sections on each pointer move, and each frame of the drag takes one pass. The release measures them once +/// for the moved object, and so does an edit made without a drag. +#[test] +fn a_drag_does_not_measure_the_sections_on_each_move() { + let measures = || SECTION_MEASURES.with(std::cell::Cell::get); + let mut app = new_app(); + let a = rect(&mut app, 100.0, 100.0, 80.0, 80.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + app.select_tool("selection"); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + // One frame with `events` → (the passes it took, the section measures it made). + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + events, + ..Default::default() + }; + let (pass, measured) = (ctx.cumulative_pass_nr(), measures()); + let _ = crate::testing::app_frame(app, &ctx, raw); + (ctx.cumulative_pass_nr() - pass, measures() - measured) + }; + for _ in 0..4 { + frame(&mut app, vec![]); + } + let x = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.selection.objects.first().and_then(|id| st.doc.node(*id)).and_then(|n| n.geometric_bounds()).unwrap().x0 + }; + let start_x = x(&app); + let start = app.canvas_view().unwrap().to_screen(craft::behavior::kurbo::Point::new(140.0, 140.0)); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&mut app, vec![Event::PointerMoved(start)]); + assert_eq!(frame(&mut app, vec![button(start, true)]), (1, 0), "the press"); + let mut at = start; + for step in 1..=6 { + at = start + egui::vec2(8.0 * step as f32, 5.0 * step as f32); + assert_eq!(frame(&mut app, vec![Event::PointerMoved(at)]), (1, 0), "move {step} of the drag"); + } + assert_eq!(frame(&mut app, vec![button(at, false)]), (1, 1), "the release measures the moved object's sections once"); + assert!(x(&app) > start_x, "the drag moved the object"); + assert_eq!(frame(&mut app, vec![]).1, 0, "a settled frame"); + app.run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + assert_eq!(frame(&mut app, vec![]).1, 1, "an edit without a drag measures the sections"); +} + +/// An edit made while an undo group is open, as a scrubbed field's drag makes, is measured once the group ends, also +/// when ending it does not move the document's revision. +#[test] +fn an_edit_during_a_drag_is_measured_when_the_drag_ends_without_a_new_revision() { + let measures = || SECTION_MEASURES.with(std::cell::Cell::get); + let mut app = new_app(); + let a = rect(&mut app, 100.0, 100.0, 80.0, 80.0); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("window.panel", json!({"panel": "properties"})).unwrap(); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + ..Default::default() + }; + let measured = measures(); + let _ = crate::testing::app_frame(app, &ctx, raw); + measures() - measured + }; + for _ in 0..4 { + frame(&mut app); + } + app.run("edit.undoGroup.begin", json!({})).unwrap(); + assert_eq!(frame(&mut app), 0, "opening the group"); + app.run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + assert_eq!(frame(&mut app), 0, "an edit inside the group"); + let revision = app.session.active().unwrap().revision; + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().revision, revision, "ending the group keeps the revision"); + assert_eq!(frame(&mut app), 1, "the end of the group measures the edit"); + assert_eq!(frame(&mut app), 0, "a settled frame"); +} + /// Start Global Edit in Quick Actions starts it on the one selected path, the button then reads /// Stop Global Edit, and Escape stops it. Selected type has no Start Global Edit button. #[test] diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 7f71d73da4..0a8ce3b8da 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -903,11 +903,15 @@ mod tests { let r = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(80.0, 16.0)); let (top, bottom) = profile_outline(r, 1.0, Some(&[(0.0, 1.0, 1.0), (0.5, 10.0, 10.0), (1.0, 1.0, 1.0)])); let all: Vec<_> = top.iter().chain(&bottom).collect(); - assert!(all.iter().all(|p| p.y >= r.top() && p.y <= r.bottom()), "{all:?}"); - let middle = all.iter().map(|p| (p.y - r.center().y).abs()).fold(0.0, f32::max); + let (highest, lowest) = all.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), p| (lo.min(p.y), hi.max(p.y))); + assert!(highest >= r.top() && lowest <= r.bottom(), "the outline stays in its box: {all:?}"); + // How far the outline reaches from the box's middle line. + let reach = |top: &[egui::Pos2], bottom: &[egui::Pos2]| top.iter().chain(bottom).map(|p| (p.y - r.center().y).abs()).fold(0.0, f32::max); + let middle = reach(&top, &bottom); assert!((middle - (r.height() / 2.0 - 1.0)).abs() < 1e-3, "the widest point fills the box ({middle})"); let (top, bottom) = profile_outline(r, 1.0, None); - assert!(top.iter().chain(&bottom).all(|p| (p.y - r.center().y).abs() <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3)); + let plain = reach(&top, &bottom); + assert!(plain > 0.0 && plain <= 0.35 * (r.height() / 2.0 - 1.0) + 1e-3, "the plain bar keeps its look ({plain})"); } #[test] diff --git a/crates/ui-egui/src/panels/swatches/tests/context_menu.rs b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs index bca7cf7852..06c5ce6caa 100644 --- a/crates/ui-egui/src/panels/swatches/tests/context_menu.rs +++ b/crates/ui-egui/src/panels/swatches/tests/context_menu.rs @@ -23,7 +23,9 @@ fn item_commands_run_on_the_clicked_swatch_and_paint_nothing() { let mut app = app(); select_rows(&mut app, &["Black"]); let (before, paint, undo) = (doc(&app), app.session.paint.fill.clone(), undo_steps(&app)); - assert!(enabled(&app, "Red").iter().all(|(_, on)| *on), "every item is enabled on a user swatch"); + let items = enabled(&app, "Red"); + assert_eq!(items.len(), ITEMS.len(), "{items:?}"); + assert!(items.iter().all(|(_, on)| *on), "every item is enabled on a user swatch: {items:?}"); menu(&mut app, "Red", "options"); assert_eq!(dialog_field(&app, KIND, "name"), json!("Red")); assert_eq!((doc(&app), undo_steps(&app)), (before.clone(), undo), "opening the dialog changes nothing"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index 77660aedc2..4397e098e6 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -103,23 +103,21 @@ fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { assert_eq!(ui["ui"]["color_wheel"], with(json!({"view": "box", "channel": "green"}))); } -/// The command's errors are translated in the catalogs that translate status and error messages, -/// and each translation keeps the accepted values. +/// The command's errors are shown in the interface language (German and Japanese here), and each +/// translation keeps the accepted values. #[test] fn ui_color_wheel_errors_are_translated() { let errors = [ ("`view` must be wheel or box", &["wheel", "box"][..]), ("`channel` must be hue, saturation, brightness, red, green or blue", &["hue", "saturation", "brightness", "red", "green", "blue"][..]), ]; - for code in [ - "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", - "ca", "nl", "bs", "da", "id", - ] { + for code in ["de", "ja"] { let lang = crate::i18n::Lang::from_code(code).expect("registered"); for (error, values) in errors { let shown = crate::i18n::message(lang, error); assert_ne!(shown, error, "{code}"); - assert!(values.iter().all(|v| shown.contains(v)), "{code}: {shown}"); + let missing: Vec<&str> = values.iter().copied().filter(|v| !shown.contains(v)).collect(); + assert!(missing.is_empty(), "{code}: {shown} lacks {missing:?}"); } } } @@ -147,16 +145,6 @@ fn ui_color_wheel_rejects_other_params() { assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } -/// `ui.colorWheel` answers every junk parameter without a panic. -#[test] -fn ui_color_wheel_answers_junk_params_without_a_panic() { - let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; - let mut app = app(json!("#336699"), "hue"); - for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { - let _ = app.run("ui.colorWheel", p); - } -} - /// The settings survive a JSON round trip of the preferences, and a saved value this build does /// not know reads as the key's default without losing the other preferences. #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs index 230485922f..b19877ec58 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -38,44 +38,20 @@ fn uncalibrated_cmyk_marks_nothing() { }); } -/// A profile loaded again under the same name can change which colors are printable while the -/// color settings stay the same; the panel keeps drawing through the change. +/// In the wheel's square and in the box, Show Out-of-Gamut Colors changes what the panel draws, +/// and turning it off again draws the panel as it was. #[test] -fn the_grid_is_computed_again_after_a_profile_is_loaded() { - if !crate::testing::in_own_process("panels::tests_color_wheel_gamut::the_grid_is_computed_again_after_a_profile_is_loaded") { - return; +fn the_setting_shades_the_wheel_and_the_box() { + for view in ["wheel", "box"] { + let mut p = Panel::new(app("#3366cc", view, false)); + let off = p.fx.frame_shapes(); + p.run("ui.colorWheel", json!({"gamut": true})); + let on = p.fx.frame_shapes(); + // Compared without printing: a frame holds thousands of shapes. + assert!(on != off, "{view}: the shading is drawn"); + p.run("ui.colorWheel", json!({"gamut": false})); + assert!(p.fx.frame_shapes() == off, "{view}: off draws no shading"); } - let mut p = Panel::new(app("#3366cc", "box", true)); - /// Unregisters the profile when dropped, also after a failed assertion. - struct Unregister(&'static str); - impl Drop for Unregister { - fn drop(&mut self) { - cms::unregister_icc(self.0); - } - } - let name = "Color Wheel Gamut Reload CMYK"; - let bytes = cms::icc_bytes(cms::GENERIC_CMYK).unwrap(); - cms::register_icc(&bytes, Some(name.into())).unwrap(); - let _unregister = Unregister(name); - p.fx.idle(2); - assert!(p.fx.by_label("Color box").is_some()); -} - -/// The wheel's square and the Hue box both show with the setting on. -#[test] -fn the_wheel_and_the_hue_box_shade_the_same_cells() { - let mut p = Panel::new(app("#3366cc", "wheel", true)); - assert!(p.fx.by_label("Saturation and brightness").is_some()); - p.run("ui.colorWheel", json!({"view": "box"})); - assert!(p.fx.by_label("Color box").is_some()); -} - -/// With Show Out-of-Gamut Colors off, the panel still draws and the setting reads off. -#[test] -fn with_the_setting_off_no_grid_is_computed() { - let p = Panel::new(app("#3366cc", "box", false)); - assert!(!p.app().ui.color_wheel.gamut); - assert!(p.fx.by_label("Color box").is_some()); } /// `ui.colorWheel {gamut}` sets the setting and keeps the others; a key set to null keeps its value diff --git a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs index 8a8ddf4768..be2cf16ae3 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_harmony.rs @@ -114,17 +114,14 @@ fn ui_color_wheel_sets_the_harmony_and_its_rule() { assert_eq!(got["harmonyRule"], json!("splitComplementary")); } -/// The errors are translated in the catalogs that translate status and error messages, and each +/// The errors are shown in the interface language (German and Japanese here), and each /// translation keeps the key and the accepted values. #[test] fn ui_color_wheel_harmony_errors_are_translated() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let flag = app.run("ui.colorWheel", json!({"harmony": 1})).unwrap_err(); let rule = app.run("ui.colorWheel", json!({"harmonyRule": "shades"})).unwrap_err(); - for code in [ - "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", - "ca", "nl", "bs", "da", "id", - ] { + for code in ["de", "ja"] { let lang = crate::i18n::Lang::from_code(code).expect("registered"); let shown = crate::i18n::message(lang, &flag); assert!(shown != flag && shown.contains("`harmony`"), "{code}: {shown}"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index f3b5ca6a47..58cb9a84b4 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -433,14 +433,3 @@ fn the_row_is_gray_with_nothing_selected_and_on_type() { let p = Panel::new(app); assert!(disabled(&p)); } - -/// `ui.colorWheel` answers every junk parameter, with and without a document, without a panic. -#[test] -fn ui_color_wheel_answers_junk_params_without_a_panic() { - let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; - for mut app in [app(), VectorcraftApp::new(Session::new(), Default::default())] { - for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { - let _ = app.run("ui.colorWheel", p); - } - } -} diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index c554b21add..183d7bbe7e 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -153,15 +153,30 @@ pub fn poll(app: &mut VectorcraftApp) { } Err(TryRecvError::Disconnected) => None, }; - let r = app.trace_runs.running.remove(i); - // The status bar no longer says it is tracing. - if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { - app.ui.status.clear(); - } - finish(app, r, done); + land(app, i, done); } } +/// Waits for each trace running to end, in the order they were started, and applies it as +/// [`poll`] does once it is done. +#[cfg(test)] +pub(crate) fn finish_all(app: &mut VectorcraftApp) { + while let Some(r) = app.trace_runs.running.first() { + let done = r.done.recv().ok(); + land(app, 0, done); + } +} + +/// Takes trace `i`, which has ended with `done`, off the list and applies it. +fn land(app: &mut VectorcraftApp, i: usize, done: Option) { + let r = app.trace_runs.running.remove(i); + // The status bar no longer says it is tracing. + if app.ui.status == format!("{}…", crate::i18n::msg(LABEL)) { + app.ui.status.clear(); + } + finish(app, r, done); +} + /// Applies trace `r`'s result in its document, which becomes the active one again, as its command /// would while the object, its image and the settings are as they were and the document was not /// reverted; else why it has none, in the status bar. diff --git a/docs/mcp.md b/docs/mcp.md index 9a6f721b93..8afcd8618a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17082,7 +17082,7 @@ Commands: - `addon.pathtools.bridge {radius?, gap?, reach?, keepOriginals?, ids?}` joins circles (`ids`, default: the selection, with a group other than a clipping group giving the objects inside it at any depth, which must all be circles; paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes, as one undo step (Object › - Plug-ins › Path Precision Tools › Smooth Bridge…). Two circles become one closed outline that goes around each circle + Plug-ins › Path Precision Tools › Common Tangents… with External and Curved). Two circles become one closed outline that goes around each circle on its side away from the other and along two concave arcs, one on each side of the line through the centers, each touching both circles from outside, so every anchor is smooth. `radius` is the arcs' radius as a percentage of the smaller circle's radius (1 to 1,000, 100 by default): a larger radius makes a wider, gentler bridge. `gap` (0 to 1,000 @@ -17112,10 +17112,11 @@ Commands: other stays as it is. The shapes and the circles left as they are are selected. It is an error when any pair within reach has one circle inside the other, when no pair within reach can be bridged (suggesting a larger radius or gap only when the largest would bridge a pair of them under these rules), when no two circles are within reach, and above 2,000 circles or 8,000 bridges. → `{ids, alone}`: - the shapes and the circles left as they are, with `id` as well for two circles. Smooth Bridge… opens a dialog - (`ui.menuDialog {command}`, key `addon.pathtools.bridge`) with Constant Gap (a Gap field in place of the Radius field in - percent), Reach (unavailable when the selection, a selected group's objects counted, holds two objects), Keep Originals - and Preview. + the shapes and the circles left as they are, with `id` as well for two circles. Opening `addon.pathtools.bridge` + from the menu dialog (`ui.menuDialog {command}`) opens Common Tangents' dialog (key + `addon.pathtools.commonTangents`) with External and Curved on, described under + `addon.pathtools.commonTangents`. No menu item runs `addon.pathtools.bridge`, and the command palette and Keyboard + Shortcuts leave it out; scripts and actions still run it. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids` @@ -17216,7 +17217,7 @@ Commands: - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). -- `addon.pathtools.commonTangents {tangents?, centerline?, ids?}` adds the common tangent lines of two convex closed +- `addon.pathtools.commonTangents {tangents?, centerline?, connect?, curved?, radius?, gap?, reach?, keepOriginals?, ids?}` adds the common tangent lines of two convex closed paths (`ids`, or the two selected objects) as separate open paths: lines that touch both paths without crossing into either. `tangents`: `external` (both paths on the same side of the line), `internal` (lines that run between them) or `all` (default). With `centerline: true` it also adds the line joining the two centers: an ellipse's center, or @@ -17241,9 +17242,19 @@ Commands: runs from the point to the path's center. Two points are refused with "select two closed paths". The lines are stroked with the current stroke color and weight (black when the stroke is None), have no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of the kind asked for, - nothing changes, and the result's `warning` says why. Common Tangents… opens a dialog (Tangents, Centerline) with - Preview; with a point selected, every Tangents choice gives the same lines. → `{ids, external, internal, - centerline, warning?}` (`centerline`: the centerline's id, or null). + nothing changes, and the result's `warning` says why. → `{ids, external, internal, centerline, warning?}` + (`centerline`: the centerline's id, or null). With `connect: true` the two tangents of each kind become one closed + path instead of two lines, joined by the chords between where they touch each path (two internal tangents make a + crossed shape, and a point's two lines make a triangle); a kind with one tangent stays a line, and the centerline + stays a line. With `curved: true` it joins the selected circles into one outline along concave arcs instead, as + `addon.pathtools.bridge` does, taking that command's `radius` or `gap`, `reach`, `keepOriginals` and `ids`, and + the result is that command's. `tangents` other than `external`, `centerline` and `connect: false` with `curved` are + an error, and so are `radius`, `gap`, `reach` and `keepOriginals` without it. Common Tangents… opens a dialog with + Tangents, Centerline and Connect tangents; with External it also shows Straight and Curved (Straight by default) and + the bridge's options: Constant Gap (a Gap field in place of the Radius field in percent), Reach (unavailable when the + selection, a selected group's objects counted, holds two objects) and Keep Originals, which take input only with + Curved. With Curved, Centerline is unavailable and Connect tangents shows on. Choosing another kind of tangent goes + back to Straight. With a point selected, every Tangents choice gives the same lines. - `addon.pathtools.boundingRectangle {each?, offset?}` draws a live rectangle on the geometric bounding box of the selected objects, strokes and effects left out (Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle…, #6966). `addon.pathtools.boundingCircle {each?, offset?}` draws the smallest live circle that holds the outlines of diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d613b4ccd2..6bd873051e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -594,7 +594,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none (its options show or hide the center cross and the radii, set their color, and set how near a segment is picked with Smart Guides on or off); Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Common Tangents… with External and Curved (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/tangents.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored |