From 3dbac8d04fa7474c4395b4cda754c5935da16f71 Mon Sep 17 00:00:00 2001 From: Skryx Dev Date: Wed, 11 Nov 2026 18:33:42 +0100 Subject: [PATCH] Pick what objects draw; the ribbon's layer list moves the selection The ribbon's layer, colour, linetype and lineweight lists act on the selected objects when there are some (as AutoCAD does), and set the current value only when nothing is selected. With a selection they show the value the objects share, or nothing when they differ. Objects on a locked layer are left out, and the command line says how many. Picking now tests what each object draws: - A polyline with width (constant or tapered, a donut) is picked anywhere in its band, and a crossing box inside the band crosses it. - The spatial index finds objects by how far they can draw (`reach`): the drawing's box for words is an estimate a wide last letter outgrows, and a dimension's words outside a circle are past its defining points. Without this, those parts could not be picked. - A linear or aligned dimension's bounds take in both ends of its line; DIMALIGNED keeps the point it was placed through, not one end. A new test picks about 36 kinds of object on what they draw and in the empty space around them, alone and through the spatial index. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/extents.rs | 21 +++ crates/engine/src/select.rs | 93 +++++++++++- crates/engine/src/spatial.rs | 11 +- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/pick_audit.rs | 216 +++++++++++++++++++++++++++ crates/render/src/lib.rs | 2 +- crates/ui-egui/src/ribbon.rs | 207 ++++++++++++++++++++----- 7 files changed, 506 insertions(+), 45 deletions(-) create mode 100644 crates/engine/tests/it/pick_audit.rs diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 66fca3d9..7a99b3fe 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -197,6 +197,24 @@ fn insert_texts(d: &Drawing, ins: &crate::Insert, outer: Mat3, depth: usize, out } } +/// The ends of a linear or aligned dimension's line. It runs through the definition point between +/// the feet of the two extension lines' origins: a dimension measured on a slant, or with its line +/// moved away, reaches there past its three points (the definition point is not always at one end: +/// DIMALIGNED keeps the point it was placed through). None for other kinds. +fn dim_line_ends(dm: &crate::Dimension) -> Vec { + let dir = match dm.kind { + crate::DimKind::Linear { rotation } => Some(Vec2::new(rotation.cos(), rotation.sin())), + crate::DimKind::Aligned => Some(dm.p14.xy() - dm.p13.xy()).filter(|v| v.len() > 1e-12).map(|v| v.normalized()), + _ => None, + }; + let Some(u) = dir.filter(|u| u.x.is_finite() && u.y.is_finite()) else { return Vec::new() }; + [dm.p13.xy(), dm.p14.xy()] + .into_iter() + .map(|origin| dm.defpt.xy() + u * (origin - dm.defpt.xy()).dot(u)) + .filter(|f| f.x.is_finite() && f.y.is_finite()) + .collect() +} + /// The box of what `e` draws (block contents on layers turned off left out). pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 { bounds_of(d, e, depth, false, &mut HashMap::new()) @@ -322,6 +340,9 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< crate::DimKind::Ordinate { .. } => vec![dm.p13.xy(), dm.p14.xy()], }; let mut b = Bounds2::from_points(pts); + for foot in dim_line_ends(dm) { + b.add(foot); + } if dm.user_text_pos { b.add(dm.text_mid.xy()); } diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 518ed757..2169be12 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -71,6 +71,10 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { } out.push(pts); } + // A polyline with width (a donut, a tapered arrow) is also hit on the edges of its band. + if let Some(t) = wide_fill(e, tol) { + out.extend(t.as_chunks::<3>().0.iter().map(|[a, b, c]| vec![*a, *b, *c, *a])); + } // A pattern hatch is also picked on its drawn pattern strokes, not only its boundary. if let EntityKind::Hatch(h) = kind && !h.solid @@ -89,6 +93,55 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { } } +/// The triangles that fill a polyline drawn with width (constant or tapered), as the renderer +/// fills it; `None` for any other object. +fn wide_fill(e: &Entity, tol: f64) -> Option> { + match &e.kind { + EntityKind::LwPolyline(p) if p.const_width > 0.0 || p.vertices.iter().any(|v| v.start_width > 0.0 || v.end_width > 0.0) => { + Some(draftcraft_render::wide_polyline(p, tol)) + } + _ => None, + } +} + +/// Whether `p` lies in one of the triangles `tris` (three points each). +fn in_triangles(tris: &[Vec2], p: Vec2) -> bool { + tris.as_chunks::<3>().0.iter().any(|t| point_in_polygon(t, p)) +} + +/// How far past `b`, the bounds the drawing gives `e`, what it draws can reach: a box picking +/// and crossing selection look for it in. Those bounds are estimates for words (a fixed width per +/// letter, which wide letters outgrow) and for dimensions (their defining points, which the words +/// of a radius placed outside the circle outgrow), so an object found by its bounds alone could not +/// be picked on its last letter or its words. Cheap on purpose: the spatial index measures every +/// object with it; the exact test runs on the few objects it lets through. +pub(crate) fn reach(d: &Drawing, e: &Entity, b: Bounds2) -> Bounds2 { + if b.is_empty() { + return b; + } + let pad = match &e.kind { + EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::MLeader(_) => 0.3 * b.width().max(b.height()), + EntityKind::Dimension(dm) => { + let th = d + .dim_style(&dm.style) + .map(|s| { + let s = s.with_overrides(&dm.overrides); + s.text_height * s.effective_scale(d.header.f64("DIMSCALE", 1.0)) + }) + .unwrap_or(0.18 * d.header.f64("DIMSCALE", 1.0)); + let f = match d.anno_draw(e) { + draftcraft_doc::AnnoDraw::Scaled(f) => f, + _ => 1.0, + }; + // Room for the words (a measurement or the text written over it), arrows and gaps. + let letters = dm.text.chars().count().clamp(12, 256) as f64; + th.abs() * f.abs() * (4.0 + letters) + } + _ => 0.0, + }; + if pad > 0.0 && pad.is_finite() { b.expand(pad) } else { b } +} + fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 { if pts.len() == 1 { return pts.first().map(|q| q.dist(p)).unwrap_or(f64::INFINITY); @@ -113,6 +166,10 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { { best = 0.0; } + // A polyline with width is picked anywhere in its band, not only on its centre line. + if best > 0.0 && wide_fill(e, tol).is_some_and(|t| in_triangles(&t, p)) { + best = 0.0; + } // A SOLID fills its polygon, not its bounding rectangle (half of which is empty for a triangle). if matches!(e.kind, EntityKind::Solid(_)) && e.kind.prims().iter().any(|prim| matches!(prim, Prim::Fill(poly) if point_in_polygon(poly, p))) { best = 0.0; @@ -287,7 +344,7 @@ pub(crate) fn pick_with(d: &Drawing, space: &Space, ix: &Option Vec, bx: &Bo if !infinite && bx.contains_box(&eb) { return true; } - if !crossing || (!infinite && !eb.intersects(bx)) { + if !crossing || (!infinite && !reach(d, e, eb).intersects(bx)) { return false; } let polys = hit_polylines(d, e, tol); @@ -377,6 +434,12 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option, bx: &Bo if hit || inside_text { return true; } + // A crossing box inside the band of a polyline with width touches what it draws. + if let Some(t) = wide_fill(e, tol) + && bx.corners().iter().any(|c| in_triangles(&t, *c)) + { + return true; + } // SOLID/TRACE are filled polygons. A crossing window wholly within the // fill must select them even when it does not touch their outline. Check // the polygon, not just its bounding rectangle (which can cover empty @@ -404,7 +467,7 @@ pub(crate) fn select_fence_with(d: &Drawing, space: &Space, ix: &Option>, bounds: Vec, + /// How far each entity can draw ([`crate::select::reach`]): the boxes in the tree. + reach: Vec, /// Local indices of xlines and rays (unbounded; always candidates for pick and crossing). infinite: Vec, } @@ -46,7 +48,7 @@ impl ChunkIx { let mut infinite = Vec::new(); // One block-bounds cache for the chunk: references to the same block measure it once. let mut cache = BlockBoundsCache::default(); - let bounds = items + let bounds: Vec = items .iter() .enumerate() .map(|(i, e)| { @@ -56,11 +58,14 @@ impl ChunkIx { entity_bounds_cached(d, e, 0, &mut cache) }) .collect(); + // The tree holds how far each object can draw ([`select::reach`]), so a pick on the last + // letter of a word or on a dimension's words finds it; the bounds stay for window tests. + let reach = items.iter().zip(&bounds).map(|(e, b)| crate::select::reach(d, e, *b)).collect(); let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - ChunkIx { serial, key, ents: items.to_vec(), bounds, infinite } + ChunkIx { serial, key, ents: items.to_vec(), bounds, reach, infinite } } fn items(&self) -> impl Iterator + '_ { - self.bounds.iter().enumerate().filter(|(_, b)| !b.is_empty()).map(|(i, b)| { + self.reach.iter().enumerate().filter(|(_, b)| !b.is_empty()).map(|(i, b)| { GeomWithData::new(Rectangle::from_corners([b.min.x, b.min.y], [b.max.x, b.max.y]), (self.serial, u32::try_from(i).unwrap_or(u32::MAX))) }) } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3a1537be..1c11467e 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -103,6 +103,7 @@ mod overkill; mod parallel_display_list; mod pedit_multiple; mod pedit_splinedit; +mod pick_audit; mod pick_text; mod pickdrag; mod pline_arc_xline_options; diff --git a/crates/engine/tests/it/pick_audit.rs b/crates/engine/tests/it/pick_audit.rs new file mode 100644 index 00000000..79a56e21 --- /dev/null +++ b/crates/engine/tests/it/pick_audit.rs @@ -0,0 +1,216 @@ +//! Picking against what is drawn, for every kind of object: a click on what an object draws +//! finds it, and a click well away from anything it draws (outside its fills and the boxes of its +//! words) finds nothing. Hit testing that runs along anything else (the outline of the object's +//! bounds, an estimate of its text, a stale shape) shows up here as a pick in empty space. + +use draftcraft_engine::Session; +use draftcraft_engine::doc::{Handle, Space}; +use draftcraft_engine::geom::{Bounds2, Vec2}; +use draftcraft_engine::render::{self, Kind}; +use draftcraft_engine::select::pick; +use serde_json::{Value, json}; + +/// The pick aperture (drawing units) the audit clicks with; the objects are tens of units across. +const AP: f64 = 0.25; + +fn dist_to_segment(p: Vec2, a: Vec2, b: Vec2) -> f64 { + let ab = b - a; + let l2 = ab.dot(ab); + let t = if l2 > 0.0 { ((p - a).dot(ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; + (a + ab * t - p).len() +} + +fn in_triangle(p: Vec2, a: Vec2, b: Vec2, c: Vec2) -> bool { + let s = |p1: Vec2, p2: Vec2, p3: Vec2| (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y); + let (d1, d2, d3) = (s(p, a, b), s(p, b, c), s(p, c, a)); + let neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0; + let pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0; + !(neg && pos) +} + +/// What `h` draws: its strokes (lines, curves, point markers, infinite lines as long segments), +/// its filled triangles, and the boxes around the strokes of its words. +struct Drawn { + strokes: Vec>, + tris: Vec<[Vec2; 3]>, + /// Filled areas picked on their frame only (a wipeout), not inside. + masks: Vec<[Vec2; 3]>, + words: Option, +} + +fn drawn(s: &Session, h: Handle) -> Drawn { + let d = s.doc().unwrap(); + let e = d.entity(h).unwrap(); + let build = |text: bool| { + render::build_entities(d, std::iter::once(e.as_ref()), &render::Options { tolerance: 0.005, text, linetypes: false, ..Default::default() }) + }; + let (full, bare) = (build(true), build(false)); + let key = |q: Vec2| (q.x.to_bits(), q.y.to_bits()); + let bare_pts: std::collections::HashSet<_> = bare.prims.iter().flat_map(|p| bare.points(p).iter().map(|q| key(*q))).collect(); + let mut out = Drawn { strokes: Vec::new(), tris: Vec::new(), masks: Vec::new(), words: None }; + for p in &full.prims { + let pts = full.points(p); + let text = !pts.iter().all(|q| bare_pts.contains(&key(*q))); + match p.kind { + Kind::Tris | Kind::Mask => { + let to = if matches!(p.kind, Kind::Mask) { &mut out.masks } else { &mut out.tris }; + to.extend(pts.as_chunks::<3>().0.iter().copied()); + } + Kind::Infinite { ray } => { + let (b, dir) = (pts[0], pts[1]); + out.strokes.push(vec![if ray { b } else { b - dir * 1e4 }, b + dir * 1e4]); + } + Kind::Point => out.strokes.push(vec![pts[0], pts[0]]), + _ => out.strokes.push(pts.to_vec()), + } + if text { + let b = Bounds2::from_points(pts.iter().copied()); + out.words = Some(out.words.map_or(b, |w| w.union(&b))); + } + } + out +} + +/// Where picking `h` disagrees with what it draws: on-stroke clicks that miss it, and clicks in +/// empty space that find it. +fn audit(s: &Session, h: Handle) -> Vec { + let d = s.doc().unwrap(); + let dr = drawn(s, h); + let mut bad = Vec::new(); + // On what it draws: a sample of segment midpoints and triangle centres. + let mut on: Vec = Vec::new(); + for st in &dr.strokes { + if st.len() == 2 && (st[1] - st[0]).len() > 1e3 { + on.push(st[0] + (st[1] - st[0]) * 0.5); + continue; + } + for w in st.windows(2) { + on.push(w[0] + (w[1] - w[0]) * 0.5); + } + if st.len() == 2 && st[0] == st[1] { + on.push(st[0]); + } + } + on.extend(dr.tris.iter().filter(|t| (t[1] - t[0]).cross(t[2] - t[0]).abs() > 1e-6).map(|t| (t[0] + t[1] + t[2]) * (1.0 / 3.0))); + let step = (on.len() / 150).max(1); + for p in on.iter().step_by(step) { + if pick(d, &Space::Model, *p, AP) != Some(h) { + bad.push(format!("misses its own drawing at ({:.2}, {:.2})", p.x, p.y)); + } + } + // Away from it: a grid over what it draws (infinite lines left out), each point farther + // than 4 apertures from every stroke and outside its fills and words. + let finite: Vec = dr.strokes.iter().filter(|st| !(st.len() == 2 && (st[1] - st[0]).len() > 1e3)).flatten().copied().collect(); + let b = Bounds2::from_points(finite.iter().copied().chain(dr.tris.iter().chain(&dr.masks).flatten().copied())); + let b = if b.is_empty() { Bounds2::new(Vec2::new(-20.0, -20.0), Vec2::new(20.0, 20.0)) } else { b.expand(5.0) }; + let n = 50; + for i in 0..=n { + for j in 0..=n { + let p = Vec2::new(b.min.x + b.width() * f64::from(i) / f64::from(n), b.min.y + b.height() * f64::from(j) / f64::from(n)); + let near = dr.strokes.iter().any(|st| { + if st.len() == 1 || (st.len() == 2 && st[0] == st[1]) { + return (st[0] - p).len() < 4.0 * AP; + } + st.windows(2).any(|w| dist_to_segment(p, w[0], w[1]) < 4.0 * AP) + }); + // In a fill, or within 4 apertures of its edge. + let filled = dr + .tris + .iter() + .chain(&dr.masks) + .any(|t| in_triangle(p, t[0], t[1], t[2]) || (0..3).any(|k| dist_to_segment(p, t[k], t[(k + 1) % 3]) < 4.0 * AP)); + let worded = dr.words.is_some_and(|w| w.expand(4.0 * AP).contains(p)); + if !near && !filled && !worded && pick(d, &Space::Model, p, AP) == Some(h) { + bad.push(format!("found in empty space at ({:.2}, {:.2})", p.x, p.y)); + } + } + } + bad +} + +/// A drawing with one object made by `cmd` (`helpers` first, erased after), and that object. +fn one(helpers: &[(&str, Value)], cmd: &str, params: Value) -> (Session, Handle) { + let mut s = Session::new(); + for (c, p) in helpers { + s.execute(c, p).unwrap(); + } + let before: Vec = s.doc().unwrap().model.iter().map(|e| e.handle).collect(); + s.execute(cmd, ¶ms).unwrap_or_else(|e| panic!("{cmd}: {e}")); + let h = s.doc().unwrap().model.iter().map(|e| e.handle).find(|h| !before.contains(h)).unwrap_or_else(|| panic!("{cmd} drew nothing")); + if !before.is_empty() { + let hexes: Vec = before.iter().map(|h| h.hex()).collect(); + s.execute("erase", &json!({ "handles": hexes })).unwrap(); + } + (s, h) +} + +fn cases() -> Vec<(&'static str, Session, Handle)> { + let rect = || ("rectang", json!({"p1": [0, 0], "p2": [40, 20]})); + let circ = || ("circle", json!({"center": [0, 0], "radius": 20})); + let mut v = Vec::new(); + let mut add = |name: &'static str, (s, h): (Session, Handle)| v.push((name, s, h)); + add("line", one(&[], "line", json!({"points": [[0, 0], [50, 20]]}))); + add("circle", one(&[], "circle", json!({"center": [0, 0], "radius": 20}))); + add("arc", one(&[], "arc", json!({"center": [0, 0], "radius": 20, "start": 30, "end": 200}))); + add("ellipse", one(&[], "ellipse", json!({"center": [0, 0], "major": [30, 0], "ratio": 0.4}))); + add("elliptical arc", one(&[], "ellipse", json!({"center": [0, 0], "major": [30, 0], "ratio": 0.4, "start": 0, "end": 210}))); + add("polyline with arcs", one(&[], "pline", json!({"vertices": [{"p": [0, 0]}, {"p": [30, 0], "bulge": 0.6}, {"p": [30, 20]}, {"p": [0, 25]}]}))); + add("wide polyline", one(&[], "pline", json!({"vertices": [[0, 0], [30, 0], [30, 20]], "width": 2}))); + add("tapered polyline", one(&[], "pline", json!({"vertices": [{"p": [0, 0], "startWidth": 0, "endWidth": 4}, {"p": [30, 0]}]}))); + add("rectangle", one(&[], "rectang", json!({"p1": [0, 0], "p2": [40, 20]}))); + add("polygon", one(&[], "polygon", json!({"sides": 6, "center": [0, 0], "radius": 20}))); + add("donut", one(&[], "donut", json!({"center": [0, 0], "inside": 10, "outside": 14}))); + add("revision cloud", one(&[], "revcloud", json!({"p1": [0, 0], "p2": [40, 20]}))); + add("spline", one(&[], "spline", json!({"fit": [[0, 0], [10, 15], [25, -5], [40, 10]]}))); + add("closed spline", one(&[], "spline", json!({"fit": [[0, 0], [20, 15], [40, 0], [20, -10]], "closed": true}))); + add("point", one(&[], "point", json!({"at": [5, 5]}))); + add("xline", one(&[], "xline", json!({"base": [0, 0], "through": [10, 5]}))); + add("ray", one(&[], "ray", json!({"base": [0, 0], "through": [10, 5]}))); + add("2D solid", one(&[], "solid", json!({"points": [[0, 0], [20, 0], [0, 20], [20, 20]]}))); + add("triangular solid", one(&[], "solid", json!({"points": [[0, 0], [30, 0], [0, 30]]}))); + add("text", one(&[], "text", json!({"at": [0, 0], "height": 5, "text": "HELLO WORLD"}))); + add("turned text", one(&[], "text", json!({"at": [0, 0], "height": 5, "text": "TURNED", "rotation": 35}))); + add("mtext", one(&[], "mtext", json!({"at": [0, 20], "height": 4, "text": "LINE ONE\\PLINE TWO"}))); + add("linear dimension", one(&[], "dimlinear", json!({"p1": [0, 0], "p2": [60, 0], "at": [30, 20]}))); + add("vertical dimension", one(&[], "dimlinear", json!({"p1": [0, 0], "p2": [0, 60], "at": [-20, 30]}))); + add("aligned dimension", one(&[], "dimaligned", json!({"p1": [0, 0], "p2": [40, 30], "at": [10, 30]}))); + add("radius dimension", one(&[circ()], "dimradius", json!({"center": [0, 0], "point": [14.14, 14.14]}))); + add("diameter dimension", one(&[circ()], "dimdiameter", json!({"center": [0, 0], "point": [14.14, 14.14]}))); + add("angular dimension", one(&[], "dimangular", json!({"vertex": [0, 0], "p1": [30, 0], "p2": [0, 30], "at": [20, 20]}))); + add("ordinate dimension", one(&[], "dimordinate", json!({"feature": [10, 10], "leader": [30, 30]}))); + add("leader", one(&[], "leader", json!({"points": [[0, 0], [20, 20], [30, 20]], "text": "NOTE"}))); + add("multileader", one(&[], "mleader", json!({"points": [[0, 0], [20, 20]], "text": "NOTE"}))); + add("pattern hatch", one(&[rect()], "hatch", json!({"points": [[20, 10]], "pattern": "ANSI31", "scale": 4, "associative": false}))); + add("solid hatch", one(&[rect()], "hatch", json!({"points": [[20, 10]], "pattern": "SOLID", "associative": false}))); + add("wipeout", one(&[], "wipeout", json!({"points": [[0, 0], [30, 0], [30, 20], [0, 20]]}))); + add("multiline", one(&[], "mline", json!({"points": [[0, 0], [40, 0], [40, 30]], "scale": 4}))); + add("table", one(&[], "table", json!({"at": [0, 0], "rows": 2, "cols": 2}))); + v +} + +#[test] +fn every_kind_of_object_is_picked_on_what_it_draws_and_nowhere_else() { + let mut report = Vec::new(); + for (name, mut s, h) in cases() { + // Alone (every object tested), then among enough others that picking goes through the + // spatial index, which finds candidates by their boxes. + for indexed in [false, true] { + if indexed { + let far: Vec = (0..400).map(|i| json!([10_000 + i * 3, 10_000])).collect(); + for p in far { + s.execute("point", &json!({ "at": p })).unwrap(); + } + } + let bad = audit(&s, h); + if !bad.is_empty() { + let how = if indexed { "indexed" } else { "alone" }; + report.push(format!( + "{name} ({how}): {} wrong picks, e.g. {}", + bad.len(), + bad.iter().take(3).cloned().collect::>().join("; ") + )); + } + } + } + assert!(report.is_empty(), "\n{}", report.join("\n")); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d6b35ed2..a44c3309 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -31,7 +31,7 @@ use draftcraft_geom::{Bounds2, Mat3, Polyline, Vec2}; use pen::Pen; pub use dim::{ArrowGeom, Arrowhead, DimGeometry, DimText, LineRole, arrowhead, dimension_geometry, dimension_geometry_with, format_linear_value}; -pub use fill::triangulate_evenodd; +pub use fill::{triangulate_evenodd, wide_polyline}; pub use hatch::{fill_loops as hatch_fill_loops, pattern_swatch}; pub use paper::{PAPER_SIZES, PaperSize, Sheet, paper_size, sheet}; pub use tolerance::{gdt_points, tolerance_in}; diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index aeef02e1..7ec10686 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1016,11 +1016,55 @@ fn paint_variant(p: &egui::Painter, r: Rect, cmd: &str) -> bool { #[derive(Default)] struct Out { command: Option<&'static str>, - layer: Option, + /// A property picked from a list of the Layers or Properties panel (see [`set_property`]). + prop: Option, run: Option<(&'static str, serde_json::Value)>, typed: Option, } +/// A property picked from a list of the Layers or Properties panel: `key` and `value` as CHPROP +/// takes them, and the command (with its parameters) that makes it the current one. +struct Prop { + key: &'static str, + value: serde_json::Value, + current: (&'static str, serde_json::Value), +} + +/// Apply a property picked from a ribbon list, as AutoCAD's layer and property controls do: with +/// objects selected it changes them (CHPROP, which leaves out those on locked layers and says +/// how many), and the current layer or property stays as it was; with nothing selected it becomes +/// the current one. +fn set_property(app: &mut CadApp, prop: Prop) { + let sel = app.session.selection(); + let r = if sel.is_empty() { + app.run(prop.current.0, prop.current.1) + } else { + let handles: Vec = sel.iter().map(|h| h.hex()).collect(); + let mut params = serde_json::Map::new(); + params.insert("handles".into(), json!(handles)); + params.insert(prop.key.into(), prop.value); + app.run("chprop", serde_json::Value::Object(params)).inspect(|r| match r.get("locked").and_then(serde_json::Value::as_u64).unwrap_or(0) { + 0 => {} + 1 => app.session.echo("1 object was on a locked layer."), + n => app.session.echo(format!("{n} objects were on a locked layer.")), + }) + }; + if let Err(e) = r { + app.set_status(e); + } +} + +/// What the selected objects share for one property: `None` with nothing selected, `Some(None)` +/// when they differ, `Some(Some(v))` when every one has `v`. The ribbon's lists show it in place +/// of the current value while objects are selected, as AutoCAD's do. +fn selection_shares(app: &CadApp, f: impl Fn(&draftcraft_engine::doc::Entity) -> T) -> Option> { + let sel = app.session.selection(); + let d = app.session.doc().ok()?; + let mut values = sel.iter().filter_map(|h| d.entity(*h)).map(|e| f(e)); + let first = values.next()?; + Some(values.all(|v| v == first).then_some(first)) +} + /// The application button: the DraftCraft logo ([`crate::brand`]) and the menu arrow. fn paint_app_button(p: &egui::Painter, r: Rect, hovered: bool) { let t = Tokens::get(); @@ -1045,8 +1089,8 @@ pub fn title_and_ribbon(app: &mut CadApp, ui: &mut egui::Ui) { ribbon(app, ui, Rect::from_min_max(pos2(r.left(), r.top() + APP_BAR), r.max), &mut out); } }); - if let Some(name) = out.layer { - let _ = app.run("layer.current", json!({ "name": name })); + if let Some(prop) = out.prop { + set_property(app, prop); } if let Some((cmd, params)) = out.run && let Err(e) = app.run(cmd, params) @@ -1448,7 +1492,7 @@ fn ribbon(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, out: &mut Out) { Layers(rows, labelled) => { let lr = Rect::from_min_size(pos2(cx, top + 1.0), vec2(cw - 8.0, ROW - 1.0)); if let Some(name) = layer_list(app, ui, lr, id.with("list")) { - out.layer = Some(name); + out.prop = Some(Prop { key: "layer", value: json!(name), current: ("layer.current", json!({ "name": name })) }); } for (ri, (row, last)) in rows.iter().zip(labelled.iter()).enumerate() { let y = top + (ri as f32 + 1.0) * (ROW + 1.0); @@ -1600,9 +1644,20 @@ fn lweight_name(code: i64) -> String { fn props_lists(app: &CadApp, ui: &mut egui::Ui, r: Rect, id: egui::Id, out: &mut Out) { let t = Tokens::get(); let Ok(d) = app.session.doc() else { return }; - let cecolor = d.header.i64("CECOLOR", 256); - let celtype = d.header.str("CELTYPE", "ByLayer"); - let celweight = d.header.i64("CELWEIGHT", -1); + // The selected objects' properties (none shown where they differ), else the current ones. + let color = match selection_shares(app, |e| e.common.color) { + Some(shared) => shared, + None => Some(draftcraft_color::Color::from_aci(d.header.i64("CECOLOR", 256).clamp(0, 256) as i16)), + }; + let cecolor = color.map(|c| i64::from(c.to_aci())); + let celtype = match selection_shares(app, |e| e.common.linetype.clone()) { + Some(shared) => shared, + None => Some(d.header.str("CELTYPE", "ByLayer").to_string()), + }; + let celweight = match selection_shares(app, |e| i64::from(e.common.lineweight.to_dxf())) { + Some(shared) => shared, + None => Some(d.header.i64("CELWEIGHT", -1)), + }; let linetypes: Vec = std::iter::once("ByLayer".to_string()) .chain(std::iter::once("ByBlock".to_string())) .chain(d.linetypes.iter().map(|l| l.name.clone()).filter(|n| !n.eq_ignore_ascii_case("bylayer") && !n.eq_ignore_ascii_case("byblock"))) @@ -1618,16 +1673,20 @@ fn props_lists(app: &CadApp, ui: &mut egui::Ui, r: Rect, id: egui::Id, out: &mut 0 => { paint_color_wheel(&p, icon_c, 8.0); let resp = list_box(ui, lr, id.with("color"), "Object Color"); - let color = draftcraft_color::Color::from_aci(cecolor.clamp(0, 256) as i16); - let rgb = color.resolve(draftcraft_color::Color::Index(7), draftcraft_color::Color::Index(7)); - let sw = Rect::from_min_size(pos2(lr.left() + 5.0, lr.center().y - 6.0), vec2(14.0, 12.0)); - p.rect_filled(sw, 1.0, Color32::from_rgb(rgb.0, rgb.1, rgb.2)); - let name = COLORS.iter().find(|c| c.1 == cecolor).map(|c| crate::i18n::t(c.0).to_string()).unwrap_or_else(|| color.name()); - p.with_clip_rect(lr.shrink(2.0)).text(pos2(sw.right() + 6.0, lr.center().y), Align2::LEFT_CENTER, name, label_font(), t.text); + if let Some(color) = color { + let rgb = color.resolve(draftcraft_color::Color::Index(7), draftcraft_color::Color::Index(7)); + let sw = Rect::from_min_size(pos2(lr.left() + 5.0, lr.center().y - 6.0), vec2(14.0, 12.0)); + p.rect_filled(sw, 1.0, Color32::from_rgb(rgb.0, rgb.1, rgb.2)); + let named = matches!(color, draftcraft_color::Color::True(_)).then(|| color.name()); + let name = named + .or_else(|| COLORS.iter().find(|c| Some(c.1) == cecolor).map(|c| crate::i18n::t(c.0).to_string())) + .unwrap_or_else(|| color.name()); + p.with_clip_rect(lr.shrink(2.0)).text(pos2(sw.right() + 6.0, lr.center().y), Align2::LEFT_CENTER, name, label_font(), t.text); + } egui::Popup::menu(&resp).width(w).show(|ui| { for (name, aci) in COLORS { - if ui.selectable_label(*aci == cecolor, crate::i18n::t(name)).clicked() { - out.run = Some(("color", json!({ "color": name }))); + if ui.selectable_label(Some(*aci) == cecolor, crate::i18n::t(name)).clicked() { + out.prop = Some(Prop { key: "color", value: json!(name), current: ("color", json!({ "color": name })) }); ui.close(); } } @@ -1643,19 +1702,21 @@ fn props_lists(app: &CadApp, ui: &mut egui::Ui, r: Rect, id: egui::Id, out: &mut p.hline(icon_c.x - 8.0..=icon_c.x + 8.0, icon_c.y - 5.0 + k as f32 * 5.0, Stroke::new(1.5, t.icon)); } let resp = list_box(ui, lr, id.with("ltype"), "Linetype"); - p.hline(lr.left() + 6.0..=lr.left() + 50.0, lr.center().y, Stroke::new(1.0, t.text)); - p.with_clip_rect(lr.shrink(2.0)).text( - pos2(lr.right() - 18.0, lr.center().y), - Align2::RIGHT_CENTER, - crate::i18n::t(&celtype), - label_font(), - t.text, - ); + if let Some(celtype) = &celtype { + p.hline(lr.left() + 6.0..=lr.left() + 50.0, lr.center().y, Stroke::new(1.0, t.text)); + p.with_clip_rect(lr.shrink(2.0)).text( + pos2(lr.right() - 18.0, lr.center().y), + Align2::RIGHT_CENTER, + crate::i18n::t(celtype), + label_font(), + t.text, + ); + } egui::Popup::menu(&resp).width(w).show(|ui| { egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { for name in &linetypes { - if ui.selectable_label(name.eq_ignore_ascii_case(&celtype), crate::i18n::t(name)).clicked() { - out.run = Some(("linetype", json!({ "current": name }))); + if ui.selectable_label(celtype.as_ref().is_some_and(|c| name.eq_ignore_ascii_case(c)), crate::i18n::t(name)).clicked() { + out.prop = Some(Prop { key: "linetype", value: json!(name), current: ("linetype", json!({ "current": name })) }); ui.close(); } } @@ -1672,25 +1733,27 @@ fn props_lists(app: &CadApp, ui: &mut egui::Ui, r: Rect, id: egui::Id, out: &mut p.hline(icon_c.x - 8.0..=icon_c.x + 8.0, icon_c.y - 5.0 + k as f32 * 5.0, Stroke::new(0.8 + k as f32, t.icon)); } let resp = list_box(ui, lr, id.with("lweight"), "Lineweight"); - p.hline(lr.left() + 6.0..=lr.left() + 50.0, lr.center().y, Stroke::new(1.0, t.text)); - p.with_clip_rect(lr.shrink(2.0)).text( - pos2(lr.right() - 18.0, lr.center().y), - Align2::RIGHT_CENTER, - crate::i18n::t(&lweight_name(celweight)), - label_font(), - t.text, - ); + if let Some(celweight) = celweight { + p.hline(lr.left() + 6.0..=lr.left() + 50.0, lr.center().y, Stroke::new(1.0, t.text)); + p.with_clip_rect(lr.shrink(2.0)).text( + pos2(lr.right() - 18.0, lr.center().y), + Align2::RIGHT_CENTER, + crate::i18n::t(&lweight_name(celweight)), + label_font(), + t.text, + ); + } egui::Popup::menu(&resp).width(w).show(|ui| { egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { for code in LWEIGHTS { - if ui.selectable_label(*code == celweight, crate::i18n::t(&lweight_name(*code))).clicked() { + if ui.selectable_label(Some(*code) == celweight, crate::i18n::t(&lweight_name(*code))).clicked() { let v = match code { -1 => json!("ByLayer"), -2 => json!("ByBlock"), -3 => json!("Default"), c => json!(*c as f64 / 100.0), }; - out.run = Some(("lweight", json!({ "lineweight": v }))); + out.prop = Some(Prop { key: "lineweight", value: v.clone(), current: ("lweight", json!({ "lineweight": v })) }); ui.close(); } } @@ -1710,7 +1773,11 @@ fn layer_list(app: &CadApp, ui: &mut egui::Ui, rect: Rect, id: egui::Id) -> Opti p.rect_filled(rect, 2.0, t.chrome_dark); return None; }; - let cur = d.header.str("CLAYER", "0"); + // The selected objects' layer (none when they differ), else the current one. + let cur = match selection_shares(app, |e| e.common.layer.clone()) { + Some(shared) => shared.unwrap_or_default(), + None => d.header.str("CLAYER", "0").to_string(), + }; let layers: Vec<(String, bool, bool, bool, Color32)> = d .layers .iter() @@ -1764,6 +1831,74 @@ fn layer_list(app: &CadApp, ui: &mut egui::Ui, rect: Rect, id: egui::Id) -> Opti mod tests { use super::*; + fn layer_of(app: &CadApp, h: draftcraft_engine::doc::Handle) -> String { + app.session.doc().unwrap().entity(h).unwrap().common.layer.clone() + } + + /// The ribbon's layer list moves the selected objects to the layer picked, leaving the + /// current layer alone; with nothing selected it sets the current layer. Objects on locked + /// layers stay where they are, and the command line says so. + #[test] + fn the_layer_list_moves_the_selection_to_the_layer() { + let mut app = CadApp::new(draftcraft_engine::Session::new(), crate::Services::default()); + app.session.cmdline("line 0,0 10,0").unwrap(); + app.session.cmdline("").unwrap(); + app.session.cmdline("circle 50,50 5").unwrap(); + let d = app.session.doc_mut().unwrap(); + d.ensure_layer("Walls"); + d.ensure_layer("Doors"); + let hs: Vec<_> = d.model.iter().map(|e| e.handle).collect(); + let (line, circle) = (hs[0], hs[1]); + let pick = |name: &str| Prop { key: "layer", value: json!(name), current: ("layer.current", json!({ "name": name })) }; + // Both selected: both move, CLAYER stays 0, the selection stays. + app.session.set_selection(vec![line, circle]); + assert_eq!(selection_shares(&app, |e| e.common.layer.clone()), Some(Some("0".to_string()))); + set_property(&mut app, pick("Walls")); + assert_eq!((layer_of(&app, line), layer_of(&app, circle)), ("Walls".into(), "Walls".into())); + assert_eq!(app.session.doc().unwrap().header.str("CLAYER", "0"), "0"); + assert_eq!(app.session.selection(), vec![line, circle]); + // One of them on another layer: the list shows none. + app.session.set_selection(vec![line]); + set_property(&mut app, pick("Doors")); + app.session.set_selection(vec![line, circle]); + assert_eq!(selection_shares(&app, |e| e.common.layer.clone()), Some(None)); + // Nothing selected: the current layer changes, no object does. + app.session.set_selection(Vec::new()); + assert_eq!(selection_shares(&app, |e| e.common.layer.clone()), None); + set_property(&mut app, pick("Walls")); + assert_eq!(app.session.doc().unwrap().header.str("CLAYER", "0"), "Walls"); + assert_eq!(layer_of(&app, line), "Doors"); + // On a locked layer: left alone, and said. + if let Some(l) = app.session.doc_mut().unwrap().layer_mut("Doors") { + l.locked = true; + } + app.session.set_selection(vec![line, circle]); + set_property(&mut app, pick("0")); + assert_eq!((layer_of(&app, line), layer_of(&app, circle)), ("Doors".into(), "0".into())); + assert!(app.session.log.iter().any(|m| m == "1 object was on a locked layer."), "{:?}", app.session.log); + } + + /// The colour, linetype and lineweight lists change the selected objects too. + #[test] + fn the_property_lists_change_the_selection() { + let mut app = CadApp::new(draftcraft_engine::Session::new(), crate::Services::default()); + app.session.cmdline("circle 0,0 5").unwrap(); + let h = app.session.doc().unwrap().model.last().unwrap().handle; + app.session.set_selection(vec![h]); + set_property(&mut app, Prop { key: "color", value: json!("Red"), current: ("color", json!({ "color": "Red" })) }); + set_property(&mut app, Prop { key: "lineweight", value: json!(0.5), current: ("lweight", json!({ "lineweight": 0.5 })) }); + set_property(&mut app, Prop { key: "linetype", value: json!("ByBlock"), current: ("linetype", json!({ "current": "ByBlock" })) }); + let d = app.session.doc().unwrap(); + let e = d.entity(h).unwrap(); + assert_eq!(e.common.color, draftcraft_color::Color::Index(1)); + assert_eq!(e.common.lineweight.to_dxf(), 50); + assert!(e.common.linetype.eq_ignore_ascii_case("ByBlock")); + // The current properties stay as they were. + assert_eq!(d.header.i64("CECOLOR", 256), 256); + assert_eq!(d.header.i64("CELWEIGHT", -1), -1); + assert_eq!(selection_shares(&app, |e| e.common.color), Some(Some(draftcraft_color::Color::Index(1)))); + } + #[test] fn every_ribbon_command_exists() { let mut missing = Vec::new();