From c3ce8633efe198df6069d10a41ab207d4d0142ed Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Wed, 28 Oct 2026 00:32:31 +0100 Subject: [PATCH 1/3] BATTMAN: Verify, Preset, Lock position and Multiple lines for attribute definitions (F17) The Block Attribute Manager switches a definition's Verify, Preset and Lock position modes and makes it multiline (with a width) or single-line again, from its dialog's check boxes, the command line's Edit options and the JSON form, which also lists them. References follow as ATTSYNC makes them, keeping their values; a multi-line value goes on one line when its definition does. The dialog's Block and Layer lists get accessible names. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/blocks/attribs.rs | 4 + crates/engine/src/cmd/blocks/battman.rs | 134 +++++++++++++- crates/engine/tests/it/attribute_tools.rs | 6 +- crates/engine/tests/it/battman_modes.rs | 175 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/managers/battman.rs | 53 ++++-- .../ui-egui/tests/it/battman_modes_dialog.rs | 62 +++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/file-format-parity.md | 5 +- docs/gaps.md | 5 +- 10 files changed, 421 insertions(+), 25 deletions(-) create mode 100644 crates/engine/tests/it/battman_modes.rs create mode 100644 crates/ui-egui/tests/it/battman_modes_dialog.rs diff --git a/crates/engine/src/cmd/blocks/attribs.rs b/crates/engine/src/cmd/blocks/attribs.rs index 8b51cae5d3..c209e6cba9 100644 --- a/crates/engine/src/cmd/blocks/attribs.rs +++ b/crates/engine/src/cmd/blocks/attribs.rs @@ -113,6 +113,10 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec .find(|a| a.tag.eq_ignore_ascii_case(&ad.tag)) .map(|a| a.text.value.clone()) .unwrap_or_else(|| ad.text.value.clone()); + // A value of several lines, kept from a multiline attribute, on one line. + if ad.multiline.is_none() && t.value.contains('\n') { + t.value = super::battman::single_line(&t.value); + } Attrib { tag: ad.tag.clone(), text: t, diff --git a/crates/engine/src/cmd/blocks/battman.rs b/crates/engine/src/cmd/blocks/battman.rs index c9c1dc14e0..964c94c4c7 100644 --- a/crates/engine/src/cmd/blocks/battman.rs +++ b/crates/engine/src/cmd/blocks/battman.rs @@ -1,10 +1,10 @@ //! BATTMAN: the attribute definitions of a block — listed, edited (tag, prompt, default value, -//! modes, height, layer), removed and reordered. Changes are applied to the existing references +//! modes, multiple lines, height, layer), removed and reordered. Changes are applied to the existing references //! (as ATTSYNC does) unless `sync` is false. Tags match in any case, as in AutoCAD. use std::sync::Arc; -use cadcraft_doc::{Attrib, Block, EntityKind, EntityStore, Handle}; +use cadcraft_doc::{Attrib, Block, EntityKind, EntityStore, Handle, MText, MultilineAttrib, mtext_literal}; use serde_json::{Value, json}; use super::attribs::{blocks_with_attdefs, has_attdefs, reference_count, rename_tag, sync}; @@ -16,7 +16,7 @@ pub(super) fn battman_spec() -> CommandSpec { CommandSpec::new("battman", "Block Attribute Manager...", run) .menu(&["Modify", "Object", "Attribute", "Block Attribute Manager..."]) .params( - "{name, action?: \"list\" (default) | \"edit\" | \"remove\" | \"up\" | \"down\" | \"order\" | \"sync\", tag? (the definition to edit, remove or move; any case), newTag?, prompt?, default?, invisible?, constant?, height?, layer?, order?: [every tag, in the new order], sync?: bool (default true: existing references follow, as with ATTSYNC)} → {block, attributes: [{tag, prompt, default, invisible, constant, height, layer}], references, synced?}", + "{name, action?: \"list\" (default) | \"edit\" | \"remove\" | \"up\" | \"down\" | \"order\" | \"sync\", tag? (the definition to edit, remove or move; any case), newTag?, prompt?, default?, invisible?, constant?, verify?, preset?, lockPosition?, multiline?: bool (width?: its width, 0 = no wrapping), height?, layer?, order?: [every tag, in the new order], sync?: bool (default true: existing references follow, as with ATTSYNC)} → {block, attributes: [{tag, prompt, default, invisible, constant, verify, preset, lockPosition, multiline, height, layer}], references, synced?}", ) .interactive(|s| Ok(Box::new(BattmanM::new(s)))) } @@ -29,10 +29,48 @@ struct Change { default: Option, invisible: Option, constant: Option, + verify: Option, + preset: Option, + lock_position: Option, + /// Multiple lines on (with the text's width) or off. + multiline: Option>, height: Option, layer: Option, } +/// Make the definition `a` multiline (Multiple lines on), `width` wide (0: no wrapping), its +/// default value its text; or single-line again (`width` None), its lines joined by spaces. +fn set_multiline(a: &mut Attrib, width: Option) { + match width { + Some(w) => { + let value = a.text.value.clone(); + let mtext = MText { + insert: a.text.insert, + height: a.text.height, + width: if w.is_finite() { w.abs() } else { 0.0 }, + attach: 1, + rotation: a.text.rotation, + style: a.text.style.clone(), + contents: mtext_literal(&value), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + a.multiline = Some(MultilineAttrib { mtext, read_as: value }); + } + None => { + if a.multiline.take().is_some() { + a.text.value = single_line(&a.text.value); + } + } + } +} + +/// `v`'s lines joined by spaces, as a single-line attribute holds them. +pub(super) fn single_line(v: &str) -> String { + v.lines().map(str::trim).filter(|l| !l.is_empty()).collect::>().join(" ") +} + /// The attribute definitions of `b` in order: handle, definition, layer. fn defs(b: &Block) -> Vec<(Handle, &Attrib, &str)> { b.entities @@ -63,7 +101,19 @@ fn listing(s: &Session, name: &str) -> Result { let atts: Vec = defs(&b) .into_iter() .map(|(_, a, layer)| { - json!({"tag": a.tag, "prompt": a.prompt, "default": a.text.value, "invisible": a.invisible, "constant": a.constant, "height": a.text.height, "layer": layer}) + json!({ + "tag": a.tag, + "prompt": a.prompt, + "default": a.text.value, + "invisible": a.invisible, + "constant": a.constant, + "verify": a.modes.verify, + "preset": a.modes.preset, + "lockPosition": a.modes.lock_position, + "multiline": a.multiline.is_some(), + "height": a.text.height, + "layer": layer + }) }) .collect(); Ok(json!({ "block": b.name, "attributes": atts, "references": reference_count(s.doc()?, &b.name) })) @@ -130,9 +180,31 @@ fn edit(s: &mut Session, name: &str, tag: &str, c: &Change) -> Result { if let Some(v) = c.constant { a.constant = v; } + if let Some(v) = c.verify { + a.modes.verify = v; + } + if let Some(v) = c.preset { + a.modes.preset = v; + } + if let Some(v) = c.lock_position { + a.modes.lock_position = v; + } if let Some(v) = c.height { a.text.height = v; } + match c.multiline { + // Turning it on keeps a multiline text as it is (its width changes when given). + Some(Some(w)) => match &mut a.multiline { + Some(ml) if w > 0.0 => ml.mtext.width = w, + Some(_) => {} + None => set_multiline(a, Some(w)), + }, + Some(None) => set_multiline(a, None), + None => {} + } + if let (Some(ml), Some(h)) = (&mut a.multiline, c.height) { + ml.mtext.height = h; + } result = a.tag.clone(); } }); @@ -228,6 +300,20 @@ fn run(s: &mut Session, p: &Value) -> Result { default: opt_str("default"), invisible: opt_bool("invisible"), constant: opt_bool("constant"), + verify: opt_bool("verify"), + preset: opt_bool("preset"), + lock_position: opt_bool("lockPosition"), + multiline: match opt_bool("multiline") { + Some(true) => { + let w = p.get("width").and_then(Value::as_f64).unwrap_or(0.0); + if !(w.is_finite() && w >= 0.0) { + return Err(bad("battman", "`width` must be zero or positive")); + } + Some(Some(w)) + } + Some(false) => Some(None), + None => None, + }, height, layer: opt_str("layer"), }; @@ -279,6 +365,10 @@ enum Prop { Default, Invisible, Constant, + Verify, + Preset, + Lock, + Multiline, Height, Layer, } @@ -302,7 +392,8 @@ struct BattmanM { } const OPTIONS: &[&str] = &["Edit", "Remove", "moveUp", "moveDown", "Sync", "List", "eXit"]; -const PROPS: &[&str] = &["Tag", "Prompt", "Default", "Invisible", "Constant", "Height", "Layer", "eXit"]; +const PROPS: &[&str] = + &["Tag", "Prompt", "Default", "Invisible", "Constant", "Verify", "pReset", "locK position", "Multiple lines", "Height", "Layer", "eXit"]; impl BattmanM { fn new(s: &Session) -> Self { @@ -332,6 +423,18 @@ impl BattmanM { if a.constant { modes.push("constant"); } + if a.modes.verify { + modes.push("verify"); + } + if a.modes.preset { + modes.push("preset"); + } + if a.modes.lock_position { + modes.push("lock position"); + } + if a.multiline.is_some() { + modes.push("multiple lines"); + } let modes = if modes.is_empty() { String::new() } else { format!(" ({})", modes.join(", ")) }; format!(" {} prompt \"{}\" default \"{}\"{modes}", a.tag, a.prompt, a.text.value) }) @@ -409,6 +512,14 @@ impl Interactive for BattmanM { Prop::Default => Prompt::new("Enter new default value", Accept::TEXT).default(text(|a| a.text.value.clone())), Prop::Invisible => Prompt::new("Invisible?", KW).kw(&["Yes", "No"]).default(yes_no(a.as_ref().is_some_and(|a| a.invisible))), Prop::Constant => Prompt::new("Constant?", KW).kw(&["Yes", "No"]).default(yes_no(a.as_ref().is_some_and(|a| a.constant))), + Prop::Verify => Prompt::new("Verify?", KW).kw(&["Yes", "No"]).default(yes_no(a.as_ref().is_some_and(|a| a.modes.verify))), + Prop::Preset => Prompt::new("Preset?", KW).kw(&["Yes", "No"]).default(yes_no(a.as_ref().is_some_and(|a| a.modes.preset))), + Prop::Lock => { + Prompt::new("Lock position?", KW).kw(&["Yes", "No"]).default(yes_no(a.as_ref().is_some_and(|a| a.modes.lock_position))) + } + Prop::Multiline => { + Prompt::new("Multiple lines?", KW).kw(&["Yes", "No"]).default(yes_no(a.as_ref().is_some_and(|a| a.multiline.is_some()))) + } Prop::Height => Prompt::new("Specify text height", Accept::NUMBER).default(num(a.as_ref().map_or(0.0, |a| a.text.height))), Prop::Layer => Prompt::new("Enter layer name", Accept::TEXT).default(self.current_layer(s)), } @@ -484,6 +595,10 @@ impl Interactive for BattmanM { "Default" => Stage::Value(Prop::Default), "Invisible" => Stage::Value(Prop::Invisible), "Constant" => Stage::Value(Prop::Constant), + "Verify" => Stage::Value(Prop::Verify), + "pReset" => Stage::Value(Prop::Preset), + "locK position" => Stage::Value(Prop::Lock), + "Multiple lines" => Stage::Value(Prop::Multiline), "Height" => Stage::Value(Prop::Height), "Layer" => Stage::Value(Prop::Layer), _ => Stage::Option, @@ -511,6 +626,15 @@ impl Interactive for BattmanM { Prop::Constant => { Change { constant: Some(yes(&i).ok_or_else(|| EngineError::Other("Enter Yes or No.".into()))?), ..Change::default() } } + Prop::Verify | Prop::Preset | Prop::Lock | Prop::Multiline => { + let v = yes(&i).ok_or_else(|| EngineError::Other("Enter Yes or No.".into()))?; + match p { + Prop::Verify => Change { verify: Some(v), ..Change::default() }, + Prop::Preset => Change { preset: Some(v), ..Change::default() }, + Prop::Lock => Change { lock_position: Some(v), ..Change::default() }, + _ => Change { multiline: Some(v.then_some(0.0)), ..Change::default() }, + } + } Prop::Height => { let h = crate::units::parse_distance(&text).ok_or_else(|| EngineError::Other("Requires a positive number.".into()))?; Change { height: Some(h), ..Change::default() } diff --git a/crates/engine/tests/it/attribute_tools.rs b/crates/engine/tests/it/attribute_tools.rs index 5d3671c8ed..af0ca0ba7a 100644 --- a/crates/engine/tests/it/attribute_tools.rs +++ b/crates/engine/tests/it/attribute_tools.rs @@ -47,7 +47,7 @@ fn battman_lists_definitions_and_references() { assert_eq!(tags(&r), ["A", "B", "C"]); assert_eq!( r["attributes"][0], - json!({"tag": "A", "prompt": "A?", "default": "a", "invisible": false, "constant": false, "height": 1.0, "layer": "0"}) + json!({"tag": "A", "prompt": "A?", "default": "a", "invisible": false, "constant": false, "verify": false, "preset": false, "lockPosition": false, "multiline": false, "height": 1.0, "layer": "0"}) ); // Listing changes nothing, so it leaves no undo step. let undo = s.state().unwrap().undo.len(); @@ -65,7 +65,7 @@ fn battman_edit_renames_a_tag_and_references_keep_their_values() { assert_eq!(r["synced"], 2); assert_eq!( r["attributes"][0], - json!({"tag": "PART", "prompt": "Part number", "default": "P-0", "invisible": true, "constant": false, "height": 1.0, "layer": "0"}) + json!({"tag": "PART", "prompt": "Part number", "default": "P-0", "invisible": true, "constant": false, "verify": false, "preset": false, "lockPosition": false, "multiline": false, "height": 1.0, "layer": "0"}) ); let a = attribs(&s, r1); assert_eq!(a[0], ("PART".into(), "one".into(), true)); @@ -158,7 +158,7 @@ fn battman_at_the_command_line_edits_removes_and_moves() { let r = battman(&mut s, json!({"name": "B"})); assert_eq!( r["attributes"][0], - json!({"tag": "ITEM", "prompt": "Item name", "default": "a", "invisible": true, "constant": false, "height": 2.0, "layer": "0"}) + json!({"tag": "ITEM", "prompt": "Item name", "default": "a", "invisible": true, "constant": false, "verify": false, "preset": false, "lockPosition": false, "multiline": false, "height": 2.0, "layer": "0"}) ); assert_eq!(attribs(&s, r1)[0], ("ITEM".into(), "one".into(), true)); for l in ["d", "item", "r", "c"] { diff --git a/crates/engine/tests/it/battman_modes.rs b/crates/engine/tests/it/battman_modes.rs new file mode 100644 index 0000000000..beee33c205 --- /dev/null +++ b/crates/engine/tests/it/battman_modes.rs @@ -0,0 +1,175 @@ +//! BATTMAN switches an attribute definition's Verify, Preset and Lock position modes and makes it +//! multiline or single-line again (gap F17); existing references follow (ATTSYNC), and what it +//! makes survives DXF and DWG. + +use cadcraft_engine::doc::{Attrib, Drawing, EntityKind, Handle}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn h(v: &Value) -> Handle { + Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap() +} + +/// Block T with the definitions A, B and C, and one reference with C = "x". +fn session() -> (Session, Handle) { + let mut s = Session::new(); + let l = s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + let mut hs = vec![l["handles"][0].clone()]; + for (tag, y) in [("A", 2), ("B", 4), ("C", 6)] { + hs.push(s.execute("attdef", &json!({ "tag": tag, "prompt": tag, "default": "d", "at": [0, y] })).unwrap()["handle"].clone()); + } + s.execute("block", &json!({ "name": "T", "base": [0, 0], "handles": hs, "keep": "delete" })).unwrap(); + let ins = h(&s.execute("insert", &json!({ "name": "T", "at": [100, 0], "attribs": { "C": "x" } })).unwrap()); + (s, ins) +} + +fn row(r: &Value, tag: &str) -> Value { + r["attributes"].as_array().unwrap().iter().find(|a| a["tag"] == tag).unwrap().clone() +} + +fn definition(d: &Drawing, tag: &str) -> Attrib { + d.block("T") + .unwrap() + .entities + .iter() + .find_map(|e| match &e.kind { + EntityKind::AttDef(a) if a.tag == tag => Some(a.clone()), + _ => None, + }) + .unwrap() +} + +fn reference_attrib(d: &Drawing, ins: Handle, tag: &str) -> Attrib { + let EntityKind::Insert(i) = &d.entity(ins).unwrap().kind else { panic!("not a reference") }; + i.attribs.iter().find(|a| a.tag == tag).unwrap().clone() +} + +#[test] +fn modes_are_listed_and_switched() { + let (mut s, ins) = session(); + let r = s.execute("battman", &json!({ "name": "T" })).unwrap(); + let a = row(&r, "A"); + assert_eq!( + (a["verify"].as_bool(), a["preset"].as_bool(), a["lockPosition"].as_bool(), a["multiline"].as_bool()), + (Some(false), Some(false), Some(false), Some(false)) + ); + let r = + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "a", "verify": true, "preset": true, "lockPosition": true })).unwrap(); + let a = row(&r, "A"); + assert_eq!((a["verify"].as_bool(), a["preset"].as_bool(), a["lockPosition"].as_bool()), (Some(true), Some(true), Some(true))); + let d = s.doc().unwrap(); + assert!(definition(d, "A").modes.verify && definition(d, "A").modes.preset); + // The reference takes Lock position only, as AutoCAD keeps it. + let ra = reference_attrib(d, ins, "A"); + assert!(ra.modes.lock_position && !ra.modes.verify && !ra.modes.preset); + // Off again. + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "A", "lockPosition": false, "preset": false })).unwrap(); + let ra = reference_attrib(s.doc().unwrap(), ins, "A"); + assert!(!ra.modes.lock_position); + assert!(definition(s.doc().unwrap(), "A").modes.verify); +} + +#[test] +fn multiple_lines_on_and_off() { + let (mut s, ins) = session(); + let r = + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": 12, "default": "one\ntwo" })).unwrap(); + assert_eq!(row(&r, "C")["multiline"], true); + let d = s.doc().unwrap(); + let c = definition(d, "C"); + let ml = c.multiline.as_ref().expect("a multiline definition"); + assert_eq!(ml.mtext.width, 12.0); + assert_eq!(c.multiline_text().unwrap().contents, "one\\Ptwo"); + // The reference follows and keeps its value. + let rc = reference_attrib(d, ins, "C"); + assert!(rc.multiline.is_some()); + assert_eq!(rc.text.value, "x"); + assert_eq!(rc.multiline_text().unwrap().contents, "x"); + // A new width; the height reaches the multiline text too. + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": 30, "height": 0.5 })).unwrap(); + let c = definition(s.doc().unwrap(), "C"); + let ml = c.multiline.as_ref().unwrap(); + assert_eq!((ml.mtext.width, ml.mtext.height, c.text.height), (30.0, 0.5, 0.5)); + + // Single-line again: the lines joined by spaces, in the definition and the references. + s.execute("attedit", &json!({ "handle": ins.hex(), "values": { "C": "first\nsecond" } })).unwrap(); + let r = s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": false })).unwrap(); + assert_eq!(row(&r, "C")["multiline"], false); + let d = s.doc().unwrap(); + let c = definition(d, "C"); + assert!(c.multiline.is_none()); + assert_eq!(c.text.value, "one two"); + let rc = reference_attrib(d, ins, "C"); + assert!(rc.multiline.is_none()); + assert_eq!(rc.text.value, "first second"); +} + +#[test] +fn what_battman_makes_survives_dxf_and_dwg() { + let (mut s, ins) = session(); + s.execute( + "battman", + &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": 12, "default": "one\ntwo", "verify": true, "lockPosition": true }), + ) + .unwrap(); + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "B", "preset": true })).unwrap(); + let d = s.doc().unwrap(); + // As the app saves them (AutoCAD 2018 here): multiline attributes need 2007 or later. + let dxf = String::from_utf8(cadcraft_io::write(d, "x.dxf").unwrap()).unwrap(); + let dwg = cadcraft_io::write(d, "x.dwg").unwrap(); + for (name, r) in [("DXF", cadcraft_io::read_dxf(dxf.as_bytes()).unwrap()), ("DWG", cadcraft_io::read(&dwg, "x.dwg").unwrap())] { + let c = definition(&r, "C"); + assert!(c.modes.verify && c.modes.lock_position, "{name}: {:?}", c.modes); + let ml = c.multiline.as_ref().unwrap_or_else(|| panic!("{name}: C multiline")); + assert!((ml.mtext.width - 12.0).abs() < 1e-9, "{name}: width {}", ml.mtext.width); + assert_eq!(c.text.value.replace("\r\n", "\n"), "one\ntwo", "{name}"); + assert!(definition(&r, "B").modes.preset, "{name}: B preset"); + let EntityKind::Insert(i) = &r.model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().kind else { panic!() }; + let rc = i.attribs.iter().find(|a| a.tag == "C").unwrap(); + assert!(rc.multiline.is_some() && rc.modes.lock_position, "{name}: reference C"); + assert_eq!(rc.text.value, "x", "{name}"); + } + let _ = ins; +} + +#[test] +fn typed_battman_asks_for_the_new_modes() { + let (mut s, _) = session(); + s.start("battman").unwrap(); + s.cmdline("T").unwrap(); + s.cmdline("e").unwrap(); + s.cmdline("A").unwrap(); + for (kw, answer) in [("Verify", "y"), ("pReset", "y"), ("locK position", "y"), ("Multiple lines", "y")] { + s.input(Input::Keyword(kw.into())).unwrap(); + s.cmdline(answer).unwrap(); + } + s.input(Input::Keyword("eXit".into())).unwrap(); + s.input(Input::Keyword("eXit".into())).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let a = row(&s.execute("battman", &json!({ "name": "T" })).unwrap(), "A"); + assert_eq!( + (a["verify"].as_bool(), a["preset"].as_bool(), a["lockPosition"].as_bool(), a["multiline"].as_bool()), + (Some(true), Some(true), Some(true), Some(true)) + ); +} + +#[test] +fn hostile_params_never_panic() { + let (mut s, _) = session(); + let before = definition(s.doc().unwrap(), "C"); + for bad in [json!(-3), json!(-1e308)] { + assert!(s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": bad })).is_err(), "{bad}"); + } + assert_eq!(definition(s.doc().unwrap(), "C"), before, "a refused edit changes nothing"); + // Values of the wrong type are ignored, as for the other modes. + for odd in [json!("yes"), json!(1), json!(null), json!([true])] { + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": odd, "verify": odd, "width": "wide" })).unwrap(); + } + assert_eq!(definition(s.doc().unwrap(), "C"), before); + // A huge width is kept as given; the drawing still saves. + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": 1e300 })).unwrap(); + let _ = cadcraft_io::write_dxf(s.doc().unwrap()); + // Switching a definition that is already single-line off again changes nothing. + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "A", "multiline": false })).unwrap(); + assert!(definition(s.doc().unwrap(), "A").multiline.is_none()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6b..fc33ddbcfe 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -10,6 +10,7 @@ mod attedit_prompts; mod attrib_modes; mod attrib_props; mod attribute_tools; +mod battman_modes; mod block_description; mod block_keep; mod block_redefine; diff --git a/crates/ui-egui/src/managers/battman.rs b/crates/ui-egui/src/managers/battman.rs index 82f8e1d978..3b4d4a0dcb 100644 --- a/crates/ui-egui/src/managers/battman.rs +++ b/crates/ui-egui/src/managers/battman.rs @@ -16,6 +16,10 @@ struct Row { default: String, invisible: bool, constant: bool, + verify: bool, + preset: bool, + lock: bool, + multiline: bool, height: f64, layer: String, } @@ -77,6 +81,10 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< default: a.text.value.clone(), invisible: a.invisible, constant: a.constant, + verify: a.modes.verify, + preset: a.modes.preset, + lock: a.modes.lock_position, + multiline: a.multiline.is_some(), height: a.text.height, layer: e.common.layer.clone(), }), @@ -102,8 +110,8 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< return; } ui.horizontal(|ui| { - ui.label("Block:"); - craft_ui::ComboBox::from_id_salt("battman_blocks").selected_text(block.as_str()).width(180.0).show_ui(ui, |ui| { + let label = ui.label("Block:"); + let combo = craft_ui::ComboBox::from_id_salt("battman_blocks").selected_text(block.as_str()).width(180.0).show_ui(ui, |ui| { for b in &blocks { if ui.selectable_label(*b == block, b).clicked() { block = b.clone(); @@ -111,6 +119,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< } } }); + combo.response.labelled_by(label.id); ui.label(RichText::new(format!("Found in drawing: {refs}")).color(t.text_dim)); }); ui.separator(); @@ -127,7 +136,11 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< } ui.label(&r.prompt); ui.label(&r.default); - let modes = [(r.invisible, "I"), (r.constant, "C")].iter().filter(|(on, _)| *on).map(|(_, m)| *m).collect::(); + let modes = [(r.invisible, "I"), (r.constant, "C"), (r.verify, "V"), (r.preset, "P"), (r.lock, "L"), (r.multiline, "M")] + .iter() + .filter(|(on, _)| *on) + .map(|(_, m)| *m) + .collect::(); ui.label(RichText::new(modes).color(t.text_dim)); ui.end_row(); } @@ -172,14 +185,27 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< } ui.end_row(); ui.label("Mode"); - ui.horizontal(|ui| { - let (mut inv, mut con) = (r.invisible, r.constant); - if ui.checkbox(&mut inv, "Invisible").changed() { - action = act(edit("invisible", json!(inv)), apply); - } - if ui.checkbox(&mut con, "Constant").changed() { - action = act(edit("constant", json!(con)), apply); - } + ui.vertical(|ui| { + ui.horizontal(|ui| { + for (key, on, label) in + [("invisible", r.invisible, "Invisible"), ("constant", r.constant, "Constant"), ("verify", r.verify, "Verify")] + { + let mut v = on; + if ui.checkbox(&mut v, label).changed() { + action = act(edit(key, json!(v)), apply); + } + } + }); + ui.horizontal(|ui| { + for (key, on, label) in + [("preset", r.preset, "Preset"), ("lockPosition", r.lock, "Lock position"), ("multiline", r.multiline, "Multiple lines")] + { + let mut v = on; + if ui.checkbox(&mut v, label).changed() { + action = act(edit(key, json!(v)), apply); + } + } + }); }); ui.end_row(); let label = ui.label("Height"); @@ -188,14 +214,15 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< action = act(edit("height", json!(h)), apply); } ui.end_row(); - ui.label("Layer"); - craft_ui::ComboBox::from_id_salt("battman_layer").selected_text(r.layer.as_str()).show_ui(ui, |ui| { + let label = ui.label("Layer"); + let combo = craft_ui::ComboBox::from_id_salt("battman_layer").selected_text(r.layer.as_str()).show_ui(ui, |ui| { for l in &layers { if ui.selectable_label(*l == r.layer, l).clicked() && *l != r.layer { action = act(edit("layer", json!(l)), apply); } } }); + combo.response.labelled_by(label.id); ui.end_row(); }); } diff --git a/crates/ui-egui/tests/it/battman_modes_dialog.rs b/crates/ui-egui/tests/it/battman_modes_dialog.rs new file mode 100644 index 0000000000..ef711ceeb8 --- /dev/null +++ b/crates/ui-egui/tests/it/battman_modes_dialog.rs @@ -0,0 +1,62 @@ +//! Block Attribute Manager: the Verify, Preset, Lock position and Multiple lines check boxes switch +//! the selected definition's modes through the `battman` command, and its reference follows. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use cadcraft_ui_egui::{CadApp, Services, dialogs, menus}; +use egui::accesskit::{Role, Toggled}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +/// Block T with the definition ROOM, one reference, and BATTMAN opened from its menu item. +fn harness() -> Harness<'static, CadApp> { + let mut app = CadApp::new(Session::new(), Services::default()); + let a = app.run("attdef", json!({ "tag": "ROOM", "prompt": "Room", "default": "101", "at": [0, 2] })).unwrap(); + app.run("block", json!({ "name": "T", "base": [0, 0], "handles": [a["handle"]], "keep": "delete" })).unwrap(); + app.run("insert", json!({ "name": "T", "at": [10, 0], "attribs": { "ROOM": "7" } })).unwrap(); + menus::activate(&mut app, "battman"); + assert_eq!(app.ui.dialog.as_deref(), Some("battman")); + let mut h = Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state(|ui, app: &mut CadApp| dialogs::show(app, ui.ctx()), app); + h.run_steps(3); + h +} + +fn listed(app: &mut CadApp) -> serde_json::Value { + app.run("battman", json!({ "name": "T" })).unwrap()["attributes"][0].clone() +} + +fn checked(h: &Harness<'static, CadApp>, label: &str) -> bool { + h.get_by_role_and_label(Role::CheckBox, label).accesskit_node().toggled() == Some(Toggled::True) +} + +#[test] +fn check_boxes_switch_the_modes_and_multiple_lines() { + let mut h = harness(); + for label in ["Verify", "Preset", "Lock position", "Multiple lines"] { + assert!(!checked(&h, label), "{label} starts off"); + h.get_by_role_and_label(Role::CheckBox, label).click(); + h.run_steps(3); + assert!(checked(&h, label), "{label} on"); + } + let row = listed(h.state_mut()); + assert_eq!( + (row["verify"].as_bool(), row["preset"].as_bool(), row["lockPosition"].as_bool(), row["multiline"].as_bool()), + (Some(true), Some(true), Some(true), Some(true)) + ); + // "Apply changes to existing references" is on: the reference is multiline and locked now. + let app = h.state(); + let d = app.session.doc().unwrap(); + let EntityKind::Insert(i) = &d.model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().kind else { panic!() }; + assert!(i.attribs[0].multiline.is_some() && i.attribs[0].modes.lock_position); + assert_eq!(i.attribs[0].text.value, "7"); + + // Off again, as one undo step each. + h.get_by_role_and_label(Role::CheckBox, "Multiple lines").click(); + h.run_steps(3); + assert!(!checked(&h, "Multiple lines")); + assert_eq!(listed(h.state_mut())["multiline"], false); + h.state_mut().run("u", json!({})).unwrap(); + assert_eq!(listed(h.state_mut())["multiline"], true, "undo brings Multiple lines back"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c32012e1ab..c6d3d5d77b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,4 +1,5 @@ mod animation_effects; +mod battman_modes_dialog; mod block_description_palette; mod chrome_geometry; mod context_menu; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2bfea4a514..a91ea756c8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LAYOUT SAveas writes a layout as a DWT template) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (attribute definitions made multiline by BATTMAN round-trip) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -75,7 +75,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137) | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137); definitions BATTMAN makes multiline or gives modes round-trip through DXF and DWG (`battman_modes`) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Attribute definitions BATTMAN makes multiline or gives the Verify, Preset and Lock position modes, and their references, read back the same from DXF and DWG | | 2026-10-25 | minor | LAYOUT SAveas (`layout.saveas`) writes a layout as a drawing template: its page setup and paper space objects, no model space objects or other layouts, and only the named objects they use | | 2026-10-22 | minor | DXF/DWG save: angular, diametric and radial dimensions get standard DIMASSOC objects (one centre reference to the circle for radial/diametric, the definition points for angular), so AutoCAD follows their geometry; the standard objects of those kinds are read back too, without CADCraft's xdata (#1651) | | 2026-10-19 | minor | DXF/DWG save: angular dimension block text honors DIMDSEP, including per-dimension overrides (#1646) | diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630f..55060bfad5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (BATTMAN switches attribute modes and multiple lines: F17 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -39,7 +39,7 @@ do them first. | F13 | Hatch: 23 patterns (AutoCAD ~85; ours must stay original); the Hatch and Gradient and Hatch Edit dialogs have no Preview or Inherit Properties (HPDLGMODE 0 keeps HATCH on the command line); no MPolygon; HATCHEDIT and -HATCHEDIT add boundaries from picked points or closed objects and remove chosen loops, but a hatch copied with its boundary isn't linked to the copy; HPGAPTOL closes gaps between curve ends only | `doc/src/library.rs`, `cmd/hatch.rs`, `cmd/hatch/edit.rs` | Medium | 6–10 | | F15 | Viewports: a clipped viewport and its clip boundary move and scale separately. Polygonal, object and clipped viewports, VPCLIP, MVIEW ON/OFF/Lock/2/3/4 and the status-bar scale list landed (#453), MVIEW Restore in #633 | `cmd/layout/viewports.rs` | Low | 2–4 | | F16 | Groups: no group bounding box or single grip when a group is selected (GROUPDISPLAYMODE), copying a whole group does not make a new group, no Object Grouping dialog (GROUP, GROUPEDIT, UNGROUP, -GROUP, PICKSTYLE group selection and the DXF/DWG round trip landed, #417); PICKSTYLE's associative-hatch bit is stored but unused | `cmd/groups.rs` | Low | 2–4 | -| F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): no verify, preset or lock-position modes, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | +| F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433; BATTMAN switches the Verify, Preset and Lock position modes and Multiple lines, its references following): ATTDEF can't set those modes or make a multiline definition, INSERT neither asks Verify attributes twice nor skips Preset ones, and locked attributes still have grips; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | | F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 | | F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export | `ui-egui/src/options/` | Low | 2–4 | | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | BATTMAN (dialog, command line and JSON) switches an attribute definition's Verify, Preset and Lock position modes and makes it multiline (with a width) or single-line again; existing references follow, a multi-line value becoming one line; kept in DXF and DWG: F17 narrowed | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | From 276a872b85563a6e19e50f14003d356d897ccbca Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Thu, 29 Oct 2026 11:24:48 +0100 Subject: [PATCH 2/3] BATTMAN: an omitted width keeps a multiline definition's, 0 unwraps it; multiline Default field With Multiple lines on, `battman edit` now tells an omitted (or null) width from an explicit one: omitted keeps a multiline definition's width, an explicit 0 removes its wrapping (it used to be ignored), and a width that is not a number is refused instead of becoming 0. In the Block Attribute Manager the Default field of a multiline definition is a multiline editor, so its value can hold several lines. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/blocks/battman.rs | 40 +++++++++++-------- crates/engine/tests/it/battman_modes.rs | 10 ++++- crates/ui-egui/src/managers/battman.rs | 17 ++++---- .../ui-egui/tests/it/battman_modes_dialog.rs | 23 +++++++++++ 4 files changed, 66 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/blocks/battman.rs b/crates/engine/src/cmd/blocks/battman.rs index 964c94c4c7..a1a0795d30 100644 --- a/crates/engine/src/cmd/blocks/battman.rs +++ b/crates/engine/src/cmd/blocks/battman.rs @@ -16,7 +16,7 @@ pub(super) fn battman_spec() -> CommandSpec { CommandSpec::new("battman", "Block Attribute Manager...", run) .menu(&["Modify", "Object", "Attribute", "Block Attribute Manager..."]) .params( - "{name, action?: \"list\" (default) | \"edit\" | \"remove\" | \"up\" | \"down\" | \"order\" | \"sync\", tag? (the definition to edit, remove or move; any case), newTag?, prompt?, default?, invisible?, constant?, verify?, preset?, lockPosition?, multiline?: bool (width?: its width, 0 = no wrapping), height?, layer?, order?: [every tag, in the new order], sync?: bool (default true: existing references follow, as with ATTSYNC)} → {block, attributes: [{tag, prompt, default, invisible, constant, verify, preset, lockPosition, multiline, height, layer}], references, synced?}", + "{name, action?: \"list\" (default) | \"edit\" | \"remove\" | \"up\" | \"down\" | \"order\" | \"sync\", tag? (the definition to edit, remove or move; any case), newTag?, prompt?, default?, invisible?, constant?, verify?, preset?, lockPosition?, multiline?: bool (width?: its width, 0 = no wrapping; omitted, a multiline definition keeps its width), height?, layer?, order?: [every tag, in the new order], sync?: bool (default true: existing references follow, as with ATTSYNC)} → {block, attributes: [{tag, prompt, default, invisible, constant, verify, preset, lockPosition, multiline, height, layer}], references, synced?}", ) .interactive(|s| Ok(Box::new(BattmanM::new(s)))) } @@ -32,8 +32,11 @@ struct Change { verify: Option, preset: Option, lock_position: Option, - /// Multiple lines on (with the text's width) or off. - multiline: Option>, + /// Multiple lines on or off. + multiline: Option, + /// With Multiple lines on: the text's width (0: no wrapping). `None` keeps a multiline + /// definition's width and gives a new one 0. + width: Option, height: Option, layer: Option, } @@ -193,13 +196,17 @@ fn edit(s: &mut Session, name: &str, tag: &str, c: &Change) -> Result { a.text.height = v; } match c.multiline { - // Turning it on keeps a multiline text as it is (its width changes when given). - Some(Some(w)) => match &mut a.multiline { - Some(ml) if w > 0.0 => ml.mtext.width = w, - Some(_) => {} - None => set_multiline(a, Some(w)), + // Turning it on keeps a multiline text as it is (its width changes when given, + // 0 included: no wrapping). + Some(true) => match &mut a.multiline { + Some(ml) => { + if let Some(w) = c.width { + ml.mtext.width = w; + } + } + None => set_multiline(a, Some(c.width.unwrap_or(0.0))), }, - Some(None) => set_multiline(a, None), + Some(false) => set_multiline(a, None), None => {} } if let (Some(ml), Some(h)) = (&mut a.multiline, c.height) { @@ -303,16 +310,17 @@ fn run(s: &mut Session, p: &Value) -> Result { verify: opt_bool("verify"), preset: opt_bool("preset"), lock_position: opt_bool("lockPosition"), - multiline: match opt_bool("multiline") { - Some(true) => { - let w = p.get("width").and_then(Value::as_f64).unwrap_or(0.0); + multiline: opt_bool("multiline"), + // Read with Multiple lines on only; omitted, a multiline definition keeps its width. + width: match (opt_bool("multiline"), p.get("width")) { + (Some(true), Some(v)) if !v.is_null() => { + let w = v.as_f64().ok_or_else(|| bad("battman", "`width` must be a number"))?; if !(w.is_finite() && w >= 0.0) { return Err(bad("battman", "`width` must be zero or positive")); } - Some(Some(w)) + Some(w) } - Some(false) => Some(None), - None => None, + _ => None, }, height, layer: opt_str("layer"), @@ -632,7 +640,7 @@ impl Interactive for BattmanM { Prop::Verify => Change { verify: Some(v), ..Change::default() }, Prop::Preset => Change { preset: Some(v), ..Change::default() }, Prop::Lock => Change { lock_position: Some(v), ..Change::default() }, - _ => Change { multiline: Some(v.then_some(0.0)), ..Change::default() }, + _ => Change { multiline: Some(v), ..Change::default() }, } } Prop::Height => { diff --git a/crates/engine/tests/it/battman_modes.rs b/crates/engine/tests/it/battman_modes.rs index beee33c205..d3622f2d79 100644 --- a/crates/engine/tests/it/battman_modes.rs +++ b/crates/engine/tests/it/battman_modes.rs @@ -90,6 +90,13 @@ fn multiple_lines_on_and_off() { let c = definition(s.doc().unwrap(), "C"); let ml = c.multiline.as_ref().unwrap(); assert_eq!((ml.mtext.width, ml.mtext.height, c.text.height), (30.0, 0.5, 0.5)); + // No width keeps it; an explicit 0 removes the wrapping. + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "prompt": "Room" })).unwrap(); + assert_eq!(definition(s.doc().unwrap(), "C").multiline.unwrap().mtext.width, 30.0, "omitted width kept"); + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": null })).unwrap(); + assert_eq!(definition(s.doc().unwrap(), "C").multiline.unwrap().mtext.width, 30.0, "null width kept"); + s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": 0 })).unwrap(); + assert_eq!(definition(s.doc().unwrap(), "C").multiline.unwrap().mtext.width, 0.0, "explicit 0: no wrapping"); // Single-line again: the lines joined by spaces, in the definition and the references. s.execute("attedit", &json!({ "handle": ins.hex(), "values": { "C": "first\nsecond" } })).unwrap(); @@ -157,7 +164,8 @@ fn typed_battman_asks_for_the_new_modes() { fn hostile_params_never_panic() { let (mut s, _) = session(); let before = definition(s.doc().unwrap(), "C"); - for bad in [json!(-3), json!(-1e308)] { + // A negative width, or one that is not a number, is refused (it used to become 0). + for bad in [json!(-3), json!(-1e308), json!("12"), json!("wide"), json!(true), json!([12])] { assert!(s.execute("battman", &json!({ "name": "T", "action": "edit", "tag": "C", "multiline": true, "width": bad })).is_err(), "{bad}"); } assert_eq!(definition(s.doc().unwrap(), "C"), before, "a refused edit changes nothing"); diff --git a/crates/ui-egui/src/managers/battman.rs b/crates/ui-egui/src/managers/battman.rs index 3b4d4a0dcb..7b7b4ae586 100644 --- a/crates/ui-egui/src/managers/battman.rs +++ b/crates/ui-egui/src/managers/battman.rs @@ -32,12 +32,14 @@ fn set_temp(ctx: &egui::Context, id: &str, v: ctx.data_mut(|d| d.insert_temp(egui::Id::unique(id), v)); } -/// A text field committing on Enter / focus loss when changed (an empty value too). +/// A text field committing on Enter / focus loss when changed (an empty value too); a +/// `multiline` one takes Enter as a line break and commits on focus loss. /// /// `label` is the visible row label's widget id, so the field has an accessible name. -fn text_field(ui: &mut egui::Ui, id: egui::Id, value: &str, label: egui::Id) -> Option { +fn text_field(ui: &mut egui::Ui, id: egui::Id, value: &str, label: egui::Id, multiline: bool) -> Option { let mut buf = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_else(|| value.to_string()); - let resp = ui.add(egui::TextEdit::singleline(&mut buf).id(id.with("te")).desired_width(180.0)).labelled_by(label); + let edit = if multiline { egui::TextEdit::multiline(&mut buf).desired_rows(3) } else { egui::TextEdit::singleline(&mut buf) }; + let resp = ui.add(edit.id(id.with("te")).desired_width(180.0)).labelled_by(label); if resp.has_focus() { ui.data_mut(|d| d.insert_temp(id, buf.clone())); } else { @@ -169,18 +171,19 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< let edit = |key: &str, v: Value| json!({ "name": block, "action": "edit", "tag": r.tag, key: v }); egui::Grid::new("battman_edit").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| { let label = ui.label("Tag"); - if let Some(v) = text_field(ui, egui::Id::unique(("battman_tag", &block, &r.tag)), &r.tag, label.id) { + if let Some(v) = text_field(ui, egui::Id::unique(("battman_tag", &block, &r.tag)), &r.tag, label.id, false) { action = act(edit("newTag", json!(v)), apply); sel = Some(v.trim().to_ascii_uppercase()); } ui.end_row(); let label = ui.label("Prompt"); - if let Some(v) = text_field(ui, egui::Id::unique(("battman_prompt", &block, &r.tag)), &r.prompt, label.id) { + if let Some(v) = text_field(ui, egui::Id::unique(("battman_prompt", &block, &r.tag)), &r.prompt, label.id, false) { action = act(edit("prompt", json!(v)), apply); } ui.end_row(); let label = ui.label("Default"); - if let Some(v) = text_field(ui, egui::Id::unique(("battman_default", &block, &r.tag)), &r.default, label.id) { + // A multiline definition's default can hold several lines. + if let Some(v) = text_field(ui, egui::Id::unique(("battman_default", &block, &r.tag)), &r.default, label.id, r.multiline) { action = act(edit("default", json!(v)), apply); } ui.end_row(); @@ -209,7 +212,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< }); ui.end_row(); let label = ui.label("Height"); - let height = text_field(ui, egui::Id::unique(("battman_height", &block, &r.tag)), &fmt_num(r.height), label.id); + let height = text_field(ui, egui::Id::unique(("battman_height", &block, &r.tag)), &fmt_num(r.height), label.id, false); if let Some(h) = height.and_then(|v| v.trim().parse::().ok()).filter(|h| h.is_finite() && *h > 0.0) { action = act(edit("height", json!(h)), apply); } diff --git a/crates/ui-egui/tests/it/battman_modes_dialog.rs b/crates/ui-egui/tests/it/battman_modes_dialog.rs index ef711ceeb8..9530e9c3cf 100644 --- a/crates/ui-egui/tests/it/battman_modes_dialog.rs +++ b/crates/ui-egui/tests/it/battman_modes_dialog.rs @@ -60,3 +60,26 @@ fn check_boxes_switch_the_modes_and_multiple_lines() { h.state_mut().run("u", json!({})).unwrap(); assert_eq!(listed(h.state_mut())["multiline"], true, "undo brings Multiple lines back"); } + +#[test] +fn a_multiline_default_is_edited_on_several_lines() { + let mut h = harness(); + // Single-line: a one-line field. + h.get_by_role_and_label(Role::TextInput, "Default"); + assert!(h.query_by_role_and_label(Role::MultilineTextInput, "Default").is_none()); + h.get_by_role_and_label(Role::CheckBox, "Multiple lines").click(); + h.run_steps(3); + // Multiple lines on: Enter in the Default field is a line break, kept when the field loses focus. + h.get_by_role_and_label(Role::MultilineTextInput, "Default").focus(); + h.run_steps(2); + h.key_press(egui::Key::End); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(1); + h.get_by_role_and_label(Role::MultilineTextInput, "Default").type_text("second"); + h.run_steps(2); + assert_eq!(listed(h.state_mut())["default"], "101", "not committed while typing"); + h.get_by_role_and_label(Role::TextInput, "Height").focus(); + h.run_steps(3); + assert_eq!(listed(h.state_mut())["default"], "101\nsecond"); +} From ac53e22ae9bf9b5dd6267ce518ac29d64712f1ac Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Thu, 29 Oct 2026 12:47:26 +0100 Subject: [PATCH 3/3] BATTMAN: a field being edited is committed when another row is selected The Block Attribute Manager's Tag, Prompt, Default and Height fields commit when they lose focus, but selecting another attribute (or block) hides the field in the same frame, before it sees that, so the typed value was lost; a multiline Default can't be committed with Enter first. The value being typed is now kept with its field and committed when the field goes. A field that loses focus to a button click (Move Up/Down, Remove, Sync) no longer replaces the button's command either: the edit runs first, then the button. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/managers/battman.rs | 125 +++++++++++++++--- .../ui-egui/tests/it/battman_modes_dialog.rs | 81 ++++++++++++ 2 files changed, 186 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/managers/battman.rs b/crates/ui-egui/src/managers/battman.rs index 7b7b4ae586..f3712e2981 100644 --- a/crates/ui-egui/src/managers/battman.rs +++ b/crates/ui-egui/src/managers/battman.rs @@ -33,19 +33,98 @@ fn set_temp(ctx: &egui::Context, id: &str, v: } /// A text field committing on Enter / focus loss when changed (an empty value too); a -/// `multiline` one takes Enter as a line break and commits on focus loss. +/// `multiline` one takes Enter as a line break and commits on focus loss. Returns the committed +/// value, and the changed value still being typed. /// /// `label` is the visible row label's widget id, so the field has an accessible name. -fn text_field(ui: &mut egui::Ui, id: egui::Id, value: &str, label: egui::Id, multiline: bool) -> Option { +fn text_field(ui: &mut egui::Ui, id: egui::Id, value: &str, label: egui::Id, multiline: bool) -> (Option, Option) { let mut buf = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_else(|| value.to_string()); let edit = if multiline { egui::TextEdit::multiline(&mut buf).desired_rows(3) } else { egui::TextEdit::singleline(&mut buf) }; let resp = ui.add(edit.id(id.with("te")).desired_width(180.0)).labelled_by(label); if resp.has_focus() { ui.data_mut(|d| d.insert_temp(id, buf.clone())); - } else { - ui.data_mut(|d| d.remove::(id)); + return (None, (buf != value).then_some(buf)); + } + ui.data_mut(|d| d.remove::(id)); + ((resp.lost_focus() && buf != value).then_some(buf), None) +} + +/// A changed field value not committed yet: the `battman` parameters it commits with, and the +/// pass it was typed in. +#[derive(Clone)] +struct Pending { + field: egui::Id, + params: Value, + pass: u64, +} + +const PENDING: &str = "battman_pending"; + +/// The text fields of one pass. A field commits when it loses focus, but selecting another +/// attribute or block (or closing the dialog) can make it go before it sees that, so the value +/// being typed is kept and committed then instead of being lost. +struct Edits { + pass: u64, + /// The value being typed in the previous pass, and whether its field is still shown. + last: Option, + last_shown: bool, + typing: Option, + /// This pass's commits, in order. + commits: Vec, +} + +impl Edits { + fn new(ctx: &egui::Context) -> Self { + let pass = ctx.cumulative_pass_nr(); + // Only from the pass just before: a dialog closed by something else never commits later. + let last = temp::(ctx, PENDING).filter(|p| pass.saturating_sub(p.pass) <= 1); + Self { pass, last, last_shown: false, typing: None, commits: Vec::new() } + } + + /// Show a text field (see [`text_field`]); `params` gives the command's parameters for a + /// value, `None` if it isn't one. Returns the value committed this pass. + fn field( + &mut self, + ui: &mut egui::Ui, + id: egui::Id, + value: &str, + label: egui::Id, + multiline: bool, + params: impl Fn(&str) -> Option, + ) -> Option { + if self.last.as_ref().is_some_and(|p| p.field == id) { + self.last_shown = true; + } + let (commit, typing) = text_field(ui, id, value, label, multiline); + if let Some(p) = typing.and_then(|v| params(&v)) { + self.typing = Some(Pending { field: id, params: p, pass: self.pass }); + } + let v = commit?; + self.commits.push(params(&v)?); + Some(v) + } + + /// The parameters to run, in order: a value whose field went away without committing it, + /// this pass's commits, and the value being typed if the dialog is `closing`. + fn finish(self, ctx: &egui::Context, closing: bool) -> Vec { + let mut out = Vec::new(); + if let Some(p) = self.last.filter(|_| !self.last_shown) { + ctx.data_mut(|d| d.remove::(p.field)); + out.push(p.params); + } + out.extend(self.commits); + match self.typing { + Some(p) if !closing => set_temp(ctx, PENDING, p), + typing => { + ctx.data_mut(|d| d.remove::(egui::Id::unique(PENDING))); + if let Some(p) = typing { + ctx.data_mut(|d| d.remove::(p.field)); + out.push(p.params); + } + } + } + out } - (resp.lost_focus() && buf != value).then_some(buf) } fn fmt_num(v: f64) -> String { @@ -53,7 +132,7 @@ fn fmt_num(v: f64) -> String { if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } } -/// Show the dialog; returns the command to run. +/// Show the dialog; runs the text fields' commits and returns the command to run after them. pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option<(&'static str, Value)> { let t = Tokens::get(); let Ok(d) = app.session.doc() else { @@ -99,13 +178,15 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< let mut sel = temp::(ctx, "battman_sel").filter(|s| rows.iter().any(|r| r.tag == *s)).or_else(|| rows.first().map(|r| r.tag.clone())); let mut apply = temp::(ctx, "battman_apply").unwrap_or(true); let mut action: Option<(&'static str, Value)> = None; - let act = |p: Value, apply: bool| { + let with_sync = |p: Value, apply: bool| { let mut p = p; if let Some(o) = p.as_object_mut() { o.insert("sync".into(), json!(apply)); } - Some(("battman", p)) + p }; + let act = |p: Value, apply: bool| Some(("battman", with_sync(p, apply))); + let mut edits = Edits::new(ctx); egui::Window::new("Block Attribute Manager").open(open).default_width(460.0).resizable(false).show(ctx, |ui| { if blocks.is_empty() { ui.label("This drawing has no blocks with attributes."); @@ -170,22 +251,20 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< ui.label(RichText::new(format!("Edit attribute {}", r.tag)).strong()); let edit = |key: &str, v: Value| json!({ "name": block, "action": "edit", "tag": r.tag, key: v }); egui::Grid::new("battman_edit").num_columns(2).spacing(vec2(10.0, 6.0)).show(ui, |ui| { + let text = |key: &'static str| move |v: &str| Some(with_sync(edit(key, json!(v)), apply)); let label = ui.label("Tag"); - if let Some(v) = text_field(ui, egui::Id::unique(("battman_tag", &block, &r.tag)), &r.tag, label.id, false) { - action = act(edit("newTag", json!(v)), apply); + let id = egui::Id::unique(("battman_tag", &block, &r.tag)); + if let Some(v) = edits.field(ui, id, &r.tag, label.id, false, text("newTag")) { sel = Some(v.trim().to_ascii_uppercase()); } ui.end_row(); let label = ui.label("Prompt"); - if let Some(v) = text_field(ui, egui::Id::unique(("battman_prompt", &block, &r.tag)), &r.prompt, label.id, false) { - action = act(edit("prompt", json!(v)), apply); - } + edits.field(ui, egui::Id::unique(("battman_prompt", &block, &r.tag)), &r.prompt, label.id, false, text("prompt")); ui.end_row(); let label = ui.label("Default"); // A multiline definition's default can hold several lines. - if let Some(v) = text_field(ui, egui::Id::unique(("battman_default", &block, &r.tag)), &r.default, label.id, r.multiline) { - action = act(edit("default", json!(v)), apply); - } + let id = egui::Id::unique(("battman_default", &block, &r.tag)); + edits.field(ui, id, &r.default, label.id, r.multiline, text("default")); ui.end_row(); ui.label("Mode"); ui.vertical(|ui| { @@ -212,10 +291,11 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< }); ui.end_row(); let label = ui.label("Height"); - let height = text_field(ui, egui::Id::unique(("battman_height", &block, &r.tag)), &fmt_num(r.height), label.id, false); - if let Some(h) = height.and_then(|v| v.trim().parse::().ok()).filter(|h| h.is_finite() && *h > 0.0) { - action = act(edit("height", json!(h)), apply); - } + let height = |v: &str| { + let h = v.trim().parse::().ok().filter(|h| h.is_finite() && *h > 0.0)?; + Some(with_sync(edit("height", json!(h)), apply)) + }; + edits.field(ui, egui::Id::unique(("battman_height", &block, &r.tag)), &fmt_num(r.height), label.id, false, height); ui.end_row(); let label = ui.label("Layer"); let combo = craft_ui::ComboBox::from_id_salt("battman_layer").selected_text(r.layer.as_str()).show_ui(ui, |ui| { @@ -237,6 +317,11 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Option< set_temp(ctx, "battman_sel", s); } set_temp(ctx, "battman_apply", apply); + // The fields' commits first: an edit typed before a button was clicked happened before it. + for p in edits.finish(ctx, !*open) { + // Errors are echoed on the command line by `run`. + let _ = app.run("battman", p); + } action } diff --git a/crates/ui-egui/tests/it/battman_modes_dialog.rs b/crates/ui-egui/tests/it/battman_modes_dialog.rs index 9530e9c3cf..0c6c422b39 100644 --- a/crates/ui-egui/tests/it/battman_modes_dialog.rs +++ b/crates/ui-egui/tests/it/battman_modes_dialog.rs @@ -23,10 +23,32 @@ fn harness() -> Harness<'static, CadApp> { h } +/// Block T with the definitions ROOM and AREA, and BATTMAN opened from its menu item. +fn two_rows() -> Harness<'static, CadApp> { + let mut app = CadApp::new(Session::new(), Services::default()); + let a = app.run("attdef", json!({ "tag": "ROOM", "prompt": "Room", "default": "101", "at": [0, 2] })).unwrap(); + let b = app.run("attdef", json!({ "tag": "AREA", "prompt": "Area", "default": "12", "at": [0, 0] })).unwrap(); + app.run("block", json!({ "name": "T", "base": [0, 0], "handles": [a["handle"], b["handle"]], "keep": "delete" })).unwrap(); + menus::activate(&mut app, "battman"); + let mut h = Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state(|ui, app: &mut CadApp| dialogs::show(app, ui.ctx()), app); + h.run_steps(3); + h +} + fn listed(app: &mut CadApp) -> serde_json::Value { app.run("battman", json!({ "name": "T" })).unwrap()["attributes"][0].clone() } +/// Click the field labelled `label` and type `text` at the end of its value, without leaving it. +fn type_at_end(h: &mut Harness<'static, CadApp>, role: Role, label: &str, text: &str) { + h.get_by_role_and_label(role, label).click(); + h.run_steps(2); + h.key_press(egui::Key::End); + h.run_steps(1); + h.get_by_role_and_label(role, label).type_text(text); + h.run_steps(2); +} + fn checked(h: &Harness<'static, CadApp>, label: &str) -> bool { h.get_by_role_and_label(Role::CheckBox, label).accesskit_node().toggled() == Some(Toggled::True) } @@ -83,3 +105,62 @@ fn a_multiline_default_is_edited_on_several_lines() { h.run_steps(3); assert_eq!(listed(h.state_mut())["default"], "101\nsecond"); } + +#[test] +fn a_multiline_default_is_committed_when_another_row_is_selected() { + let mut h = two_rows(); + h.get_by_role_and_label(Role::CheckBox, "Multiple lines").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::MultilineTextInput, "Default").click(); + h.run_steps(2); + h.key_press(egui::Key::End); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(1); + h.get_by_role_and_label(Role::MultilineTextInput, "Default").type_text("second"); + h.run_steps(2); + // Enter was a line break: nothing is committed until the field goes. Selecting AREA does that. + assert_eq!(listed(h.state_mut())["default"], "101"); + h.get_by_label("AREA").click(); + h.run_steps(3); + h.get_by_label("Edit attribute AREA"); + assert_eq!(listed(h.state_mut())["default"], "101\nsecond"); + // AREA's field shows AREA's own value, and ROOM's shows the committed one when selected again. + assert_eq!(h.get_by_role_and_label(Role::TextInput, "Default").accesskit_node().value().as_deref(), Some("12")); + h.get_by_label("ROOM").click(); + h.run_steps(3); + assert_eq!(h.get_by_role_and_label(Role::MultilineTextInput, "Default").accesskit_node().value().as_deref(), Some("101\nsecond")); +} + +#[test] +fn one_line_fields_are_committed_when_another_row_is_selected() { + let mut h = two_rows(); + for (label, key, typed, want) in [("Prompt", "prompt", "s", "Rooms"), ("Default", "default", "9", "1019"), ("Tag", "tag", "S", "ROOMS")] { + let tag = listed(h.state_mut())["tag"].as_str().unwrap().to_string(); + h.get_by_label(&tag).click(); + h.run_steps(3); + type_at_end(&mut h, Role::TextInput, label, typed); + h.get_by_label("AREA").click(); + h.run_steps(3); + assert_eq!(listed(h.state_mut())[key], want, "{label} committed when AREA is selected"); + } + assert_eq!(listed(h.state_mut())["prompt"], "Rooms"); +} + +#[test] +fn an_edit_is_committed_when_the_dialog_closes_or_a_button_is_clicked() { + let mut h = two_rows(); + // Move Down while the prompt is being typed: the prompt is kept and ROOM moves down. + type_at_end(&mut h, Role::TextInput, "Prompt", "s"); + h.get_by_role_and_label(Role::Button, "Move Down").click(); + h.run_steps(3); + let rows = h.state_mut().run("battman", json!({ "name": "T" })).unwrap()["attributes"].clone(); + assert_eq!((rows[0]["tag"].as_str(), rows[1]["tag"].as_str(), rows[1]["prompt"].as_str()), (Some("AREA"), Some("ROOM"), Some("Rooms"))); + // Closing the dialog while the default is being typed keeps it. + type_at_end(&mut h, Role::TextInput, "Default", "9"); + h.get_by_role_and_label(Role::Button, "Close window").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog, None); + let rows = h.state_mut().run("battman", json!({ "name": "T" })).unwrap()["attributes"].clone(); + assert_eq!(rows[1]["default"], "1019"); +}