From f474a27fad11078e5b7c987b53745ab7db178d9e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 20 Nov 2026 01:45:59 -0700 Subject: [PATCH] Stack d1: fix review findings on array key points, -ATTEDIT and layer states ARRAYEDIT reads both key points before it resets or replaces items, so a bad one changes nothing, and a new base point keeps replaced items in place (their blocks' base points move with the source block's). A key point of a circle under an uneven array scale is one of the ellipse it is drawn as. -ATTEDIT measures a picked height or angle from the point the text is placed by, Angle turns an aligned or fit attribute's baseline, and Position, Height, Angle and Style change a multiline attribute's text too. Reading layer states charges the file's budget for the strings each entry writes, updates included. --- crates/engine/src/cmd/array.rs | 39 +++++++++- crates/engine/src/cmd/array/edit.rs | 34 +++++++- crates/engine/src/cmd/blocks/attedit.rs | 55 ++++++++++++- crates/engine/tests/it/assoc_array.rs | 35 +++++++++ crates/engine/tests/it/attedit_prompts.rs | 95 +++++++++++++++++++++++ crates/io/src/dxf_layer_states.rs | 47 ++++++++++- 6 files changed, 294 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 843fb1ccb..5bb6bec34 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -257,13 +257,30 @@ pub(crate) fn nearest_key_point<'a>(ents: impl Iterator, m: & if !at.is_finite() { return Ok(None); } + let stretched = m.similarity_scale().is_none(); let mut best: Option<(Vec2, f64)> = None; for (n, e) in ents.enumerate() { if n >= MAX_KEY_OBJECTS { return Err(other(format!("Too many objects to search for a key point (at most {MAX_KEY_OBJECTS}); specify a point."))); } - let mut k = e.kind.clone(); - k.transform(m); + let k = match &e.kind { + // Under an uneven scale a circle is drawn as an ellipse: its key points are the ellipse's. + EntityKind::Circle(c) if stretched => { + let g = cadcraft_geom::Ellipse::full(c.center.xy(), Vec2::X * c.radius, 1.0).transformed(m); + EntityKind::Ellipse(cadcraft_doc::Ellipse { + center: g.center.to3(c.center.z), + major: g.major.to3(0.0), + ratio: g.ratio, + start: g.start, + end: g.end, + }) + } + kind => { + let mut k = kind.clone(); + k.transform(m); + k + } + }; for g in k.grips().into_iter().filter(|g| g.is_finite()) { let d = g.dist(at); if best.is_none_or(|(_, bd)| d < bd) { @@ -1295,4 +1312,22 @@ mod tests { let c = at(&polar(4, -360.0)); assert!(c[2].near(Vec2::new(0.0, 1.0), 1e-9)); } + + #[test] + fn a_circle_under_an_uneven_scale_offers_the_drawn_ellipses_key_points() { + let c = Entity { + handle: Handle(1), + common: Default::default(), + kind: EntityKind::Circle(cadcraft_doc::Circle { center: v3(Vec2::ZERO), radius: 1.0 }), + }; + // Scaled (2, 1) the circle is drawn as an ellipse with semi-axes 2 and 1. + let m = Mat3::scale(2.0, 1.0); + let key = |at: Vec2| nearest_key_point(std::iter::once(&c), &m, at).unwrap().unwrap(); + assert!(key(Vec2::new(0.1, 1.2)).near(Vec2::new(0.0, 1.0), 1e-9), "{:?}", key(Vec2::new(0.1, 1.2))); + assert!(key(Vec2::new(2.2, 0.1)).near(Vec2::new(2.0, 0.0), 1e-9), "{:?}", key(Vec2::new(2.2, 0.1))); + // A uniform scale keeps the circle. + let m = Mat3::scale(2.0, 2.0); + let k = nearest_key_point(std::iter::once(&c), &m, Vec2::new(0.1, 2.2)).unwrap().unwrap(); + assert!(k.near(Vec2::new(0.0, 2.0), 1e-9), "{k:?}"); + } } diff --git a/crates/engine/src/cmd/array/edit.rs b/crates/engine/src/cmd/array/edit.rs index 952c785f0..bce421bab 100644 --- a/crates/engine/src/cmd/array/edit.rs +++ b/crates/engine/src/cmd/array/edit.rs @@ -244,6 +244,30 @@ fn rebase(s: &mut Session, h: Handle, base: Vec2) -> Result<()> { ns.name = d.anonymous_block_name("*U"); p.source.clone_from(&ns.name); d.blocks.insert(ns.name.clone(), Arc::new(ns)); + // A replacement is placed as the source is, so its base point moves the same way (each block + // once, however many items share it). Records no item uses keep their names. + let used: Vec = { + let block_for = p.block_lookup(); + p.replaced.iter().map(|r| block_for(r.i, r.j, r.level) == r.block).collect() + }; + let mut moved: HashMap = HashMap::new(); + for (r, used) in p.replaced.iter_mut().zip(used) { + if !used { + continue; + } + let key = r.block.to_ascii_uppercase(); + if let Some(n) = moved.get(&key) { + r.block.clone_from(n); + continue; + } + let Some(rb) = d.block(&r.block).cloned() else { continue }; + let mut nb = (*rb).clone(); + nb.base = (nb.base.xy() + b).to3(nb.base.z); + nb.name = d.anonymous_block_name("*U"); + moved.insert(key, nb.name.clone()); + r.block.clone_from(&nb.name); + d.blocks.insert(nb.name.clone(), Arc::new(nb)); + } if let ArrayKind::Polar(k) = &mut p.kind { k.center -= b; } @@ -465,14 +489,18 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result { let h = super::super::curves::handle_param(p, "handle").ok_or_else(|| bad("arrayedit", "`handle` (the array) is required"))?; refuse_while_editing(s)?; array_of(s.doc()?, h)?; + // Both key points are read before anything changes: a bad one leaves the array as it was. + let replace = p.get("replace").filter(|v| !v.is_null()); + let rep_key = replace.map(|r| key_point_param("arrayedit", r)).transpose()?.flatten(); + let key = key_point_param("arrayedit", p)?; if bool_or(p, "reset", false) { let (_, _, mut a) = array_of(s.doc()?, h)?; a.replaced.clear(); rebuild(s, h, a, None)?; } - if let Some(r) = p.get("replace").filter(|v| !v.is_null()) { + if let Some(r) = replace { let hs = targets(s, r)?; - let base = match key_point_param("arrayedit", r)? { + let base = match rep_key { Some(k) => key_point_of(s.doc()?, &hs, k)?, None => point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()), }; @@ -493,7 +521,7 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result { if let Some(b) = point_param(p, "base") { rebase(s, h, b)?; } - if let Some(k) = key_point_param("arrayedit", p)? { + if let Some(k) = key { let at = source_key_point(s.doc()?, h, k, KEY_POINT_TOLERANCE)?; rebase(s, h, at)?; } diff --git a/crates/engine/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index 2ee9358cc..e86826265 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -167,6 +167,34 @@ fn move_text(text: &mut Text, to: cadcraft_geom::Vec2) { text.align_pt = text.align_pt.map(|ap| ap + d); } +/// Move attribute `a` so the point it is placed by lands on `to`. A multiline attribute is drawn +/// as its multiline text: that text's insertion point lands on `to`, and the single-line text +/// moves with it. +fn move_attrib(a: &mut cadcraft_doc::Attrib, to: cadcraft_geom::Vec2) { + match &mut a.multiline { + Some(m) => { + let d = Vec3::new(to.x - m.mtext.insert.x, to.y - m.mtext.insert.y, 0.0); + m.mtext.insert = m.mtext.insert + d; + a.text.insert = a.text.insert + d; + a.text.align_pt = a.text.align_pt.map(|ap| ap + d); + } + None => move_text(&mut a.text, to), + } +} + +/// Turn `text` to angle `ang` (radians). Aligned and fit text is drawn along its baseline from +/// the insertion point to the alignment point, so that baseline turns about the insertion point, +/// its length kept. +fn turn_text(text: &mut Text, ang: f64) { + text.rotation = ang; + if matches!(text.halign, HAlign::Aligned | HAlign::Fit) + && let Some(ap) = text.align_pt + { + let to = text.insert.xy() + cadcraft_geom::Vec2::from_angle(ang) * ap.xy().dist(text.insert.xy()); + text.align_pt = Some(to.to3(ap.z)); + } +} + /// Change the properties set on attribute `k` of block reference `h`. fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut AttribProps)) -> Result<()> { s.doc_mut()?.modify_entity(h, |e| { @@ -214,6 +242,16 @@ fn current_text(s: &Session, (h, k): (Handle, usize)) -> Option Option { + let d = s.doc().ok()?; + let EntityKind::Insert(ins) = &d.entity(h)?.kind else { return None }; + let a = ins.attribs.get(k)?; + Some(a.multiline.as_ref().map_or_else(|| a.text.justify_point(), |m| m.mtext.insert.xy())) +} + /// Replace every `find` in `value` with `with`, unless the result would be too long. fn replaced(value: &str, find: &str, with: &str) -> Option { if find.is_empty() || !value.contains(find) { @@ -555,14 +593,14 @@ impl Interactive for DashAtteditM { _ => return Ok(Step::Continue), }; if let Some(it) = self.items.get(self.cur).copied() { - modify_attrib(s, it, |a| move_text(&mut a.text, p))?; + modify_attrib(s, it, |a| move_attrib(a, p))?; } self.stage = Stage::Option; } Stage::Height => { let h = match &i { Input::Point(p) => { - let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy()); + let cur_pt = self.items.get(self.cur).and_then(|it| placement_point(s, *it)); match cur_pt { Some(base) => base.dist(*p).max(1e-9), None => p.len().max(1e-9), @@ -580,6 +618,9 @@ impl Interactive for DashAtteditM { if let Some(it) = self.items.get(self.cur).copied() { modify_attrib(s, it, |a| { a.text.height = h; + if let Some(m) = &mut a.multiline { + m.mtext.height = h; + } })?; } self.stage = Stage::Option; @@ -587,7 +628,7 @@ impl Interactive for DashAtteditM { Stage::Angle => { let ang = match &i { Input::Point(p) => { - let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy()); + let cur_pt = self.items.get(self.cur).and_then(|it| placement_point(s, *it)); match cur_pt { Some(base) => base.angle_to(*p), None => p.y.atan2(p.x), @@ -604,7 +645,10 @@ impl Interactive for DashAtteditM { }; if let Some(it) = self.items.get(self.cur).copied() { modify_attrib(s, it, |a| { - a.text.rotation = ang; + turn_text(&mut a.text, ang); + if let Some(m) = &mut a.multiline { + m.mtext.rotation = ang; + } })?; } self.stage = Stage::Option; @@ -617,6 +661,9 @@ impl Interactive for DashAtteditM { s.doc()?.text_style(t).map(|st| st.name.clone()).ok_or_else(|| EngineError::Other(format!("Cannot find style \"{t}\".")))?; if let Some(it) = self.items.get(self.cur).copied() { modify_attrib(s, it, |a| { + if let Some(m) = &mut a.multiline { + m.mtext.style.clone_from(&st); + } a.text.style = st; })?; } diff --git a/crates/engine/tests/it/assoc_array.rs b/crates/engine/tests/it/assoc_array.rs index f672176b3..0f199d470 100644 --- a/crates/engine/tests/it/assoc_array.rs +++ b/crates/engine/tests/it/assoc_array.rs @@ -296,6 +296,41 @@ fn arrayedit_base_replace_and_reset() { assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 4); } +#[test] +fn a_new_base_point_keeps_replaced_items_in_place() { + let mut s = Session::new(); + let a = rect_array(&mut s); + // Item 1 (at 2,0) becomes a circle one unit to its right. + let c = circle(&mut s, 3.0, 10.0); + s.execute("arrayedit", &json!({"handle": a, "replace": {"handles": [c], "base": [2, 10], "items": [[1, 0, 0]]}})).unwrap(); + assert_eq!(centres(&s, &a), vec![(0, 0), (3000, 0), (4000, 0)]); + // Neither a new base point nor a key point moves the replacement (or the other items). + s.execute("arrayedit", &json!({"handle": a, "base": [7, 7]})).unwrap(); + assert_eq!(centres(&s, &a), vec![(0, 0), (3000, 0), (4000, 0)]); + s.execute("arrayedit", &json!({"handle": a, "keyPoint": [4, 0.9]})).unwrap(); + assert_eq!(centres(&s, &a), vec![(0, 0), (3000, 0), (4000, 0)]); + // The replacement still counts from its item. + s.execute("arrayedit", &json!({"handle": a, "colSpacing": 4})).unwrap(); + assert_eq!(centres(&s, &a), vec![(0, 0), (5000, 0), (8000, 0)]); +} + +#[test] +fn a_bad_key_point_refuses_arrayedit_before_reset_or_replace() { + let mut s = Session::new(); + let a = rect_array(&mut s); + let l = s.execute("line", &json!({"points": [[0, 20], [1, 20]]})).unwrap()["handles"][0].clone(); + s.execute("arrayedit", &json!({"handle": a, "replace": {"handles": [l], "base": [0, 20], "items": [[1, 0, 0]]}})).unwrap(); + let c = s.execute("line", &json!({"points": [[50, 50], [51, 50]]})).unwrap()["handles"][0].clone(); + for bad in [ + json!({"handle": a, "reset": true, "keyPoint": "bad"}), + json!({"handle": a, "reset": true, "replace": {"handles": [c], "keyPoint": [1], "items": [[0, 0, 0]]}}), + json!({"handle": a, "replace": {"handles": [c], "items": [[2, 0, 0]]}, "keyPoint": {"x": 1}}), + ] { + assert!(s.execute("arrayedit", &bad).is_err(), "{bad}"); + assert_eq!((centres(&s, &a), lines_in(&s, &a)), (vec![(0, 0), (4000, 0)], 1), "{bad}"); + } +} + #[test] fn arrayedit_source_then_arrayclose() { let mut s = Session::new(); diff --git a/crates/engine/tests/it/attedit_prompts.rs b/crates/engine/tests/it/attedit_prompts.rs index 15fd5e7aa..7a7d47304 100644 --- a/crates/engine/tests/it/attedit_prompts.rs +++ b/crates/engine/tests/it/attedit_prompts.rs @@ -148,3 +148,98 @@ fn dash_attedit_position_keeps_an_aligned_attributes_baseline() { assert!(t.align_pt.is_some_and(|p| p.xy().near(cadcraft_geom::Vec2::new(14.0, 20.0), 1e-9)), "{halign:?}: {:?}", t.align_pt); } } + +/// Change attribute T of reference `h` in place. +fn set_t(s: &mut Session, h: Handle, f: impl Fn(&mut cadcraft_doc::Attrib)) { + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + for a in i.attribs.iter_mut().filter(|a| a.tag == "T") { + f(a); + } + } + }) + .unwrap(); +} + +fn attrib_t(s: &Session, h: Handle) -> cadcraft_doc::Attrib { + let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") }; + i.attribs.iter().find(|a| a.tag == "T").unwrap().clone() +} + +/// -ATTEDIT Angle turns an aligned or fit attribute's baseline (which sets its direction) about +/// its insertion point, keeping its length. +#[test] +fn dash_attedit_angle_turns_an_aligned_attributes_baseline() { + use cadcraft_doc::HAlign; + use cadcraft_geom::{Vec2, Vec3}; + for halign in [HAlign::Aligned, HAlign::Fit] { + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"}))); + set_t(&mut s, h, |a| { + a.text.halign = halign; + a.text.insert = Vec3::new(100.0, 1.0, 0.0); + a.text.align_pt = Some(Vec3::new(104.0, 1.0, 0.0)); + }); + type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", "", "a", "90", "n"]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let t = attrib_t(&s, h).text; + assert!(t.insert.xy().near(Vec2::new(100.0, 1.0), 1e-9), "{halign:?}: {:?}", t.insert); + assert!(t.align_pt.is_some_and(|p| p.xy().near(Vec2::new(100.0, 5.0), 1e-9)), "{halign:?}: {:?}", t.align_pt); + assert!((t.rotation.to_degrees() - 90.0).abs() < 1e-9, "{halign:?}: {}", t.rotation); + } +} + +/// A height or angle picked at -ATTEDIT is measured from the point the text is placed by: the +/// alignment point of justified text. +#[test] +fn dash_attedit_picked_height_and_angle_start_at_the_justification_point() { + use cadcraft_doc::HAlign; + use cadcraft_geom::Vec3; + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"}))); + set_t(&mut s, h, |a| { + a.text.halign = HAlign::Center; + a.text.insert = Vec3::new(100.0, 1.0, 0.0); + a.text.align_pt = Some(Vec3::new(110.0, 1.0, 0.0)); + }); + type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", "", "h", "110,6", "a", "110,6", "n"]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let t = attrib_t(&s, h).text; + assert!((t.height - 5.0).abs() < 1e-9, "{}", t.height); + assert!((t.rotation.to_degrees() - 90.0).abs() < 1e-9, "{}", t.rotation.to_degrees()); +} + +/// A multiline attribute is drawn as its multiline text: -ATTEDIT Position, Height and Angle +/// change that text, and a picked angle starts at its insertion point. +#[test] +fn dash_attedit_edits_a_multiline_attributes_text() { + use cadcraft_doc::{MText, MultilineAttrib}; + use cadcraft_geom::{Vec2, Vec3}; + let mut s = with_block(); + let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"}))); + let mtext = MText { + insert: Vec3::new(120.0, 3.0, 0.0), + height: 2.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "abc".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + set_t(&mut s, h, |a| a.multiline = Some(MultilineAttrib { mtext: mtext.clone(), read_as: "abc".into() })); + let before = attrib_t(&s, h).text.insert; + type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", "", "p", "10,20", "h", "2.5", "a", "10,30", "n"]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let a = attrib_t(&s, h); + let m = a.multiline.as_ref().unwrap().mtext.clone(); + assert!(m.insert.xy().near(Vec2::new(10.0, 20.0), 1e-9), "{:?}", m.insert); + // The single-line text moves with it. + assert!((a.text.insert - before).xy().near(Vec2::new(-110.0, 17.0), 1e-9), "{:?}", a.text.insert); + assert!((m.height - 2.5).abs() < 1e-9 && (a.text.height - 2.5).abs() < 1e-9, "{} {}", m.height, a.text.height); + assert!((m.rotation.to_degrees() - 90.0).abs() < 1e-9, "{}", m.rotation.to_degrees()); +} diff --git a/crates/io/src/dxf_layer_states.rs b/crates/io/src/dxf_layer_states.rs index babb20780..471659815 100644 --- a/crates/io/src/dxf_layer_states.rs +++ b/crates/io/src/dxf_layer_states.rs @@ -185,12 +185,18 @@ pub(crate) fn read(name: &str, tags: &[Tag], lookup: &Lookup, budget: &mut usize at += len; let groups = group.get(1..len).unwrap_or_default(); let key = head.str().trim().to_ascii_uppercase(); + // The layer as the entry leaves it is charged, the strings the entry wrote included; an + // update is charged what it adds to the copy it replaces. if let Some(slot) = index.get(&key).and_then(|&i| st.layers.get_mut(i)) { - entry(slot, groups, lookup); + let mut l = slot.clone(); + entry(&mut l, groups, lookup); + let Some(left) = budget.checked_add(cost(slot)).and_then(|b| b.checked_sub(cost(&l))) else { break }; + *budget = left; + *slot = l; } else if let Some(mut l) = (lookup.layer)(&head.str()) { + entry(&mut l, groups, lookup); let Some(left) = budget.checked_sub(cost(&l)) else { break }; *budget = left; - entry(&mut l, groups, lookup); index.insert(key, st.layers.len()); st.layers.push(l); } @@ -291,4 +297,41 @@ mod tests { let st = read("T", &tags(&[("B1", 2)]), &lookup, &mut budget); assert!(st.layers.is_empty()); } + + #[test] + fn the_budget_is_charged_for_the_strings_an_entry_writes() { + let layer = |h: &str| (h == "A1").then(|| Layer::new("A")); + let none = |_: &str| None::; + let lookup = Lookup { layer: &layer, ltype: &none, pstyle: &none, colour_dependent: false }; + let long = "P".repeat(4096); + // A state's groups with an entry of layer A per plot style (group 1). + let styled = |styles: &[&str]| { + let mut t = tags(&[]); + for s in styles { + t.extend([Tag::s(330, "A1"), Tag::i(90, 8), Tag::s(1, *s)]); + } + t + }; + let short = |style: &str| { + let mut l = Layer::new("A"); + l.plot_style = style.to_string(); + cost(&l) + }; + // A copy is charged with the plot style its entry wrote: one the budget can't cover is left out. + let mut budget = short("S") + 100; + let st = read("S", &styled(&[long.as_str()]), &lookup, &mut budget); + assert!(st.layers.is_empty()); + let mut budget = MAX_COPIED_BYTES; + let st = read("S", &styled(&[long.as_str()]), &lookup, &mut budget); + assert_eq!(MAX_COPIED_BYTES - budget, short(long.as_str())); + // A later entry of the same layer is charged what it adds; past the budget it is left out, + // and one that adds nothing still applies. + let mut budget = short("S") + 100; + let st = read("S", &styled(&["S", long.as_str()]), &lookup, &mut budget); + assert_eq!(st.layers.iter().map(|l| l.plot_style.as_str()).collect::>(), ["S"]); + assert_eq!(budget, 100); + let mut budget = short("SS"); + let st = read("S", &styled(&["SS", "T"]), &lookup, &mut budget); + assert_eq!((st.layers.iter().map(|l| l.plot_style.as_str()).collect::>(), budget), (vec!["T"], 1)); + } }