From de73d8c71cc674ae126de1fe49e4a637c712fc85 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 11:36:16 +0200 Subject: [PATCH 01/30] Text formulas and fields: =... in text, dimensions and leaders; UPDATEFIELD Split out of #2034. - A text, mtext, attribute definition, multileader or dimension text that starts with `=` keeps the formula and shows the result (render textformula: arithmetic, comparisons, text, date and math functions; `<>` is a dimension's measurement). - AutoCAD date fields in DXF are read (dxf_fields) and updated; formulas round-trip as CADCRAFTFORMULA xdata. - Formulas and fields are worked out again when a drawing opens; Tools > Update Fields (UPDATEFIELD) does it at once; Help > Text Formulas. - A formula typed where a distance or number is asked (`=1200+350*2`) is worked out first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- Cargo.lock | 86 ++ apps/cadcraft-cli/src/main.rs | 1 + crates/constraints/src/tests.rs | 1 + crates/doc/src/entity/dim.rs | 4 + crates/doc/src/entity/text.rs | 8 + crates/doc/src/extents.rs | 2 + crates/doc/src/tests.rs | 4 + crates/engine/src/cmd/annotate/mleader.rs | 2 + crates/engine/src/cmd/blocks.rs | 1 + crates/engine/src/cmd/draw/text.rs | 2 + crates/engine/src/cmd/file.rs | 5 +- crates/engine/src/cmd/modify/explode.rs | 2 + crates/engine/src/cmd/modify2.rs | 5 +- crates/engine/src/cmd/modify2/textedit.rs | 31 +- crates/engine/src/cmd/mtext_opts.rs | 1 + crates/engine/src/cmd/props.rs | 9 + crates/engine/src/cmd/tolerance.rs | 1 + crates/engine/src/cmd/txt2mtxt.rs | 2 + crates/engine/src/formula.rs | 130 +++ crates/engine/src/lib.rs | 13 + crates/engine/src/sample.rs | 3 +- crates/engine/src/session/cmdline.rs | 16 + crates/engine/src/spatial.rs | 1 + crates/engine/src/textformula.rs | 126 +++ crates/engine/tests/audit.rs | 1 + crates/engine/tests/it/attrib_modes.rs | 1 + crates/engine/tests/it/formula_input.rs | 23 + crates/engine/tests/it/main.rs | 2 + crates/engine/tests/it/mtext_columns.rs | 1 + .../engine/tests/it/multiline_attributes.rs | 2 + crates/engine/tests/it/snap_annotations.rs | 1 + crates/engine/tests/it/text_formulas.rs | 134 +++ crates/engine/tests/usage.rs | 1 + crates/io/src/dxf_ext.rs | 39 + crates/io/src/dxf_fields.rs | 204 ++++ crates/io/src/dxf_mleader.rs | 1 + crates/io/src/dxf_read.rs | 1 + crates/io/src/dxf_read/entities.rs | 1 + crates/io/src/dxf_read/text.rs | 2 + crates/io/src/dxf_write/blocks.rs | 2 + crates/io/src/dxf_write/common.rs | 9 + crates/io/src/dxf_write/entity.rs | 5 +- crates/io/src/lib.rs | 1 + crates/io/src/tests.rs | 7 + crates/io/tests/it/acad_interop.rs | 2 + crates/io/tests/it/annotative_roundtrip.rs | 1 + crates/io/tests/it/attrib_modes.rs | 1 + crates/io/tests/it/attrib_props.rs | 1 + crates/io/tests/it/dxf_versions.rs | 1 + crates/io/tests/it/entity_props_roundtrip.rs | 1 + crates/io/tests/it/followups_626.rs | 2 + crates/io/tests/it/main.rs | 1 + crates/io/tests/it/mleader_roundtrip.rs | 2 + crates/io/tests/it/mtext_columns_roundtrip.rs | 1 + crates/io/tests/it/mtext_embedded_object.rs | 1 + crates/io/tests/it/mtext_line_spacing.rs | 1 + crates/io/tests/it/text_formula_roundtrip.rs | 44 + crates/io/tests/pdf_text.rs | 2 + crates/render/Cargo.toml | 3 + crates/render/src/dim.rs | 4 +- crates/render/src/dim/text.rs | 32 +- crates/render/src/lib.rs | 1 + crates/render/src/tests.rs | 5 + crates/render/src/textformula.rs | 913 ++++++++++++++++++ crates/render/tests/it/annotative_viewport.rs | 1 + crates/render/tests/it/dim_text_fill.rs | 4 + crates/render/tests/it/render_props.rs | 1 + crates/ui-egui/src/dialogs.rs | 24 + crates/ui-egui/src/menus.rs | 2 + 69 files changed, 1933 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/formula.rs create mode 100644 crates/engine/src/textformula.rs create mode 100644 crates/engine/tests/it/formula_input.rs create mode 100644 crates/engine/tests/it/text_formulas.rs create mode 100644 crates/io/src/dxf_fields.rs create mode 100644 crates/io/tests/it/text_formula_roundtrip.rs create mode 100644 crates/render/src/textformula.rs diff --git a/Cargo.lock b/Cargo.lock index b646729fb5..e63768be8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -723,6 +723,7 @@ dependencies = [ "cadcraft-doc", "cadcraft-fonts", "cadcraft-geom", + "jiff", "lyon_tessellation", "rayon", "serde_json", @@ -1121,6 +1122,37 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "deranged" version = "0.5.9" @@ -2252,6 +2284,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jni" version = "0.22.4" diff --git a/apps/cadcraft-cli/src/main.rs b/apps/cadcraft-cli/src/main.rs index 99a8b4282c..1049f1a080 100644 --- a/apps/cadcraft-cli/src/main.rs +++ b/apps/cadcraft-cli/src/main.rs @@ -579,6 +579,7 @@ fn synthetic(n: usize, side: f64) -> Result EntityKind::Text(d::Text { + formula: None, insert: v3(x, y), align_pt: None, height: s * 0.2, diff --git a/crates/constraints/src/tests.rs b/crates/constraints/src/tests.rs index 35b73fea20..570232ac34 100644 --- a/crates/constraints/src/tests.rs +++ b/crates/constraints/src/tests.rs @@ -318,6 +318,7 @@ fn invalid_references_and_purge() { let t = add_e( &mut d, EntityKind::Text(cadcraft_doc::Text { + formula: None, insert: v(0.0, 0.0), align_pt: None, height: 1.0, diff --git a/crates/doc/src/entity/dim.rs b/crates/doc/src/entity/dim.rs index 396e74c6f9..bc07077b0b 100644 --- a/crates/doc/src/entity/dim.rs +++ b/crates/doc/src/entity/dim.rs @@ -85,6 +85,10 @@ pub struct DimMarks { /// Inspection frame, label and rate (DIMINSPECT). #[serde(skip_serializing_if = "Option::is_none")] pub inspect: Option, + /// A formula for the dimension text (`=<>/2`, `=TEXT(<>,"0.0")&" mm"`; `<>` is the + /// measurement); `Dimension::text` holds the last result. + #[serde(skip_serializing_if = "Option::is_none")] + pub formula: Option, } impl DimMarks { diff --git a/crates/doc/src/entity/text.rs b/crates/doc/src/entity/text.rs index a4eff04277..d60b7c5b84 100644 --- a/crates/doc/src/entity/text.rs +++ b/crates/doc/src/entity/text.rs @@ -42,6 +42,10 @@ pub struct Text { pub halign: HAlign, #[serde(default)] pub valign: VAlign, + /// The formula the text shows the result of: `=...` (CADCraft text formulas) or an AutoCAD + /// field code (`%<\AcVar date \f "dd.MM.yyyy">%`). `value` holds the last result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub formula: Option, } impl Text { @@ -83,6 +87,10 @@ pub struct MText { /// one column. #[serde(default, skip_serializing_if = "Option::is_none")] pub columns: Option, + /// The formula the text shows the result of (see [`Text::formula`]); `contents` holds the + /// last result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub formula: Option, } fn attach_tl() -> u8 { diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index d7c7c7a8a0..1469326fa6 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -292,6 +292,7 @@ mod tests { fn text(halign: HAlign, valign: VAlign) -> Text { Text { + formula: None, insert: Vec3::new(0.0, 0.0, 0.0), align_pt: Some(Vec3::new(0.0, 0.0, 0.0)), height: 1.0, @@ -346,6 +347,7 @@ mod tests { #[test] fn multileader_text_is_inside_its_bounds() { let mtext = crate::MText { + formula: None, insert: Vec3::new(25.45, 0.0, 0.0), height: 5.0, width: 0.0, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 067d42ac09..14e931a240 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -103,6 +103,7 @@ fn visible_attributes_of_a_missing_block_still_count() { let attrib = |invisible: bool| Attrib { tag: "TAG".into(), text: Text { + formula: None, insert: Vec3::new(1000.0, 1000.0, 0.0), align_pt: None, height: 10.0, @@ -441,6 +442,7 @@ fn attdef_in_block_is_ignored_in_insert_extents() { EntityKind::AttDef(Attrib { tag: "TAG".into(), text: Text { + formula: None, insert: Vec3::new(5000.0, 5000.0, 0.0), align_pt: None, height: 1.0, @@ -466,6 +468,7 @@ fn attdef_in_block_is_ignored_in_insert_extents() { fn text_kind(value: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, insert: Vec3::new(10.0, 10.0, 0.0), align_pt: None, height: 2.0, @@ -481,6 +484,7 @@ fn text_kind(value: &str) -> EntityKind { fn mtext_kind(contents: &str) -> EntityKind { EntityKind::MText(MText { + formula: None, insert: Vec3::new(10.0, 10.0, 0.0), height: 2.0, width: 0.0, diff --git a/crates/engine/src/cmd/annotate/mleader.rs b/crates/engine/src/cmd/annotate/mleader.rs index c2e0a63df0..b422268c8a 100644 --- a/crates/engine/src/cmd/annotate/mleader.rs +++ b/crates/engine/src/cmd/annotate/mleader.rs @@ -19,6 +19,7 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option< landing: v3(*landing_pt), dogleg, text: (!text.is_empty()).then(|| MText { + formula: None, insert: v3(tpos), height: th, width: 0.0, @@ -66,6 +67,7 @@ pub(super) fn run_leader(s: &mut Session, p: &Value) -> Result { let th = s.doc()?.dim_style(&style(s)).map(|d| d.text_height).unwrap_or(0.18); out.push( s.add_entity(EntityKind::MText(MText { + formula: None, insert: v3(*last + Vec2::new(th * 0.5, th * 0.5)), height: th, width: 0.0, diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 15d75da14f..19f01a3be6 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -312,6 +312,7 @@ fn attdef_kind(s: &Session, tag: &str, prompt: &str, default: &str, at: Vec2, he EntityKind::AttDef(Attrib { tag: tag.to_ascii_uppercase(), text: Text { + formula: None, insert: v3(at), align_pt: None, height, diff --git a/crates/engine/src/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 2ca220a9ba..0b0bc4d8a6 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -27,6 +27,7 @@ pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotatio let (h, v) = j; let left = h == HAlign::Left && v == VAlign::Baseline; EntityKind::Text(Text { + formula: None, insert: v3(at), align_pt: if left { None } else { Some(v3(at)) }, height, @@ -69,6 +70,7 @@ pub(super) fn run_mtext(s: &mut Session, p: &Value) -> Result { }; let width = f64_or(p, "width", 0.0).max(0.0); let k = EntityKind::MText(MText { + formula: None, insert: v3(at), height, width, diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 95975a4e28..067d79f78e 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -310,7 +310,10 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result) -> usize { +fn add_read(s: &mut Session, mut drawing: Drawing, binary_dxf: bool, name: &str, path: Option) -> usize { + // Formulas and fields (dates) worked out for today. + let env = crate::textformula::Env { now: crate::textformula::local_now(), file: file_name(name), sheet: "Model".into(), measured: None }; + crate::textformula::refresh(&mut drawing, &env); let notes = drawing.read_notes.clone(); let i = s.open_drawing(drawing, &file_name(name), path); if let Some(st) = s.docs.get_mut(i) { diff --git a/crates/engine/src/cmd/modify/explode.rs b/crates/engine/src/cmd/modify/explode.rs index 3b25ccfeea..13fc63180b 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -36,6 +36,7 @@ fn explode_mtext(e: &Entity, m: &cadcraft_doc::MText) -> Vec { handle: Handle(0), common: e.common.clone(), kind: EntityKind::Text(cadcraft_doc::Text { + formula: None, insert: v3(at), align_pt: None, height: m.height, @@ -108,6 +109,7 @@ fn explode_dimension(d: &cadcraft_doc::Drawing, e: &Entity, dm: &cadcraft_doc::D handle: Handle(0), common: e.common.clone(), kind: EntityKind::MText(cadcraft_doc::MText { + formula: None, insert: v3(g.text_pos), height: g.text_height, width: 0.0, diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index 8d814ebe07..05fd9a1177 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -80,6 +80,9 @@ pub fn specs() -> Vec { .menu(&["Modify", "Array", "Path Array"]) .params("{handles?, path (handle), count? (default 6) | spacing?, align?: bool (default true)}") .interactive(|_| Ok(Box::new(PathArrayM::default()))), + CommandSpec::new("updatefield", "Update Fields", run_updatefield) + .menu(&["Tools", "Update Fields"]) + .params("{} (works out every text formula and known field again: dates, file name)"), CommandSpec::new("textedit", "Edit Text...", run_textedit) .menu(&["Modify", "Object", "Edit Text..."]) .alias(&["ed", "ddedit"]) @@ -153,7 +156,7 @@ pub(super) use patharray::PathArrayM; use patharray::run_arraypath; use pedit::{PPhase, PeditM, run_pedit}; use selop::{SelKind, SelOp, run_chspace, run_flatten, run_reverse}; -use textedit::{TextEditM, run_textedit}; +use textedit::{TextEditM, run_textedit, run_updatefield}; use trimext::{ellipse_kind, ellipse_of}; pub(crate) use trimext::{extend_other, trim_other}; diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index d160d992f4..9b952b0e09 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -4,12 +4,20 @@ use super::*; // TEXTEDIT // ===================================================================================== +/// A text formula (`=...`) of an object, which editing shows instead of its result. +fn formula_of(x: &Option) -> Option { + x.clone().filter(|f| crate::textformula::is_formula(f)) +} + +/// The text an edit starts from: the formula when the object has one, else its text. fn text_of(k: &EntityKind) -> Option { match k { - EntityKind::Text(t) => Some(t.value.clone()), - EntityKind::AttDef(a) => Some(a.text.value.clone()), - EntityKind::MText(t) => Some(t.contents.replace("\\P", "\n")), - EntityKind::Dimension(d) => Some(if d.text.is_empty() { "<>".into() } else { d.text.clone() }), + EntityKind::Text(t) => Some(formula_of(&t.formula).unwrap_or_else(|| t.value.clone())), + EntityKind::AttDef(a) => Some(formula_of(&a.text.formula).unwrap_or_else(|| a.text.value.clone())), + EntityKind::MText(t) => Some(formula_of(&t.formula).unwrap_or_else(|| t.contents.replace("\\P", "\n"))), + EntityKind::Dimension(d) => { + Some(formula_of(&d.marks.formula).unwrap_or_else(|| if d.text.is_empty() { "<>".into() } else { d.text.clone() })) + } _ => None, } } @@ -19,6 +27,9 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { return Err(other("The object is on a locked layer.")); } let mut k = curves::entity(s, h)?.kind; + // The text as the edit showed it (a formula, else the value): unchanged, it keeps its + // formula or AutoCAD field. + let unchanged = text_of(&k).is_some_and(|shown| shown == text || shown == text.replace('\n', "\\P")); match &mut k { EntityKind::Text(t) => t.value = text.to_string(), EntityKind::AttDef(a) => a.text.value = text.to_string(), @@ -29,9 +40,21 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { } _ => return Err(other("Select a text, mtext, attribute definition or dimension.")), } + let mut env = crate::textformula::env(s); + if let EntityKind::Dimension(dm) = &k { + env.measured = crate::textformula::measured(s.doc()?, dm); + } + crate::textformula::apply(&mut k, &env, !unchanged); set_kind(s, h, k) } +pub(super) fn run_updatefield(s: &mut Session, _p: &Value) -> Result { + let env = crate::textformula::env(s); + let n = crate::textformula::refresh(s.doc_mut()?, &env); + s.echo(format!("{n} field(s) updated")); + Ok(json!({ "updated": n })) +} + pub(super) fn run_textedit(s: &mut Session, p: &Value) -> Result { let h = targets(s, p)?.first().copied().ok_or_else(|| bad("textedit", "`handle` is required"))?; let text = str_param(p, "text").ok_or_else(|| bad("textedit", "`text` is required"))?; diff --git a/crates/engine/src/cmd/mtext_opts.rs b/crates/engine/src/cmd/mtext_opts.rs index c234271bf8..285eeca4e2 100644 --- a/crates/engine/src/cmd/mtext_opts.rs +++ b/crates/engine/src/cmd/mtext_opts.rs @@ -79,6 +79,7 @@ impl MTextOpts { (None, w) => (first, w.unwrap_or(0.0)), }; MText { + formula: None, insert: Vec3::new(insert.x, insert.y, 0.0), height: self.height, width, diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index f9fbf29694..fd892eb5d0 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -197,6 +197,9 @@ fn run_set(s: &mut Session, p: &Value) -> Result { .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) .transpose()?; let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; + // A new text is worked out like a typed one: a formula becomes the text's formula, other + // text drops the one it had. + let formula_env = crate::textformula::env(s); let d = s.doc_mut()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). let linetype = str_param(p, "linetype") @@ -218,6 +221,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { let anno_scale = d.current_anno_scale(); for h in &hs { d.modify_entity(*h, |e| { + let mut new_text = false; // Annotative: Yes supports the current annotation scale; No drops every scale. if let Some(a) = p.get("annotative").and_then(Value::as_bool) { cadcraft_doc::set_annotative(e, a, &anno_scale); @@ -301,6 +305,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { EntityKind::Text(t) => { if let Some(v) = str_param(p, "text") { t.value = v.to_string(); + new_text = true; } if let Some(x) = num("height").filter(|x| *x > 0.0) { t.height = x; @@ -323,6 +328,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { EntityKind::MText(t) => { if let Some(v) = str_param(p, "text") { t.contents = v.replace('\n', "\\P"); + new_text = true; } if let Some(x) = num("height").filter(|x| *x > 0.0) { t.height = x; @@ -417,6 +423,9 @@ fn run_set(s: &mut Session, p: &Value) -> Result { } _ => {} } + if new_text { + crate::textformula::apply(&mut e.kind, &formula_env, true); + } })?; } Ok(json!({ "changed": hs.len() })) diff --git a/crates/engine/src/cmd/tolerance.rs b/crates/engine/src/cmd/tolerance.rs index b4edfe0f9c..a1f1531be8 100644 --- a/crates/engine/src/cmd/tolerance.rs +++ b/crates/engine/src/cmd/tolerance.rs @@ -297,6 +297,7 @@ pub(crate) fn explode(d: &Drawing, e: &Entity, t: &Tolerance) -> Vec { } for tx in &g.texts { v.push(mk(EntityKind::Text(cadcraft_doc::Text { + formula: None, insert: v3(tx.pos), align_pt: None, height: tx.height, diff --git a/crates/engine/src/cmd/txt2mtxt.rs b/crates/engine/src/cmd/txt2mtxt.rs index 6682ee4d29..7302280db3 100644 --- a/crates/engine/src/cmd/txt2mtxt.rs +++ b/crates/engine/src/cmd/txt2mtxt.rs @@ -97,6 +97,7 @@ fn convert(s: &mut Session, hs: &[Handle], o: &Txt2MtxtOptions) -> Result<(Vec>().join(sep); let width = if o.wrap { items.iter().map(|(_, k, _)| line_width(k)).fold(0.0, f64::max) } else { 0.0 }; let m = MText { + formula: None, insert: v3(corner), height, width, @@ -186,6 +187,7 @@ fn single(t: &Text) -> MText { _ => 2, }; MText { + formula: None, insert: v3(t.justify_point()), height: t.height, width: 0.0, diff --git a/crates/engine/src/formula.rs b/crates/engine/src/formula.rs new file mode 100644 index 0000000000..d751fe9c8d --- /dev/null +++ b/crates/engine/src/formula.rs @@ -0,0 +1,130 @@ +//! Formulas typed at a prompt: `=1200+350*2`, `=(2400-50)/3`. A value starting with `=` is +//! worked out with `+`, `-`, `*`, `/`, parentheses and unary minus, and the result is the answer +//! (a distance, a length, a number of items...). + +/// Longest formula read. +const MAX_LEN: usize = 256; +/// Deepest nesting of parentheses and signs. +const MAX_DEPTH: usize = 32; + +/// The value of `text` when it is a formula (`=` then an expression); `None` when it is not one, +/// `Some(Err)` with the reason when it is one that can't be worked out. +pub fn eval(text: &str) -> Option> { + let body = text.trim().strip_prefix('=')?; + if body.len() > MAX_LEN { + return Some(Err("The formula is too long.".into())); + } + let mut p = Parser { s: body.as_bytes(), i: 0, depth: 0 }; + let v = p.expr().and_then(|v| { + p.ws(); + if p.i < p.s.len() { Err(format!("Unexpected \"{}\" in the formula.", &body[p.i..])) } else { Ok(v) } + }); + Some(v.and_then(|v| if v.is_finite() { Ok(v) } else { Err("The formula has no finite value (division by zero?).".into()) })) +} + +struct Parser<'a> { + s: &'a [u8], + i: usize, + depth: usize, +} + +impl Parser<'_> { + fn ws(&mut self) { + while self.s.get(self.i).is_some_and(u8::is_ascii_whitespace) { + self.i += 1; + } + } + fn peek(&mut self) -> Option { + self.ws(); + self.s.get(self.i).copied() + } + fn expr(&mut self) -> Result { + let mut v = self.term()?; + while let Some(c @ (b'+' | b'-')) = self.peek() { + self.i += 1; + let r = self.term()?; + v = if c == b'+' { v + r } else { v - r }; + } + Ok(v) + } + fn term(&mut self) -> Result { + let mut v = self.factor()?; + while let Some(c @ (b'*' | b'/' | b'x' | b'X')) = self.peek() { + self.i += 1; + let r = self.factor()?; + v = if c == b'/' { v / r } else { v * r }; + } + Ok(v) + } + fn factor(&mut self) -> Result { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err("The formula is nested too deeply.".into()); + } + let r = match self.peek() { + Some(b'-') => { + self.i += 1; + self.factor().map(|v| -v) + } + Some(b'+') => { + self.i += 1; + self.factor() + } + Some(b'(') => { + self.i += 1; + let v = self.expr()?; + if self.peek() != Some(b')') { + return Err("A \")\" is missing in the formula.".into()); + } + self.i += 1; + Ok(v) + } + Some(c) if c.is_ascii_digit() || c == b'.' || c == b',' => self.number(), + Some(_) => Err("The formula takes numbers, + - * / and parentheses.".into()), + None => Err("The formula ends too soon.".into()), + }; + self.depth -= 1; + r + } + /// A number; a comma is read as the decimal separator (`2,5`). + fn number(&mut self) -> Result { + let start = self.i; + while self.s.get(self.i).is_some_and(|c| c.is_ascii_digit() || *c == b'.' || *c == b',') { + self.i += 1; + } + // An exponent: 1e3, 2.5E-2. + if self.s.get(self.i).is_some_and(|c| *c == b'e' || *c == b'E') + && self.s.get(self.i + 1).is_some_and(|c| c.is_ascii_digit() || *c == b'-' || *c == b'+') + { + self.i += 2; + while self.s.get(self.i).is_some_and(u8::is_ascii_digit) { + self.i += 1; + } + } + let t = String::from_utf8_lossy(self.s.get(start..self.i).unwrap_or_default()).replace(',', "."); + t.parse::().map_err(|_| format!("\"{t}\" is not a number.")) + } +} + +#[cfg(test)] +mod tests { + use super::eval; + + #[test] + fn formulas_work_out_with_precedence_and_parentheses() { + assert_eq!(eval("=1200+350*2"), Some(Ok(1900.0))); + assert_eq!(eval("= (2400 - 50) / 2"), Some(Ok(1175.0))); + assert_eq!(eval("=-3*-2"), Some(Ok(6.0))); + assert_eq!(eval("=2,5*2"), Some(Ok(5.0))); + assert_eq!(eval("=10/4"), Some(Ok(2.5))); + assert_eq!(eval("=1e3/4"), Some(Ok(250.0))); + assert_eq!(eval("1200"), None); + } + + #[test] + fn bad_formulas_say_why_and_never_panic() { + for f in ["=", "=1+", "=(1+2", "=1/0", "=abc", "=1)2", &format!("={}", "(".repeat(500)), &format!("={}1", "-".repeat(100))] { + assert!(matches!(eval(f), Some(Err(_))), "{f}"); + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index caeda8d7d5..3111934e38 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -19,6 +19,7 @@ pub mod capped_read; pub mod cmd; pub mod doc_path; mod finite; +pub mod formula; pub mod grip_dims; pub mod grips; mod guard; @@ -32,6 +33,7 @@ pub mod select; pub mod snap; pub mod spatial; pub mod sysvars; +pub mod textformula; pub mod undoctl; pub mod units; @@ -252,6 +254,17 @@ impl Session { /// Add an entity to the current space with current properties. pub fn add_entity(&mut self, kind: EntityKind) -> Result { + // Text starting with `=` is a formula: it keeps the formula and shows the result. + let mut kind = kind; + // Multileader and dimension text too, as when it is edited (a dimension's `<>` is its + // measurement). + if matches!(kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::MLeader(_) | EntityKind::Dimension(_)) { + let mut env = textformula::env(self); + if let EntityKind::Dimension(dm) = &kind { + env.measured = textformula::measured(self.doc()?, dm); + } + textformula::apply(&mut kind, &env, true); + } let common = self.current_common(); let space = self.space(); let true_color = self.doc()?.header.get("CECOLOR_RGB").and_then(|v| v.as_i64()); diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 85a222f64b..53e3b3a3f9 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -37,6 +37,7 @@ fn dim(kind: DimKind, p13: Vec2, p14: Vec2, defpt: Vec2) -> EntityKind { fn text(at: Vec2, h: f64, s: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, insert: v3(at), align_pt: None, height: h, @@ -211,7 +212,7 @@ pub fn bracket() -> Drawing { add(on("Notes"), text(Vec2::new(4.1, -0.3), 0.16, "FRONT VIEW")); add( on("Notes"), - EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }), + EntityKind::MText(MText { formula: None, insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }), ); let tb0 = Vec2::new(14.0, -0.5); add(on("Title"), lwpoly(rect_vertices(tb0, tb0 + Vec2::new(4.0, 2.0)), true)); diff --git a/crates/engine/src/session/cmdline.rs b/crates/engine/src/session/cmdline.rs index 5a57e329ec..edb6b6ef12 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -82,6 +82,22 @@ impl Session { if tt.starts_with('\'') { return self.start(tt); } + // A formula (`=1200+350*2`) where a distance or number is asked: its value is the answer. + if (prompt.accept.number || prompt.accept.point) + && let Some(r) = crate::formula::eval(tt) + { + return match r { + Ok(v) => { + let v = if v.fract() == 0.0 && v.abs() < 1e15 { format!("{v:.0}") } else { format!("{v}") }; + self.echo(format!("{tt} = {v}")); + self.typed(&v) + } + Err(e) => { + self.echo(e); + Ok(()) + } + }; + } // A LISP expression typed at a command's prompt: its value is the answer. // Not at a free-text prompt: there the text is the answer (CAL takes "(3+4)*2"). if lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() { diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index ca15bd4c4f..174c0c1479 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -330,6 +330,7 @@ mod tests { plinegen: false, }), 5 => EntityKind::Text(Text { + formula: None, insert: v3(x, y), align_pt: None, height: s * 0.3, diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs new file mode 100644 index 0000000000..c3532bff4c --- /dev/null +++ b/crates/engine/src/textformula.rs @@ -0,0 +1,126 @@ +//! Formulas in text applied to drawings: a text, multiline text, multileader or dimension text +//! whose value is a formula (`=...`, one line) keeps the formula and shows its result; formulas and +//! AutoCAD fields are worked out again when a drawing is opened. The evaluator and the function +//! list are [`cadcraft_render::textformula`]. + +use cadcraft_doc::{Drawing, EntityKind}; +pub use cadcraft_render::textformula::{Env, FUNCTIONS, evaluate, has_fields, is_formula, local_now}; + +/// The environment of a session's drawing. +pub fn env(s: &crate::Session) -> Env { + let file = s + .state() + .ok() + .map(|st| match &st.path { + Some(p) => std::path::Path::new(p).file_name().map_or_else(|| p.clone(), |n| n.to_string_lossy().into_owned()), + None => st.title.clone(), + }) + .unwrap_or_default(); + Env { now: local_now(), file, sheet: s.space().tab_name().to_string(), measured: None } +} + +// ---------- applying to a drawing ---------- + +/// The measurement a dimension shows (for `<>` in its formula). +pub fn measured(d: &Drawing, dm: &cadcraft_doc::Dimension) -> Option { + let plain = cadcraft_doc::Dimension { + text: String::new(), + block: None, + marks: cadcraft_doc::DimMarks { formula: None, ..dm.marks.clone() }, + ..dm.clone() + }; + let v = cadcraft_render::dimension_in(d, &plain).value; + let s: String = v + .chars() + .skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.') + .take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')) + .collect(); + s.replace(' ', "").replace(',', ".").parse().ok() +} + +/// A text object's formula, worked out into what it shows: a value that is a formula (one line +/// starting with `=`) becomes its formula; a formula's result becomes the value. `edited` is a +/// value just typed: typing over an AutoCAD field turns it into plain text, typing a value that +/// is not a formula drops the formula. Text, attribute definitions, multiline text, +/// multileader text and dimension text (whose `<>` is its measurement, `env.measured`). +pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { + // Multiline text keeps a result's `\`, `{` and `}` as letters, not formatting codes. + let (value, formula, mtext): (&mut String, &mut Option, bool) = match kind { + EntityKind::Text(t) => (&mut t.value, &mut t.formula, false), + EntityKind::AttDef(a) => (&mut a.text.value, &mut a.text.formula, false), + EntityKind::MText(t) => (&mut t.contents, &mut t.formula, true), + EntityKind::MLeader(m) => match &mut m.text { + Some(t) => (&mut t.contents, &mut t.formula, true), + None => return, + }, + EntityKind::Dimension(d) => (&mut d.text, &mut d.marks.formula, false), + _ => return, + }; + if edited { + let plain = cadcraft_fonts::plain_mtext(value); + if is_formula(&plain) { + *formula = Some(plain.trim().to_string()); + } else { + *formula = None; + return; + } + } + if let Some(f) = formula.as_deref() + && let Some(v) = evaluate(f, env) + { + *value = if mtext { cadcraft_doc::mtext_literal(&v) } else { v }; + } +} + +/// Whether an entity has a formula or field to work out. +fn has_formula(k: &EntityKind) -> bool { + match k { + EntityKind::Text(t) => t.formula.is_some(), + EntityKind::AttDef(a) => a.text.formula.is_some(), + EntityKind::MText(t) => t.formula.is_some(), + EntityKind::MLeader(m) => m.text.as_ref().is_some_and(|t| t.formula.is_some()), + EntityKind::Dimension(d) => d.marks.formula.is_some(), + _ => false, + } +} + +/// Work out every formula and known field of a drawing again (when it is opened): model space, +/// layouts and block definitions. The number of texts worked out. +pub fn refresh(d: &mut Drawing, env: &Env) -> usize { + let mut n = 0; + // Dimensions' measurements first (they need the whole drawing). + let mut measures: std::collections::HashMap> = std::collections::HashMap::new(); + // Dimensions in block definitions too: their `<>` is their own measurement. + for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) { + if let EntityKind::Dimension(dm) = &e.kind + && dm.marks.formula.is_some() + { + measures.insert(e.handle, measured(d, dm)); + } + } + // Each space with its own sheet name (SHEET()): model space is "Model", a layout its name; + // block definitions keep the name given. + let fix = |store: &mut cadcraft_doc::EntityStore, sheet: Option<&str>, n: &mut usize| { + let hs: Vec = store.iter().filter(|e| has_formula(&e.kind)).map(|e| e.handle).collect(); + for h in hs { + let mut env = Env { measured: measures.get(&h).copied().flatten(), ..env.clone() }; + if let Some(sheet) = sheet { + env.sheet = sheet.to_string(); + } + store.modify(h, |e| apply(&mut e.kind, &env, false)); + *n += 1; + } + }; + fix(&mut d.model, Some("Model"), &mut n); + for l in &mut d.layouts { + let name = l.name.clone(); + fix(&mut l.entities, Some(&name), &mut n); + } + let names: Vec = d.blocks.iter().filter(|(_, b)| b.entities.iter().any(|e| has_formula(&e.kind))).map(|(k, _)| k.clone()).collect(); + for k in names { + if let Some(b) = d.blocks.get_mut(&k) { + fix(&mut std::sync::Arc::make_mut(b).entities, None, &mut n); + } + } + n +} diff --git a/crates/engine/tests/audit.rs b/crates/engine/tests/audit.rs index 8c1ce9c4a9..b3b2d5dd08 100644 --- a/crates/engine/tests/audit.rs +++ b/crates/engine/tests/audit.rs @@ -57,6 +57,7 @@ fn corrupt(d: &mut Drawing) -> (Handle, Handle) { &Space::Model, on("0"), EntityKind::Text(Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 1.0, diff --git a/crates/engine/tests/it/attrib_modes.rs b/crates/engine/tests/it/attrib_modes.rs index 65238823aa..1ae19aaf1b 100644 --- a/crates/engine/tests/it/attrib_modes.rs +++ b/crates/engine/tests/it/attrib_modes.rs @@ -12,6 +12,7 @@ use serde_json::json; fn references_take_lock_position_from_the_definition() { let mut d = cadcraft_engine::doc::Drawing::new_imperial(); let text = Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 2.0, diff --git a/crates/engine/tests/it/formula_input.rs b/crates/engine/tests/it/formula_input.rs new file mode 100644 index 0000000000..c2d68c5040 --- /dev/null +++ b/crates/engine/tests/it/formula_input.rs @@ -0,0 +1,23 @@ +//! A formula typed where a distance or number is asked (`=1200+350*2`) is worked out first. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; + +#[test] +fn a_formula_answers_a_distance_prompt() { + let mut s = Session::new(); + s.cmdline("circle 0,0").unwrap(); + s.cmdline("=(10+2)*3/4").unwrap(); + let r = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }).unwrap(); + assert!((r - 9.0).abs() < 1e-12, "{r}"); +} + +#[test] +fn a_bad_formula_is_reported_and_asks_again() { + let mut s = Session::new(); + s.cmdline("circle 0,0").unwrap(); + s.cmdline("=10+").unwrap(); + assert!(s.running.is_some(), "the prompt is still waiting"); + s.cmdline("=5").unwrap(); + assert!(s.running.is_none()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 8babc2c49b..7f569af929 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -41,6 +41,7 @@ mod dynamic_grips; mod fillet_chamfer; mod fix_holds_grips; mod followups_626; +mod formula_input; mod grip_dim_input; mod grip_options; mod grip_selection; @@ -130,6 +131,7 @@ mod table_formulas; mod table_styles; mod temp_tracking; mod text_commands; +mod text_formulas; mod text_left_justify; mod tolerance; mod transparent; diff --git a/crates/engine/tests/it/mtext_columns.rs b/crates/engine/tests/it/mtext_columns.rs index 61420352a7..664686b839 100644 --- a/crates/engine/tests/it/mtext_columns.rs +++ b/crates/engine/tests/it/mtext_columns.rs @@ -85,6 +85,7 @@ fn scale_scales_multileader_text_width_and_columns() { // #709: SCALE 2 on a multileader's text doubles its width and column lengths like it does // for a standalone MTEXT, not only its height. let text = MText { + formula: None, insert: Default::default(), height: 2.0, width: 10.0, diff --git a/crates/engine/tests/it/multiline_attributes.rs b/crates/engine/tests/it/multiline_attributes.rs index b7a7a7d0f5..35cf2b58e3 100644 --- a/crates/engine/tests/it/multiline_attributes.rs +++ b/crates/engine/tests/it/multiline_attributes.rs @@ -12,6 +12,7 @@ use serde_json::json; fn session() -> Session { let mut d = cadcraft_engine::doc::Drawing::new_imperial(); let text = Text { + formula: None, insert: Vec3::new(2.0, 2.0, 0.0), align_pt: None, height: 2.0, @@ -24,6 +25,7 @@ fn session() -> Session { valign: Default::default(), }; let mtext = MText { + formula: None, insert: Vec3::new(10.0, 3.0, 0.0), height: 2.0, width: 0.0, diff --git a/crates/engine/tests/it/snap_annotations.rs b/crates/engine/tests/it/snap_annotations.rs index 97bf0ac289..c570ca966a 100644 --- a/crates/engine/tests/it/snap_annotations.rs +++ b/crates/engine/tests/it/snap_annotations.rs @@ -44,6 +44,7 @@ fn justified_text_snaps_and_grips_at_its_alignment_point() { let mut s = Session::new(); // As read from DXF: a right-justified text keeps group 10 (start) and group 11 (alignment). let t = Text { + formula: None, insert: Vec3::new(0.0, 0.0, 0.0), align_pt: Some(Vec3::new(10.0, 0.0, 0.0)), height: 1.0, diff --git a/crates/engine/tests/it/text_formulas.rs b/crates/engine/tests/it/text_formulas.rs new file mode 100644 index 0000000000..cc1a8a0fd6 --- /dev/null +++ b/crates/engine/tests/it/text_formulas.rs @@ -0,0 +1,134 @@ +//! Text formulas: a text, multiline text, multileader or dimension text that starts with `=` +//! keeps the formula and shows its result; UPDATEFIELD works them out again. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +#[test] +fn text_formulas_show_their_result_and_edit_as_formulas() { + let mut s = Session::new(); + let r = s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=2400-2*18" })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let get = |s: &Session| match &s.doc().unwrap().model.iter().next().unwrap().kind { + EntityKind::Text(t) => (t.value.clone(), t.formula.clone()), + _ => panic!(), + }; + assert_eq!(get(&s), ("2364".to_string(), Some("=2400-2*18".to_string()))); + // Edited as the formula; plain text drops it. + s.execute("textedit", &json!({ "handle": h, "text": "=ROUND(10/3,2)" })).unwrap(); + assert_eq!(get(&s).0, "3.33"); + s.execute("textedit", &json!({ "handle": h, "text": "plain" })).unwrap(); + assert_eq!(get(&s), ("plain".to_string(), None)); + // Dates follow the clock when fields are updated. + s.execute("textedit", &json!({ "handle": h, "text": "=TEXT(TODAY(),\"yyyy\")" })).unwrap(); + let year = get(&s).0; + assert!(year.len() == 4 && year.starts_with("20"), "{year}"); + assert_eq!(s.execute("updatefield", &json!({})).unwrap()["updated"], 1); +} + +#[test] +fn formulas_work_when_editing_multiline_text_dimensions_and_leaders() { + let mut s = Session::new(); + let r = s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "abc" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": m, "text": "{\\fArial|b0;=1200+350*2}" })).unwrap(); + let mt = s.doc().unwrap().model.iter().find_map(|e| match &e.kind { + EntityKind::MText(t) => Some(t.clone()), + _ => None, + }); + let mt = mt.unwrap(); + assert!(cadcraft_fonts::plain_mtext(&mt.contents).contains("1900"), "{}", mt.contents); + // Two lines: not a formula. + s.execute("textedit", &json!({ "handle": m, "text": "=1+1\\Psecond" })).unwrap(); + let mt = s.doc().unwrap().model.iter().find_map(|e| match &e.kind { + EntityKind::MText(t) => Some(t.clone()), + _ => None, + }); + assert!(mt.unwrap().formula.is_none()); +} + +#[test] +fn dimension_text_takes_formulas() { + let mut s = Session::new(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [1250, 0], "at": [600, 100] })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": h, "text": "=<>/2" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + assert_eq!(dm.marks.formula.as_deref(), Some("=<>/2")); + assert_eq!(dm.text, "625"); + assert_eq!(cadcraft_render::dimension_in(d, dm).value, "625"); +} + +/// properties.set replacing a text drops the formula it had (or takes the new one), like +/// typing over it; UPDATEFIELD does not bring the old result back (#2034 review). +#[test] +fn replacing_text_in_properties_updates_its_formula() { + let mut s = Session::new(); + let r = s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=1+1" })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let r = s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "=2+2" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("properties.set", &json!({ "handles": [h, m], "text": "replacement" })).unwrap(); + s.execute("updatefield", &json!({})).unwrap(); + for e in s.doc().unwrap().model.iter() { + match &e.kind { + EntityKind::Text(t) => assert_eq!((t.value.as_str(), t.formula.as_deref()), ("replacement", None)), + EntityKind::MText(t) => assert_eq!((t.contents.as_str(), t.formula.as_deref()), ("replacement", None)), + _ => {} + } + } + // A formula given there is worked out. + s.execute("properties.set", &json!({ "handles": [h], "text": "=3*3" })).unwrap(); + let t = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!((t.value.as_str(), t.formula.as_deref()), ("9", Some("=3*3"))); +} + +/// SHEET() in a layout is that layout's name, in model space "Model", whichever is active when +/// fields are updated (#2034 review). +#[test] +fn sheet_is_each_texts_own_layout() { + let mut s = Session::new(); + s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=SHEET()" })).unwrap(); + let layout = s.doc().unwrap().layouts.first().map(|l| l.name.clone()).unwrap(); + s.execute("layout.set", &json!({ "name": layout })).unwrap(); + s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=SHEET()" })).unwrap(); + s.execute("updatefield", &json!({})).unwrap(); + let d = s.doc().unwrap(); + let value = |e: &std::sync::Arc| if let EntityKind::Text(t) = &e.kind { t.value.clone() } else { String::new() }; + assert_eq!(d.model.iter().map(value).collect::>(), ["Model"]); + let l = d.layouts.iter().find(|l| l.name == layout).unwrap(); + assert_eq!(l.entities.iter().map(value).collect::>(), std::slice::from_ref(&layout)); +} + +/// A new multileader's text that is a formula is worked out as when it is edited; a multiline +/// result keeps `\`, `{` and `}` as letters (#2034 review). +#[test] +fn new_multileader_formulas_and_literal_results() { + let mut s = Session::new(); + s.execute("mleader", &json!({ "points": [[0, 0], [10, 10]], "text": "=2*3" })).unwrap(); + let ml = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.clone() } else { None }).unwrap(); + assert_eq!((cadcraft_fonts::plain_mtext(&ml.contents).as_str(), ml.formula.as_deref()), ("6", Some("=2*3"))); + // In multiline text a brace is written `\{`: the formula is =UPPER("{a}"). + let r = s.execute("mtext", &json!({ "at": [0, 20], "height": 1, "width": 20, "text": "=UPPER(\"\\{a\\}\")" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let mt = s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&m).unwrap()).map(|e| e.kind.clone()); + let Some(EntityKind::MText(mt)) = mt else { panic!() }; + assert_eq!(mt.formula.as_deref(), Some("=UPPER(\"{a}\")")); + assert_eq!(cadcraft_fonts::plain_mtext(&mt.contents), "{A}", "{}", mt.contents); +} + +/// A dimension formula's `<>` is the measurement itself, not the first number in the shown text: +/// a DIMPOST prefix with a digit (`2X<>`) does not become the value (#2034 review). +#[test] +fn a_dimension_formula_uses_the_measurement_not_the_shown_text() { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "DIMPOST", "value": "2X<>" })).unwrap(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [1250, 0], "at": [600, 100] })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": h, "text": "=<>/2" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + assert_eq!(cadcraft_render::dimension_in(d, dm).value, "625"); +} diff --git a/crates/engine/tests/usage.rs b/crates/engine/tests/usage.rs index 9754ce7666..4ddc6f50c7 100644 --- a/crates/engine/tests/usage.rs +++ b/crates/engine/tests/usage.rs @@ -20,6 +20,7 @@ fn text(handle: u64, layer: &str, style: &str) -> Entity { let mut e = Entity::new( Handle(handle), EntityKind::Text(Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 1.0, diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 392ee14002..0d728611ef 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -20,6 +20,45 @@ use serde_json::Value; /// Registered application name of CADCraft's extended data. pub(crate) const APP: &str = "CADCRAFT"; +/// Extended data of a text's formula (`=...`), in 1000 strings of at most 250 characters. +pub(crate) const FORMULA_APP: &str = "CADCRAFTFORMULA"; + +/// A text's formula from its `CADCRAFTFORMULA` extended data. +pub(crate) fn formula(tags: &[Tag]) -> Option { + let x = xdata(tags, FORMULA_APP); + let s: String = x.iter().filter(|t| t.code == 1000).map(|t| t.str()).collect(); + (!s.is_empty()).then_some(s) +} + +/// A formula as 1000 strings of at most 250 bytes (whole characters). +pub(crate) fn formula_chunks(f: &str) -> Vec { + // An xdata string holds at most 255 bytes: Hebrew, Cyrillic or Chinese letters take 2 to 4 + // bytes each, so the pieces are cut by bytes, between letters. + let mut out = Vec::new(); + let mut cur = String::new(); + for c in f.chars().take(4000) { + if cur.len() + c.len_utf8() > 250 { + out.push(std::mem::take(&mut cur)); + } + cur.push(c); + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +#[cfg(test)] +mod formula_chunk_tests { + #[test] + fn chunks_fit_an_xdata_string_in_bytes() { + let f = format!("=\"{}\"", "שלום ".repeat(200)); + let chunks = super::formula_chunks(&f); + assert!(chunks.iter().all(|c| c.len() <= 250), "{:?}", chunks.iter().map(String::len).collect::>()); + assert_eq!(chunks.concat(), f, "nothing lost, no letter cut"); + assert_eq!(super::formula_chunks("=1+1"), ["=1+1"]); + } +} /// Named-object-dictionary key of the constraint XRECORD. pub(crate) const CONSTRAINTS_KEY: &str = "CADCRAFT_CONSTRAINTS"; /// Named-object-dictionary key of the saved layer states XRECORD. diff --git a/crates/io/src/dxf_fields.rs b/crates/io/src/dxf_fields.rs new file mode 100644 index 0000000000..e340b3252c --- /dev/null +++ b/crates/io/src/dxf_fields.rs @@ -0,0 +1,204 @@ +//! AutoCAD fields in text: a TEXT or MTEXT whose extension dictionary holds `ACAD_FIELD` → +//! `TEXT` → a FIELD object. That field's code is the text's template (`Date: %<\_FldIdx 0>%`) +//! and its child fields fill the `\_FldIdx` places (`\AcVar date \f "dd.MM.yyyy"`). The +//! resolved template becomes the text's formula, which the engine works out when the drawing is +//! opened (dates follow the clock); the field objects themselves are kept and written back as +//! they were read. + +use std::collections::HashMap; + +use cadcraft_doc::{Drawing, EntityKind, EntityStore, Handle}; +use cadcraft_dxf::{Section, Tag, records}; + +/// Deepest nesting of fields followed. +const MAX_DEPTH: usize = 8; +/// Longest template kept. +const MAX_LEN: usize = 16_384; + +fn handle_of(tags: &[Tag]) -> Option { + tags.iter().find(|t| t.code == 5).map(|t| t.str().trim().to_ascii_uppercase()) +} + +/// The extension dictionary of a record (`102 {ACAD_XDICTIONARY` `360 handle`). +fn xdict(tags: &[Tag]) -> Option { + let at = tags.iter().position(|t| t.code == 102 && t.str().trim().eq_ignore_ascii_case("{ACAD_XDICTIONARY"))?; + tags.get(at + 1).filter(|t| t.code == 360).map(|t| t.str().trim().to_ascii_uppercase()) +} + +/// A dictionary's entry (`3 name` then `350`/`360 handle`). +fn entry(tags: &[Tag], name: &str) -> Option { + let at = tags.iter().position(|t| t.code == 3 && t.str().trim().eq_ignore_ascii_case(name))?; + tags.get(at + 1).filter(|t| t.code == 350 || t.code == 360).map(|t| t.str().trim().to_ascii_uppercase()) +} + +/// A field's code (2, continued in 3s) with its `\_FldIdx n` places filled from its children. +fn code(objects: &HashMap>, h: &str, depth: usize) -> Option { + code_in(objects, h, depth, &mut HashMap::new()) +} + +/// [`code`], with the codes already worked out (by handle and depth) in `seen`: a file whose +/// fields share children is expanded once per child, not once per reference. +fn code_in(objects: &HashMap>, h: &str, depth: usize, seen: &mut HashMap<(String, usize), Option>) -> Option { + if depth > MAX_DEPTH { + return None; + } + if let Some(done) = seen.get(&(h.to_string(), depth)) { + return done.clone(); + } + let out = expand(objects, h, depth, seen); + seen.insert((h.to_string(), depth), out.clone()); + out +} + +fn expand(objects: &HashMap>, h: &str, depth: usize, seen: &mut HashMap<(String, usize), Option>) -> Option { + let tags = objects.get(h)?; + let start = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbField").unwrap_or(0); + let body = tags.get(start..)?; + // The code and its overflow come before the value data (the first 7 ACFD_FIELD_VALUE). + let end = body.iter().position(|t| t.code == 7).unwrap_or(body.len()); + let own = body.get(..end)?; + let mut s = String::new(); + for t in own.iter().filter(|t| t.code == 2 || t.code == 3) { + s.push_str(&t.str()); + if s.len() > MAX_LEN { + return None; + } + } + let children: Vec = own.iter().filter(|t| t.code == 360).map(|t| t.str().trim().to_ascii_uppercase()).collect(); + for (i, c) in children.iter().enumerate().take(64) { + let place = format!("%<\\_FldIdx {i}>%"); + if s.contains(&place) { + let inner = code_in(objects, c, depth + 1, seen)?; + // The filled-in code stays within the limit too (nested fields can multiply it). + if inner.len() > MAX_LEN { + return None; + } + s = s.replace(&place, &format!("%<{inner}>%")); + if s.len() > MAX_LEN { + return None; + } + } + } + Some(s) +} + +/// Give the texts with AutoCAD fields their templates as formulas. +pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { + let mut objects: HashMap> = HashMap::new(); + for s in secs.iter().filter(|s| s.name == "OBJECTS") { + for (kind, tags) in records(&s.tags) { + if (kind == "DICTIONARY" || kind == "FIELD") + && let Some(h) = handle_of(&tags) + { + objects.insert(h, tags); + } + } + } + if !objects.values().any(|t| t.iter().any(|g| g.code == 100 && g.str().trim() == "AcDbField")) { + return; + } + let mut formulas: HashMap = HashMap::new(); + for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") { + for (kind, tags) in records(&s.tags) { + if !matches!(kind.as_str(), "TEXT" | "MTEXT") { + continue; + } + let found = (|| { + let x = xdict(&tags)?; + let fd = entry(objects.get(&x)?, "ACAD_FIELD")?; + let f = entry(objects.get(&fd)?, "TEXT")?; + let c = code(&objects, &f, 0)?; + let h = Handle::parse_hex(&handle_of(&tags)?)?; + Some((h, c)) + })(); + if let Some((h, c)) = found.filter(|(_, c)| c.contains("%<\\")) { + formulas.insert(h, c); + } + } + } + if formulas.is_empty() { + return; + } + let set = |store: &mut EntityStore| { + let hs: Vec = store.iter().filter(|e| formulas.contains_key(&e.handle)).map(|e| e.handle).collect(); + for h in hs { + let f = formulas.get(&h).cloned(); + store.modify(h, |e| match &mut e.kind { + EntityKind::Text(t) => t.formula = f, + EntityKind::MText(t) => t.formula = f, + _ => {} + }); + } + }; + set(&mut d.model); + for l in &mut d.layouts { + set(&mut l.entities); + } + let names: Vec = + d.blocks.iter().filter(|(_, b)| b.entities.iter().any(|e| formulas.contains_key(&e.handle))).map(|(k, _)| k.clone()).collect(); + for k in names { + if let Some(b) = d.blocks.get_mut(&k) { + set(&mut std::sync::Arc::make_mut(b).entities); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_dxf::Tag; + + fn field(code: &str, children: &[&str]) -> Vec { + let mut t = vec![Tag::s(100, "AcDbField"), Tag::s(2, code)]; + t.extend(children.iter().map(|c| Tag::s(360, *c))); + t + } + + #[test] + fn nested_fields_fill_their_places() { + let mut o = HashMap::new(); + o.insert("A".to_string(), field("Date: %<\\_FldIdx 0>%", &["B"])); + o.insert("B".to_string(), field("\\AcVar date", &[])); + assert_eq!(code(&o, "A", 0).as_deref(), Some("Date: %<\\AcVar date>%")); + } + + /// A hostile file whose fields each use the next one 60 times, 8 deep: the expansion would + /// be 60^8 times the text. It is refused, quickly and without the memory. + #[test] + fn fields_that_multiply_are_refused_without_blowing_up() { + let places: String = (0..60).map(|i| format!("%<\\_FldIdx {i}>%")).collect(); + let mut o = HashMap::new(); + for k in 0..=MAX_DEPTH { + let next = format!("L{}", k + 1); + let kids: Vec<&str> = (0..60).map(|_| next.as_str()).collect(); + o.insert(format!("L{k}"), field(&places, &kids)); + } + o.insert(format!("L{}", MAX_DEPTH + 1), field("x", &[])); + let t = std::time::Instant::now(); + assert_eq!(code(&o, "L0", 0), None); + assert!(t.elapsed().as_secs() < 5, "took {:?}", t.elapsed()); + } + + /// The length cap alone: one level whose filled-in code would pass MAX_LEN is refused. + #[test] + fn a_filled_in_code_past_the_limit_is_refused() { + let mut o = HashMap::new(); + o.insert("A".to_string(), field("%<\\_FldIdx 0>%%<\\_FldIdx 1>%%<\\_FldIdx 2>%", &["B", "B", "B"])); + o.insert("B".to_string(), field(&"x".repeat(MAX_LEN / 2), &[])); + assert_eq!(code(&o, "A", 0), None); + } + + /// Shared children alone: eight levels of two places using one child each fit the limit and + /// are worked out (each child once per level, not 2^8 times). + #[test] + fn shared_children_are_filled_in() { + let mut o = HashMap::new(); + for k in 0..MAX_DEPTH { + let next = format!("L{}", k + 1); + o.insert(format!("L{k}"), field("%<\\_FldIdx 0>%%<\\_FldIdx 1>%", &[next.as_str(), next.as_str()])); + } + o.insert(format!("L{MAX_DEPTH}"), field("x", &[])); + let c = code(&o, "L0", 0).expect("fits the limit"); + assert_eq!(c.matches('x').count(), 1 << MAX_DEPTH); + } +} diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index 04ce90a014..528170711a 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -300,6 +300,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { _ => p.text_rotation.unwrap_or(0.0), }; MText { + formula: None, insert: text_location.unwrap_or(landing), height: pos(p.text_height).unwrap_or(def.text_height), width: p.text_width.unwrap_or(0.0).max(0.0), diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 88d1801c3b..90d7771b93 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -133,6 +133,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { d.layers.insert(0, Layer::default()); } crate::dxf_raw::read(&secs, &mut d); + crate::dxf_fields::resolve(&secs, &mut d); d.skipped_records = skipped; Ok(d) } diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 9f0816d2a7..8270c9a6ac 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -422,6 +422,7 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK dm.p15 = center; } dm.marks = crate::dxf_ext::read_marks(tags); + dm.marks.formula = crate::dxf_ext::formula(tags); // Group 52: the extension lines' angle relative to the dimension line (DIMEDIT Oblique). let base = match dm.kind { DimKind::Linear { rotation } => Some(rotation), diff --git a/crates/io/src/dxf_read/text.rs b/crates/io/src/dxf_read/text.rs index 45ee2f0033..f4b29050b5 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -71,6 +71,7 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText { }; } MText { + formula: crate::dxf_ext::formula(tags), insert: t.p(10), height: t.fd(40, 0.2).max(1e-9), width: match &columns { @@ -114,6 +115,7 @@ pub(super) fn text_from(t: &T) -> Text { style: t.s(7).unwrap_or_else(|| "Standard".into()), halign: h, valign: v, + formula: crate::dxf_ext::formula(t.0), }; let n = Vec3::new(t.fd(210, 0.0), t.fd(220, 0.0), t.fd(230, 1.0)); if n.z < 0.0 { diff --git a/crates/io/src/dxf_write/blocks.rs b/crates/io/src/dxf_write/blocks.rs index 6514d49bc8..ae7fda2eac 100644 --- a/crates/io/src/dxf_write/blocks.rs +++ b/crates/io/src/dxf_write/blocks.rs @@ -114,6 +114,7 @@ pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Ve handle: Handle(0), common: text_c, kind: EntityKind::MText(MText { + formula: None, insert: g.text_pos.to3(0.0), height: g.text_height, width: 0.0, @@ -168,6 +169,7 @@ pub(crate) fn table_block_entities(d: &Drawing, t: &Table, layer: &str) -> Vec i64 { i64::from(a.invisible) | if a.constant { 2 } else { 0 } | if a.modes.verify { 4 } else { 0 } | if a.modes.preset { 8 } else { 0 } } +/// A text's own formula (`=...`) as extended data; AutoCAD fields stay in their own objects. +pub(super) fn formula_xdata(w: &mut W, f: Option<&str>) { + let Some(f) = f.filter(|f| f.trim_start().starts_with('=')) else { return }; + w.s(1001, dxf_ext::FORMULA_APP); + for c in dxf_ext::formula_chunks(f) { + w.s(1000, c); + } +} + /// A TEXT's groups, or an attribute's (`attrib`, in a file of version `target`) with its /// subclass: the subclass version (`280 0`, 2010 and later), prompt, tag, flags and alignment, /// then Lock position (`280`, 2007 and later; readers take the 280 after the tag as it). diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 6c58cdfacc..8f8cfc726a 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -1,5 +1,5 @@ use super::blocks::table_size; -use super::common::{attrib_common, common, common_x, dim_xdata, layer_and_props, multiline_tags, oblique_52, text_tags}; +use super::common::{attrib_common, common, common_x, dim_xdata, formula_xdata, layer_and_props, multiline_tags, oblique_52, text_tags}; use super::ctx::Ctx; use super::layout::paper_view; use super::*; @@ -204,6 +204,7 @@ pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo common(w, e, owner, paper, "AcDbText"); thickness(w, e); text_tags(w, d, t, None, None); + formula_xdata(w, t.formula.as_deref()); } // Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS. EntityKind::Region(r) => { @@ -254,6 +255,7 @@ pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo w.i(73, if t.line_spacing_exact { 2 } else { 1 }); w.f(44, t.line_spacing); w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t)); + formula_xdata(w, t.formula.as_deref()); } EntityKind::Insert(i) => { w.s(0, "INSERT"); @@ -377,6 +379,7 @@ pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo } } dim_xdata(w, dm, cx); + formula_xdata(w, dm.marks.formula.as_deref()); } EntityKind::Table(t) => { // Tables without a generated block (none expected) are not written. diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ef56e66023..e9f87559f0 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -6,6 +6,7 @@ mod dxf_raw; mod dxf_ext; +mod dxf_fields; mod dxf_image; mod dxf_mleader; mod dxf_read; diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index d5fe5d2f7f..59922a456d 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -30,6 +30,7 @@ fn sample() -> Drawing { &Space::Model, c("0"), EntityKind::Text(Text { + formula: None, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 0.25, @@ -47,6 +48,7 @@ fn sample() -> Drawing { &Space::Model, c("0"), EntityKind::MText(MText { + formula: None, insert: Vec3::new(5.0, 5.0, 0.0), height: 0.2, width: 3.0, @@ -258,6 +260,7 @@ fn block_definition_properties_and_constant_attdefs_roundtrip() { let mut b = Block::new("Title"); (b.description, b.units, b.explodable) = ("Drawing title block".into(), 4, false); let text = Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 2.5, @@ -1433,6 +1436,7 @@ const INTL: &str = "图号 İø Ø 😀"; fn intl_text(value: &str) -> Text { Text { + formula: None, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 2.5, @@ -1457,6 +1461,7 @@ fn intl_sample() -> Drawing { &Space::Model, on.clone(), EntityKind::MText(MText { + formula: None, insert: Vec3::new(5.0, 5.0, 0.0), height: 2.5, width: 30.0, @@ -1698,6 +1703,7 @@ fn dwg_roundtrip_keeps_extension_data() { fn mleader_is_written_as_multileader() { let mut d = Drawing::new_metric(); let text = cadcraft_doc::MText { + formula: None, insert: Vec3::new(12.0, 5.0, 0.0), height: 2.5, width: 0.0, @@ -1732,6 +1738,7 @@ fn mleader_is_written_as_multileader() { fn attdef_prompt_survives_dxf_roundtrip() { let mut d = Drawing::new_metric(); let text = Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 2.0, diff --git a/crates/io/tests/it/acad_interop.rs b/crates/io/tests/it/acad_interop.rs index 387f233344..0bbecaf761 100644 --- a/crates/io/tests/it/acad_interop.rs +++ b/crates/io/tests/it/acad_interop.rs @@ -21,6 +21,7 @@ fn tags(dxf: &str) -> Vec<(i32, String)> { fn text(value: &str, at: Vec3, h: HAlign, v: VAlign) -> EntityKind { EntityKind::Text(Text { + formula: None, insert: at, align_pt: Some(at), height: 5.0, @@ -207,6 +208,7 @@ fn justified_text_made_here_writes_its_baseline_start_for_every_justification() let at = Vec3::new(100.0, 400.0 - 22.0 * i as f64, 0.0); let left = h == Left && v == Baseline; let t = Text { + formula: None, insert: at, align_pt: if left { None } else { Some(at) }, height: 5.0, diff --git a/crates/io/tests/it/annotative_roundtrip.rs b/crates/io/tests/it/annotative_roundtrip.rs index b7fb62384e..f98b9a95be 100644 --- a/crates/io/tests/it/annotative_roundtrip.rs +++ b/crates/io/tests/it/annotative_roundtrip.rs @@ -10,6 +10,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn text(value: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 2.5, diff --git a/crates/io/tests/it/attrib_modes.rs b/crates/io/tests/it/attrib_modes.rs index 625ead9392..7d779b1fb6 100644 --- a/crates/io/tests/it/attrib_modes.rs +++ b/crates/io/tests/it/attrib_modes.rs @@ -9,6 +9,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn attrib(tag: &str, modes: AttribModes) -> Attrib { let text = Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 1.0, diff --git a/crates/io/tests/it/attrib_props.rs b/crates/io/tests/it/attrib_props.rs index 32dac11012..d5ff7c59a3 100644 --- a/crates/io/tests/it/attrib_props.rs +++ b/crates/io/tests/it/attrib_props.rs @@ -10,6 +10,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn text(x: f64, value: &str) -> Text { Text { + formula: None, insert: Vec3::new(x, 0.0, 0.0), align_pt: None, height: 1.0, diff --git a/crates/io/tests/it/dxf_versions.rs b/crates/io/tests/it/dxf_versions.rs index 3fc2f1c73c..98433c6ed1 100644 --- a/crates/io/tests/it/dxf_versions.rs +++ b/crates/io/tests/it/dxf_versions.rs @@ -9,6 +9,7 @@ const INTL: &str = "图号 Café Ø 😀"; fn text(value: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 2.5, diff --git a/crates/io/tests/it/entity_props_roundtrip.rs b/crates/io/tests/it/entity_props_roundtrip.rs index d86d0b4b86..587468b847 100644 --- a/crates/io/tests/it/entity_props_roundtrip.rs +++ b/crates/io/tests/it/entity_props_roundtrip.rs @@ -29,6 +29,7 @@ fn thickness_roundtrips_on_every_entity_that_has_one() { let mut d = Drawing::new_metric(); let p = |x, y| Vec3::new(x, y, 0.0); let text = Text { + formula: None, insert: p(0.0, 0.0), align_pt: None, height: 2.5, diff --git a/crates/io/tests/it/followups_626.rs b/crates/io/tests/it/followups_626.rs index a44a27eb43..e435eaf3ce 100644 --- a/crates/io/tests/it/followups_626.rs +++ b/crates/io/tests/it/followups_626.rs @@ -35,6 +35,7 @@ fn mleader_drawing() -> (Drawing, MLeader) { landing: Vec3::new(5.0, 4.0, 0.0), dogleg: 0.75, text: Some(MText { + formula: None, insert: Vec3::new(5.9, 4.0, 0.0), height: 0.4, width: 6.0, @@ -162,6 +163,7 @@ fn code_page_is_kept_before_2007() { &Space::Model, Common::default(), EntityKind::Text(Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 2.5, diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 51e7f1965e..a88ff5f4e5 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -62,6 +62,7 @@ mod svg_arc_budget; mod svg_tiny_extents; mod table_cellstyle_roundtrip; mod tables_objects_roundtrip; +mod text_formula_roundtrip; mod text_left_justify; mod tolerance_roundtrip; mod user_lin_pat_roundtrip; diff --git a/crates/io/tests/it/mleader_roundtrip.rs b/crates/io/tests/it/mleader_roundtrip.rs index 4cb1bff34c..30d589de9c 100644 --- a/crates/io/tests/it/mleader_roundtrip.rs +++ b/crates/io/tests/it/mleader_roundtrip.rs @@ -22,6 +22,7 @@ fn text_mleader() -> MLeader { landing: Vec3::new(5.0, 4.0, 0.0), dogleg: 0.75, text: Some(MText { + formula: None, insert: Vec3::new(5.9, 4.0, 0.0), height: 0.4, width: 6.0, @@ -78,6 +79,7 @@ fn spline_leader_with_block_content_and_attributes() { let mut blk = Block::new("BUBBLE"); blk.entities.push(Entity::new(Handle(0x200), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 }))); let tag_text = Text { + formula: None, insert: Vec3::new(-0.2, -0.1, 0.0), align_pt: None, height: 0.25, diff --git a/crates/io/tests/it/mtext_columns_roundtrip.rs b/crates/io/tests/it/mtext_columns_roundtrip.rs index 7db9ed685b..4eb93f2124 100644 --- a/crates/io/tests/it/mtext_columns_roundtrip.rs +++ b/crates/io/tests/it/mtext_columns_roundtrip.rs @@ -7,6 +7,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn mtext(contents: &str, rotation: f64, columns: Option) -> MText { MText { + formula: None, insert: Vec3::new(1.0, 2.0, 0.0), height: 0.5, width: 6.0, diff --git a/crates/io/tests/it/mtext_embedded_object.rs b/crates/io/tests/it/mtext_embedded_object.rs index 4bd95cb778..421ef8ebde 100644 --- a/crates/io/tests/it/mtext_embedded_object.rs +++ b/crates/io/tests/it/mtext_embedded_object.rs @@ -12,6 +12,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn with_embedded_object(rotation: f64, dir: (f64, f64)) -> String { let mut d = Drawing::new_metric(); let t = MText { + formula: None, insert: Vec3::new(30.0, 17.0, 0.0), height: 0.5, width: 6.0, diff --git a/crates/io/tests/it/mtext_line_spacing.rs b/crates/io/tests/it/mtext_line_spacing.rs index 8a030cbc7f..c67db6e23f 100644 --- a/crates/io/tests/it/mtext_line_spacing.rs +++ b/crates/io/tests/it/mtext_line_spacing.rs @@ -8,6 +8,7 @@ fn line_spacing_style_roundtrips() { for exact in [false, true] { let mut d = Drawing::new_metric(); let t = MText { + formula: None, insert: Vec3::new(1.0, 2.0, 0.0), height: 2.5, width: 40.0, diff --git a/crates/io/tests/it/text_formula_roundtrip.rs b/crates/io/tests/it/text_formula_roundtrip.rs new file mode 100644 index 0000000000..86ab5d4ade --- /dev/null +++ b/crates/io/tests/it/text_formula_roundtrip.rs @@ -0,0 +1,44 @@ +//! A text's formula (`=...`) round-trips through DXF as CADCRAFTFORMULA extended data, a long +//! Hebrew one included (cut into 250-byte strings between letters). + +use cadcraft_doc::{Common, Drawing, EntityKind, HAlign, MText, Space, Text, VAlign}; +use cadcraft_geom::Vec3; + +#[test] +fn text_and_mtext_formulas_roundtrip() { + let mut d = Drawing::new_metric(); + let long = format!("=\"{}\"", "שלום ".repeat(120)); + let t = Text { + insert: Vec3::new(1.0, 2.0, 0.0), + align_pt: None, + height: 2.5, + value: "2".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + formula: Some("=1+1".into()), + }; + d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); + let m = MText { + formula: Some(long.clone()), + insert: Vec3::new(0.0, 10.0, 0.0), + height: 2.5, + width: 40.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "x".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(m)).unwrap(); + let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let kinds: Vec = back.model.iter().map(|e| e.kind.clone()).collect(); + assert!(kinds.iter().any(|k| matches!(k, EntityKind::Text(t) if t.formula.as_deref() == Some("=1+1")))); + assert!(kinds.iter().any(|k| matches!(k, EntityKind::MText(m) if m.formula.as_deref() == Some(long.as_str())))); +} diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index baba82f9da..abf34b3226 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -167,6 +167,7 @@ fn style(d: &mut Drawing, name: &str, font: &str) { fn text(d: &mut Drawing, space: &Space, style: &str, at: (f64, f64), value: &str, (rotation, width_factor, oblique): (f64, f64, f64)) { let t = Text { + formula: None, insert: Vec3::new(at.0, at.1, 0.0), align_pt: None, height: 10.0, @@ -368,6 +369,7 @@ fn hostile_text_never_panics() { [("A".repeat(5000), 10.0, 0.0), ("AB".into(), 1e300, 0.0), ("AB".into(), 1e-300, 1e300), ("\u{0}A\u{FFFF}B".into(), 5.0, f64::NAN)] { let t = Text { + formula: None, insert: Vec3::new(0.0, 0.0, 0.0), align_pt: None, height: h, diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index d62af23b9d..5a7578907d 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,6 +19,9 @@ lyon_tessellation = { workspace = true } # Display lists of large drawings are built on all cores (not on the web, which has no threads). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } +# The local date and time for date formulas and fields in text (MIT OR Unlicense); the web build +# uses UTC. +jiff = { version = "0.2", default-features = false, features = ["std", "tz-system", "tzdb-bundle-platform", "tzdb-zoneinfo"] } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index a2f0021a2f..c86576a34b 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -18,7 +18,7 @@ mod text; use arrowheads::tick; pub use arrowheads::{ArrowGeom, Arrowhead, arrow, arrowhead}; pub use text::{DimText, format_linear_value}; -use text::{apply_override, inspected, linear_text}; +use text::{apply_override, inspected, linear_text, shown_value}; /// Most DIMBREAK gaps drawn per dimension. const MAX_BREAKS: usize = 1000; @@ -602,7 +602,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let azin = (st.angular_zero_suppression & 3) * 4; let txt = format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator); // DIMPOST is a linear-dimension prefix/suffix; angles have their own format only. - g.mtext = inspected(apply_override(&txt, d), d); + g.mtext = inspected(apply_override(&txt, d, Some(shown_value(sweep.to_degrees(), st.angular_decimals))), d); let mut pts = Vec::new(); arc.tessellate(r * 1e-3, &mut pts); g.dim(pts); diff --git a/crates/render/src/dim/text.rs b/crates/render/src/dim/text.rs index fb3d6eda75..18672dbb3a 100644 --- a/crates/render/src/dim/text.rs +++ b/crates/render/src/dim/text.rs @@ -49,7 +49,15 @@ pub(super) fn linear_text(meas: f64, d: &Dimension, st: &DimStyle, prefix: &str) let alt = format_linear(v * st.alt_factor, &af).1; s += &format!(" [{}]", post(&st.alt_post, &alt)); } - inspected(apply_override(&s, d), d) + inspected(apply_override(&s, d, Some(shown_value(v, nf.decimals))), d) +} + +/// A measurement rounded as the dimension shows it (`decimals` places), for a formula's `<>`: +/// `=<>/2` of a 1250 dimension is 625, not 624.99995. +pub(super) fn shown_value(v: f64, decimals: u8) -> f64 { + let k = 10f64.powi(i32::from(decimals.min(8))); + let r = (v * k).round() / k; + if r.is_finite() { r } else { v } } /// DIMINSPECT: the label and the rate either side of the value, two spaces apart. @@ -78,8 +86,28 @@ fn post(template: &str, meas: &str) -> String { } } +/// The first number in a formatted measurement (`R12.5` → 12.5, `1 250,5` → 1250.5). +fn measured_number(base: &str) -> Option { + let s: String = base + .chars() + .skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.') + .take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')) + .collect(); + s.replace(' ', "").replace(',', ".").parse().ok() +} + /// Apply dimension text overrides: empty uses the base, whitespace suppresses text, and other text substitutes it. -pub(super) fn apply_override(base: &str, d: &Dimension) -> String { +/// `value`: the measurement as a number (in the dimension's units, degrees for an angle), which a +/// formula's `<>` stands for; read back from the formatted text when not given. +pub(super) fn apply_override(base: &str, d: &Dimension, value: Option) -> String { + // A formula: worked out with `<>` as the measurement. + if let Some(f) = d.marks.formula.as_deref().filter(|f| crate::textformula::is_formula(f)) { + let measured = value.filter(|v| v.is_finite()).or_else(|| measured_number(base)); + let env = crate::textformula::Env { measured, now: crate::textformula::local_now(), ..Default::default() }; + if let Some(v) = crate::textformula::evaluate(f, &env) { + return v; + } + } if d.text.is_empty() { base.to_string() } else if d.text.trim().is_empty() { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5b9dc83a1d..2460d331d0 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -21,6 +21,7 @@ mod plotstyle; mod point; pub mod raster; mod text; +pub mod textformula; mod tolerance; pub mod units; mod wide; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index fc4b99156f..0890511c02 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -48,6 +48,7 @@ fn text_produces_strokes() { &Space::Model, Common::default(), EntityKind::Text(cadcraft_doc::Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 1.0, @@ -255,6 +256,7 @@ fn text_doc(style_font: &str, value: &str) -> Drawing { &Space::Model, Common::default(), EntityKind::Text(cadcraft_doc::Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 1.0, @@ -329,6 +331,7 @@ fn truetype_mtext_and_dimension_text() { &Space::Model, Common::default(), EntityKind::MText(cadcraft_doc::MText { + formula: None, insert: Vec3::ZERO, height: 1.0, width: 0.0, @@ -764,6 +767,7 @@ fn attrib(tag: &str) -> cadcraft_doc::Attrib { cadcraft_doc::Attrib { tag: tag.into(), text: cadcraft_doc::Text { + formula: None, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 1.0, @@ -861,6 +865,7 @@ fn attributes_follow_the_reference_layer_and_have_no_definition() { fn mtext_exact_spacing_ignores_taller_lines() { // #711: a doubled middle line pushes the next baseline down with At least, not with Exactly. let mtext = |contents: &str, line_spacing: f64, line_spacing_exact: bool| cadcraft_doc::MText { + formula: None, insert: Vec3::ZERO, height: 1.0, width: 10.0, diff --git a/crates/render/src/textformula.rs b/crates/render/src/textformula.rs new file mode 100644 index 0000000000..9bf6d62d00 --- /dev/null +++ b/crates/render/src/textformula.rs @@ -0,0 +1,913 @@ +//! Formulas in text, as in a spreadsheet (the evaluator; the engine applies it to drawings): a text whose value starts with `=` shows the result +//! of the formula (`=2400-2*18`, `=TEXT(TODAY(),"dd.mm.yyyy")`, `=ROUND(PI()*125^2/1000000,3)`). +//! The formula is kept with the text ([`cadcraft_doc::Text::formula`]) and worked out again +//! when the drawing is opened (dates follow the computer's clock) and when it is edited. +//! +//! AutoCAD fields read from drawings (`%<\AcVar date \f "dd.MM.yyyy">%`) are worked out the same +//! way when CADCraft knows them (dates, the file name); others keep the value AutoCAD saved. +//! +//! The functions are listed in [`FUNCTIONS`] (name, arguments, description), which the editor's +//! completion list and Help show. + +/// Longest formula worked out. +const MAX_LEN: usize = 2000; +/// Deepest nesting. +const MAX_DEPTH: usize = 40; +/// Most arguments of one function. +const MAX_ARGS: usize = 255; + +/// The functions: (name, arguments, description). Shown by completion and Help. +pub const FUNCTIONS: &[(&str, &str, &str)] = &[ + ("ABS", "number", "The number without its sign."), + ("ACOS", "number", "Arccosine, in radians."), + ("AND", "logical1, logical2, ...", "TRUE when all arguments are true."), + ("ASIN", "number", "Arcsine, in radians."), + ("ATAN", "number", "Arctangent, in radians."), + ("AVERAGE", "number1, number2, ...", "The average of the numbers."), + ("CONCAT", "text1, text2, ...", "Joins texts (as the & operator)."), + ("COS", "angle", "Cosine of an angle in radians."), + ("DATE", "year, month, day", "A date."), + ("DAY", "date", "The day of the month of a date."), + ("DEGREES", "angle", "Radians to degrees."), + ("EXP", "number", "e raised to a power."), + ("FILENAME", "", "The drawing's file name."), + ("FIXED", "number, decimals", "A number as text with that many decimals."), + ("HOUR", "time", "The hour of a time."), + ("IF", "condition, value_if_true, value_if_false", "One of two values, by a condition."), + ("INT", "number", "Rounds down to an integer."), + ("LEFT", "text, count", "The first characters of a text."), + ("LEN", "text", "The number of characters of a text."), + ("LN", "number", "Natural logarithm."), + ("LOG10", "number", "Base-10 logarithm."), + ("LOWER", "text", "A text in lower case."), + ("MAX", "number1, number2, ...", "The largest number."), + ("MID", "text, start, count", "Characters from the middle of a text (start = 1 for the first)."), + ("MIN", "number1, number2, ...", "The smallest number."), + ("MINUTE", "time", "The minutes of a time."), + ("MOD", "number, divisor", "The remainder of a division."), + ("MONTH", "date", "The month of a date (1 to 12)."), + ("NOT", "logical", "The opposite of a logical value."), + ("NOW", "", "The current date and time (worked out again when the drawing is opened)."), + ("OR", "logical1, logical2, ...", "TRUE when any argument is true."), + ("PI", "", "The number π."), + ("POWER", "number, power", "A number raised to a power (as ^)."), + ("RADIANS", "angle", "Degrees to radians."), + ("RIGHT", "text, count", "The last characters of a text."), + ("ROUND", "number, decimals", "Rounds to that many decimals."), + ("ROUNDDOWN", "number, decimals", "Rounds toward zero."), + ("ROUNDUP", "number, decimals", "Rounds away from zero."), + ("SHEET", "", "The name of the current layout (\"Model\" in model space)."), + ("SIN", "angle", "Sine of an angle in radians."), + ("SQRT", "number", "Square root."), + ("SUM", "number1, number2, ...", "Adds the numbers."), + ("TAN", "angle", "Tangent of an angle in radians."), + ("TEXT", "value, format", "A value as text in a format: \"0.00\", \"#,##0\", \"0%\", \"dd.mm.yyyy\", \"hh:mm\"..."), + ("TODAY", "", "Today's date (worked out again when the drawing is opened)."), + ("TRIM", "text", "A text without spaces at its ends and double spaces."), + ("UPPER", "text", "A text in capitals."), + ("YEAR", "date", "The year of a date."), +]; + +/// What a formula can refer to: the time, the file and the layout. +#[derive(Clone, Debug, PartialEq)] +pub struct Env { + /// Local date and time: year, month, day, hour, minute, second. + pub now: (i32, u32, u32, u32, u32, u32), + pub file: String, + pub sheet: String, + /// A dimension's measurement, which `<>` stands for in its formula. + pub measured: Option, +} + +impl Default for Env { + fn default() -> Self { + Env { now: (2000, 1, 1, 0, 0, 0), file: String::new(), sheet: "Model".into(), measured: None } + } +} + +/// The local date and time now (UTC where the time zone is unknown). +pub fn local_now() -> (i32, u32, u32, u32, u32, u32) { + #[cfg(not(target_arch = "wasm32"))] + { + let z = jiff::Zoned::now(); + let clamp = |v: i8| u32::try_from(v).unwrap_or(0); + (i32::from(z.year()), clamp(z.month()), clamp(z.day()), clamp(z.hour()), clamp(z.minute()), clamp(z.second())) + } + #[cfg(target_arch = "wasm32")] + { + (2000, 1, 1, 0, 0, 0) + } +} + +/// Whether `text` is a formula: one line starting with `=` (after spaces). +pub fn is_formula(text: &str) -> bool { + let t = text.trim(); + t.starts_with('=') && t.len() > 1 && !t.contains(['\n', '\r']) +} + +/// Whether `text` holds AutoCAD field codes. +pub fn has_fields(text: &str) -> bool { + text.contains("%<\\") +} + +/// Work out a formula (`=...`) or the fields of a field template: the text to show, or `None` +/// for a field CADCraft doesn't know (the saved value stays). +pub fn evaluate(formula: &str, env: &Env) -> Option { + if is_formula(formula) { + return Some(match eval(formula.trim_start().trim_start_matches('='), env) { + Ok(v) => v.show(), + Err(e) => e.to_string(), + }); + } + if has_fields(formula) { + return fields(formula, env); + } + None +} + +// ---------- values ---------- + +#[derive(Clone, Debug, PartialEq)] +enum Val { + Num(f64), + /// A date and time as a serial number (days since 30 December 1899, as spreadsheets). + Date(f64), + Text(String), + Bool(bool), +} + +/// Formula errors, shown as spreadsheets show them. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Err { + /// An unknown function or name. + Name, + /// A wrong kind of value. + Value, + Div0, + /// A number out of range (square root of -1...). + Num, + /// The formula can't be read. + Syntax, +} + +impl std::fmt::Display for Err { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Err::Name => "#NAME?", + Err::Value => "#VALUE!", + Err::Div0 => "#DIV/0!", + Err::Num => "#NUM!", + Err::Syntax => "#ERROR!", + }) + } +} + +type R = std::result::Result; + +impl Val { + fn num(&self) -> std::result::Result { + match self { + Val::Num(v) | Val::Date(v) => Ok(*v), + Val::Bool(b) => Ok(f64::from(u8::from(*b))), + Val::Text(t) => t.trim().replace(',', ".").parse::().map_err(|_| Err::Value), + } + } + fn text(&self) -> String { + self.show() + } + fn truth(&self) -> std::result::Result { + match self { + Val::Bool(b) => Ok(*b), + Val::Text(t) if t.eq_ignore_ascii_case("true") => Ok(true), + Val::Text(t) if t.eq_ignore_ascii_case("false") => Ok(false), + v => Ok(v.num()? != 0.0), + } + } + /// As the text shows it: numbers without trailing zeros (at most 10 decimals), dates as + /// dd.mm.yyyy (with the time when it has one), TRUE/FALSE. + fn show(&self) -> String { + match self { + Val::Num(v) => general(*v), + Val::Date(d) => { + if d.fract().abs() < 1e-9 { + format_date(*d, "dd.mm.yyyy") + } else { + format_date(*d, "dd.mm.yyyy hh:mm") + } + } + Val::Text(t) => t.clone(), + Val::Bool(b) => if *b { "TRUE" } else { "FALSE" }.into(), + } + } +} + +/// A number with at most 10 decimals, trailing zeros dropped. +fn general(v: f64) -> String { + if !v.is_finite() { + return Err::Num.to_string(); + } + if v.abs() >= 1e15 || (v != 0.0 && v.abs() < 1e-10) { + return format!("{v:e}"); + } + let s = format!("{v:.10}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +// ---------- dates ---------- + +/// Days from 1970-01-01 of a civil date (proleptic Gregorian). +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn civil_from_days(z: i64) -> (i64, i64, i64) { + let z = z + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +/// The spreadsheet serial of 1970-01-01. +const EPOCH_SERIAL: i64 = 25_569; + +fn serial(y: i64, m: i64, d: i64) -> f64 { + // Months beyond 1..12 roll into the next or previous years, as spreadsheets do. + let (y, m) = (y + (m - 1).div_euclid(12), (m - 1).rem_euclid(12) + 1); + (days_from_civil(y, m, 1) + d - 1 + EPOCH_SERIAL) as f64 +} + +/// (year, month, day, hour, minute, second) of a serial. +fn parts(s: f64) -> (i64, i64, i64, i64, i64, i64) { + // About ±8000 years around 1900: the calendar arithmetic stays far from overflowing (a + // file's formula can hold any number, `=YEAR(1E300)`). + let s = if s.is_finite() { s.clamp(-3_000_000.0, 3_000_000.0) } else { 0.0 }; + let days = s.floor(); + let secs = ((s - days) * 86_400.0).round() as i64; + let (y, m, d) = civil_from_days(days as i64 - EPOCH_SERIAL); + (y, m, d, secs / 3600 % 24, secs / 60 % 60, secs % 60) +} + +const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +/// A date in a spreadsheet date format: d dd ddd? m mm mmm mmmm yy yyyy h hh mm (minutes after +/// h) ss; other characters as they are. +fn format_date(s: f64, fmt: &str) -> String { + let (y, mo, d, h, mi, se) = parts(s); + let chars: Vec = fmt.chars().collect(); + let mut out = String::new(); + let mut i = 0; + let mut after_hour = false; + while let Some(&c) = chars.get(i) { + let run = chars.get(i..).unwrap_or_default().iter().take_while(|x| x.eq_ignore_ascii_case(&c)).count(); + match c.to_ascii_lowercase() { + 'y' => { + out += &if run <= 2 { format!("{:02}", y.rem_euclid(100)) } else { format!("{y:04}") }; + after_hour = false; + } + 'm' if after_hour && run <= 2 => { + out += &if run == 1 { mi.to_string() } else { format!("{mi:02}") }; + after_hour = false; + } + 'm' => { + let name = MONTHS.get(usize::try_from(mo - 1).unwrap_or(0)).copied().unwrap_or(""); + out += &match run { + 1 => mo.to_string(), + 2 => format!("{mo:02}"), + 3 => name.chars().take(3).collect(), + _ => name.into(), + }; + } + 'd' => { + out += &if run == 1 { d.to_string() } else { format!("{d:02}") }; + after_hour = false; + } + 'h' => { + out += &if run == 1 { h.to_string() } else { format!("{h:02}") }; + after_hour = true; + } + 's' => { + out += &if run == 1 { se.to_string() } else { format!("{se:02}") }; + } + _ => { + out.extend(std::iter::repeat_n(c, run)); + } + } + i += run; + } + out +} + +/// A number in a spreadsheet number format: `0`, `0.00`, `#,##0.00`, `0%`, `0.0E+0`-less. +/// Text before and after the digits stays (`"L=" 0.0` → `L=12.5`, quotes dropped). +fn format_number(v: f64, fmt: &str) -> String { + let percent = fmt.contains('%'); + let v = if percent { v * 100.0 } else { v }; + let start = fmt.find(['0', '#']); + let end = fmt.rfind(['0', '#']).map(|e| e + 1); + let (Some(a), Some(b)) = (start, end) else { return fmt.replace('"', "") }; + let core = fmt.get(a..b).unwrap_or("0"); + let decimals = core.split_once('.').map_or(0, |(_, f)| f.chars().filter(|c| *c == '0' || *c == '#').count()); + let grouped = core.split_once('.').map_or(core, |(i, _)| i).contains(','); + let mut s = format!("{:.*}", decimals.min(15), v.abs()); + if grouped { + let (int, frac) = s.split_once('.').map_or((s.clone(), String::new()), |(i, f)| (i.to_string(), format!(".{f}"))); + let mut g = String::new(); + for (k, ch) in int.chars().enumerate() { + if k > 0 && (int.len() - k) % 3 == 0 { + g.push(','); + } + g.push(ch); + } + s = g + &frac; + } + let sign = if v < 0.0 && s.chars().any(|c| c.is_ascii_digit() && c != '0') { "-" } else { "" }; + let pre = fmt.get(..a).unwrap_or("").replace('"', ""); + let post = fmt.get(b..).unwrap_or("").replace('"', ""); + format!("{pre}{sign}{s}{post}") +} + +fn looks_like_date_format(f: &str) -> bool { + let l = f.to_ascii_lowercase(); + l.contains('y') || l.contains('d') || l.contains("mm") && !l.contains('0') || l.contains('h') +} + +// ---------- parsing and evaluation ---------- + +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Num(f64), + Str(String), + Name(String), + Op(&'static str), + LParen, + RParen, + Comma, +} + +fn lex(s: &str) -> std::result::Result, Err> { + let c: Vec = s.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + while let Some(&ch) = c.get(i) { + match ch { + ' ' | '\t' => i += 1, + '0'..='9' | '.' => { + let st = i; + while c.get(i).is_some_and(|x| x.is_ascii_digit() || *x == '.') { + i += 1; + } + if c.get(i).is_some_and(|x| *x == 'e' || *x == 'E') && c.get(i + 1).is_some_and(|x| x.is_ascii_digit() || *x == '-' || *x == '+') { + i += 2; + while c.get(i).is_some_and(char::is_ascii_digit) { + i += 1; + } + } + let t: String = c.get(st..i).unwrap_or_default().iter().collect(); + out.push(Tok::Num(t.parse().map_err(|_| Err::Syntax)?)); + } + '"' => { + i += 1; + let mut t = String::new(); + loop { + match c.get(i) { + None => return Err(Err::Syntax), + Some('"') if c.get(i + 1) == Some(&'"') => { + t.push('"'); + i += 2; + } + Some('"') => { + i += 1; + break; + } + Some(x) => { + t.push(*x); + i += 1; + } + } + } + out.push(Tok::Str(t)); + } + '(' => { + out.push(Tok::LParen); + i += 1; + } + ')' => { + out.push(Tok::RParen); + i += 1; + } + // `;` separates arguments too (spreadsheets in languages with a decimal comma). + ',' | ';' => { + out.push(Tok::Comma); + i += 1; + } + '<' | '>' => { + let two: String = c.get(i..i + 2).unwrap_or_default().iter().collect(); + let op = match two.as_str() { + "<=" => "<=", + ">=" => ">=", + "<>" => "<>", + _ if ch == '<' => "<", + _ => ">", + }; + i += op.len(); + out.push(Tok::Op(op)); + } + '+' | '-' | '*' | '/' | '^' | '&' | '=' | '%' => { + out.push(Tok::Op(match ch { + '+' => "+", + '-' => "-", + '*' => "*", + '/' => "/", + '^' => "^", + '&' => "&", + '=' => "=", + _ => "%", + })); + i += 1; + } + x if x.is_alphabetic() || x == '_' => { + let st = i; + while c.get(i).is_some_and(|y| y.is_alphanumeric() || *y == '_' || *y == '.') { + i += 1; + } + out.push(Tok::Name(c.get(st..i).unwrap_or_default().iter().collect::().to_ascii_uppercase())); + } + _ => return Err(Err::Syntax), + } + if out.len() > MAX_LEN { + return Err(Err::Syntax); + } + } + Ok(out) +} + +struct P<'a> { + t: Vec, + i: usize, + depth: usize, + env: &'a Env, +} + +fn eval(src: &str, env: &Env) -> R { + if src.len() > MAX_LEN { + return Err(Err::Syntax); + } + let mut p = P { t: lex(src)?, i: 0, depth: 0, env }; + let v = p.compare()?; + if p.i < p.t.len() { + return Err(Err::Syntax); + } + Ok(v) +} + +impl P<'_> { + fn peek(&self) -> Option<&Tok> { + self.t.get(self.i) + } + fn is_op(&self, ops: &[&str]) -> Option<&'static str> { + match self.peek() { + Some(Tok::Op(o)) if ops.contains(o) => Some(o), + _ => None, + } + } + fn compare(&mut self) -> R { + let a = self.concat()?; + if let Some(op) = self.is_op(&["=", "<>", "<", ">", "<=", ">="]) { + self.i += 1; + let b = self.concat()?; + let ord = match (&a, &b) { + (Val::Text(x), Val::Text(y)) => x.to_lowercase().cmp(&y.to_lowercase()), + _ => a.num()?.partial_cmp(&b.num()?).ok_or(Err::Num)?, + }; + use std::cmp::Ordering::*; + return Ok(Val::Bool(match op { + "=" => ord == Equal, + "<>" => ord != Equal, + "<" => ord == Less, + ">" => ord == Greater, + "<=" => ord != Greater, + _ => ord != Less, + })); + } + Ok(a) + } + fn concat(&mut self) -> R { + let mut a = self.sum()?; + while self.is_op(&["&"]).is_some() { + self.i += 1; + let b = self.sum()?; + a = Val::Text(a.text() + &b.text()); + } + Ok(a) + } + fn sum(&mut self) -> R { + let mut a = self.product()?; + while let Some(op) = self.is_op(&["+", "-"]) { + self.i += 1; + let b = self.product()?; + let v = if op == "+" { a.num()? + b.num()? } else { a.num()? - b.num()? }; + // A date plus or minus days is a date; the difference of two dates is a number. + a = match (&a, &b) { + (Val::Date(_), Val::Date(_)) => Val::Num(v), + (Val::Date(_), _) | (_, Val::Date(_)) => Val::Date(v), + _ => Val::Num(v), + }; + } + Ok(a) + } + fn product(&mut self) -> R { + let mut a = self.power()?; + while let Some(op) = self.is_op(&["*", "/"]) { + self.i += 1; + let b = self.power()?; + let (x, y) = (a.num()?, b.num()?); + a = Val::Num(if op == "*" { + x * y + } else { + if y == 0.0 { + return Err(Err::Div0); + } + x / y + }); + } + Ok(a) + } + fn power(&mut self) -> R { + let a = self.unary()?; + if self.is_op(&["^"]).is_some() { + self.i += 1; + let b = self.power()?; + let v = a.num()?.powf(b.num()?); + return if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; + } + Ok(a) + } + fn unary(&mut self) -> R { + if let Some(op) = self.is_op(&["-", "+"]) { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(Err::Syntax); + } + self.i += 1; + let v = self.unary()?; + self.depth -= 1; + return Ok(Val::Num(if op == "-" { -v.num()? } else { v.num()? })); + } + let mut v = self.atom()?; + while self.is_op(&["%"]).is_some() { + self.i += 1; + v = Val::Num(v.num()? / 100.0); + } + Ok(v) + } + /// Where the argument starting here ends: the next comma or closing parenthesis outside + /// any parentheses it opens (`None`: the formula ends first). + fn arg_end(&self) -> Option { + let mut level = 0usize; + for (k, t) in self.t.iter().enumerate().skip(self.i) { + match t { + Tok::LParen => level += 1, + Tok::RParen if level == 0 => return Some(k), + Tok::RParen => level -= 1, + Tok::Comma if level == 0 => return Some(k), + _ => {} + } + } + None + } + fn atom(&mut self) -> R { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(Err::Syntax); + } + let tok = self.peek().cloned(); + self.i += 1; + let r = match tok { + Some(Tok::Num(v)) => Ok(Val::Num(v)), + Some(Tok::Str(s)) => Ok(Val::Text(s)), + Some(Tok::LParen) => { + let v = self.compare()?; + if self.peek() != Some(&Tok::RParen) { + return Err(Err::Syntax); + } + self.i += 1; + Ok(v) + } + // In a dimension's formula, `<>` is its measurement. + Some(Tok::Op("<>")) if self.env.measured.is_some() => Ok(Val::Num(self.env.measured.unwrap_or(0.0))), + Some(Tok::Name(n)) if n == "TRUE" => Ok(Val::Bool(true)), + Some(Tok::Name(n)) if n == "FALSE" => Ok(Val::Bool(false)), + Some(Tok::Name(n)) => { + if self.peek() != Some(&Tok::LParen) { + return Err(Err::Name); + } + self.i += 1; + // Each argument's value or the error working it out gave: IF uses only the branch + // it picks, so an error in the other one (`=IF(TRUE;1;1/0)`) doesn't count. + let mut args: Vec = Vec::new(); + if self.peek() != Some(&Tok::RParen) { + loop { + let end = self.arg_end().ok_or(Err::Syntax)?; + let depth = self.depth; + let v = self.compare(); + self.depth = depth; + match v { + Err(Err::Syntax) => return Err(Err::Syntax), + Ok(_) if self.i != end => return Err(Err::Syntax), + _ => {} + } + self.i = end; + args.push(v); + if args.len() > MAX_ARGS { + return Err(Err::Value); + } + match self.peek() { + Some(Tok::Comma) => self.i += 1, + Some(Tok::RParen) => break, + _ => return Err(Err::Syntax), + } + } + } + self.i += 1; + if n == "IF" { + let mut it = args.into_iter(); + let c = it.next().unwrap_or(Err(Err::Value))?.truth()?; + let (yes, no) = (it.next(), it.next()); + if c { yes.unwrap_or(Ok(Val::Bool(true))) } else { no.unwrap_or(Ok(Val::Bool(false))) } + } else { + let args: Vec = args.into_iter().collect::>()?; + call(&n, &args, self.env) + } + } + _ => Err(Err::Syntax), + }; + self.depth -= 1; + r + } +} + +fn round_to(x: f64, n: f64, how: fn(f64) -> f64) -> f64 { + let k = 10f64.powi(n.clamp(-15.0, 15.0) as i32); + how(x * k) / k +} + +fn arg(a: &[Val], i: usize) -> std::result::Result<&Val, Err> { + a.get(i).ok_or(Err::Value) +} + +fn nums(a: &[Val]) -> std::result::Result, Err> { + a.iter().map(Val::num).collect() +} + +fn call(name: &str, a: &[Val], env: &Env) -> R { + let n0 = |a: &[Val]| arg(a, 0).and_then(Val::num); + let n1 = |a: &[Val]| arg(a, 1).and_then(Val::num); + let checked = |v: f64| if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; + let chars = |v: &Val| v.text().chars().collect::>(); + let count = |v: f64| if v.is_finite() { usize::try_from(v.clamp(0.0, 1e6) as i64).unwrap_or(0) } else { 0 }; + let (y, mo, d, h, mi, s) = env.now; + let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + match name { + "ABS" => Ok(Val::Num(n0(a)?.abs())), + "ACOS" => checked(n0(a)?.acos()), + "ASIN" => checked(n0(a)?.asin()), + "ATAN" => Ok(Val::Num(n0(a)?.atan())), + "AND" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().all(|b| *b))), + "OR" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().any(|b| *b))), + "NOT" => Ok(Val::Bool(!arg(a, 0)?.truth()?)), + "AVERAGE" => { + let v = nums(a)?; + if v.is_empty() { Err(Err::Div0) } else { Ok(Val::Num(v.iter().sum::() / v.len() as f64)) } + } + "SUM" => Ok(Val::Num(nums(a)?.iter().sum())), + "MIN" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::INFINITY, f64::min)).clone()) + .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "MAX" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::NEG_INFINITY, f64::max))) + .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "CONCAT" => Ok(Val::Text(a.iter().map(Val::text).collect())), + "COS" => Ok(Val::Num(n0(a)?.cos())), + "SIN" => Ok(Val::Num(n0(a)?.sin())), + "TAN" => checked(n0(a)?.tan()), + "DEGREES" => Ok(Val::Num(n0(a)?.to_degrees())), + "RADIANS" => Ok(Val::Num(n0(a)?.to_radians())), + "EXP" => checked(n0(a)?.exp()), + "LN" => checked(n0(a)?.ln()), + "LOG10" => checked(n0(a)?.log10()), + "SQRT" => checked(n0(a)?.sqrt()), + "POWER" => checked(n0(a)?.powf(n1(a)?)), + "MOD" => { + let (x, m) = (n0(a)?, n1(a)?); + if m == 0.0 { Err(Err::Div0) } else { Ok(Val::Num(x - m * (x / m).floor())) } + } + "INT" => Ok(Val::Num(n0(a)?.floor())), + "PI" => Ok(Val::Num(std::f64::consts::PI)), + "ROUND" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::round))), + "ROUNDUP" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), |x| if x < 0.0 { x.floor() } else { x.ceil() }))), + "ROUNDDOWN" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::trunc))), + "FIXED" => Ok(Val::Text(format!("{:.*}", count(n1(a).unwrap_or(2.0)).min(15), n0(a)?))), + "IF" => { + let c = arg(a, 0)?.truth()?; + Ok(if c { a.get(1).cloned().unwrap_or(Val::Bool(true)) } else { a.get(2).cloned().unwrap_or(Val::Bool(false)) }) + } + "LEN" => Ok(Val::Num(chars(arg(a, 0)?).len() as f64)), + "UPPER" => Ok(Val::Text(arg(a, 0)?.text().to_uppercase())), + "LOWER" => Ok(Val::Text(arg(a, 0)?.text().to_lowercase())), + "TRIM" => Ok(Val::Text(arg(a, 0)?.text().split_whitespace().collect::>().join(" "))), + "LEFT" => Ok(Val::Text(chars(arg(a, 0)?).into_iter().take(count(n1(a).unwrap_or(1.0))).collect())), + "RIGHT" => { + let c = chars(arg(a, 0)?); + let k = count(n1(a).unwrap_or(1.0)).min(c.len()); + Ok(Val::Text(c.get(c.len() - k..).unwrap_or_default().iter().collect())) + } + "MID" => { + let c = chars(arg(a, 0)?); + let st = count(n1(a)? - 1.0); + let k = count(arg(a, 2)?.num()?); + Ok(Val::Text(c.into_iter().skip(st).take(k).collect())) + } + "TEXT" => { + let v = arg(a, 0)?; + let f = arg(a, 1)?.text(); + Ok(Val::Text(match v { + Val::Date(x) => format_date(*x, &f), + _ if looks_like_date_format(&f) => format_date(v.num()?, &f), + Val::Text(t) if t.trim().parse::().is_err() => t.clone(), + _ => format_number(v.num()?, &f), + })) + } + "TODAY" => Ok(Val::Date(now.floor())), + "NOW" => Ok(Val::Date(now)), + "DATE" => { + let (yy, mm, dd) = (n0(a)?, n1(a)?, arg(a, 2)?.num()?); + if !(yy.is_finite() && mm.is_finite() && dd.is_finite()) || yy.abs() > 9999.0 || mm.abs() > 12_000.0 || dd.abs() > 1e6 { + return Err(Err::Num); + } + Ok(Val::Date(serial(yy as i64, mm as i64, dd as i64))) + } + "YEAR" => Ok(Val::Num(parts(n0(a)?).0 as f64)), + "MONTH" => Ok(Val::Num(parts(n0(a)?).1 as f64)), + "DAY" => Ok(Val::Num(parts(n0(a)?).2 as f64)), + "HOUR" => Ok(Val::Num(parts(n0(a)?).3 as f64)), + "MINUTE" => Ok(Val::Num(parts(n0(a)?).4 as f64)), + "FILENAME" => Ok(Val::Text(env.file.clone())), + "SHEET" => Ok(Val::Text(env.sheet.clone())), + _ => Err(Err::Name), + } +} + +// ---------- AutoCAD fields ---------- + +/// The fields of a field template worked out (`%<\AcVar date \f "dd.MM.yyyy">%` and the file +/// name ones); `None` when one is a field CADCraft doesn't know. +fn fields(template: &str, env: &Env) -> Option { + let mut out = String::new(); + let mut rest = template; + let mut guard = 0; + while let Some(a) = rest.find("%<") { + guard += 1; + if guard > 64 { + return None; + } + out.push_str(rest.get(..a)?); + let tail = rest.get(a + 2..)?; + let b = tail.find(">%")?; + out.push_str(&field(tail.get(..b)?, env)?); + rest = tail.get(b + 2..)?; + } + out.push_str(rest); + Some(out) +} + +/// One field code (between `%<` and `>%`). +fn field(code: &str, env: &Env) -> Option { + let code = code.trim(); + let body = code.strip_prefix("\\AcVar")?.trim(); + let (name, fmt) = match body.split_once("\\f") { + Some((n, f)) => (n.trim(), Some(f.trim().trim_matches('"'))), + None => (body, None), + }; + let (y, mo, d, h, mi, s) = env.now; + let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + match name.to_ascii_lowercase().as_str() { + // AutoCAD's date formats are .NET's: MM month, mm minutes, HH hours. + "date" => Some(format_date(now, &net_to_sheet(fmt.unwrap_or("dd.MM.yyyy")))), + "filename" => Some(env.file.clone()), + _ => None, + } +} + +/// A .NET date format (`dd.MM.yyyy HH:mm`) as a spreadsheet one (`dd.mm.yyyy hh:mm`). +fn net_to_sheet(f: &str) -> String { + // .NET: M month, m minute; spreadsheet: m month, m after h minute. Minutes become "mm" after + // an hour, months stay "mm" otherwise. + f.replace("HH", "hh").replace('H', "h").replace("MMMM", "mmmm").replace("MMM", "mmm").replace("MM", "mm").replace('M', "m") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env() -> Env { + Env { now: (2026, 10, 23, 14, 5, 9), file: "plan.dwg".into(), sheet: "4".into(), measured: None } + } + + fn ev(f: &str) -> String { + evaluate(f, &env()).unwrap_or_default() + } + + /// Huge or infinite dates never overflow (a crash in a test build, nonsense otherwise). + #[test] + fn huge_date_serials_do_not_overflow() { + for f in ["=YEAR(1E300)", "=YEAR(-1E300)", "=TEXT(1E300,\"yyyy\")", "=TODAY()+1E300", "=MONTH(1E308*10)"] { + let _ = ev(f); + } + assert_eq!(ev("=YEAR(45000)"), "2023"); + } + + /// IF works out only the branch it picks: an error in the other one is not its result + /// (#2034 review). Errors in the condition or the picked branch still show. + #[test] + fn if_uses_only_the_branch_it_picks() { + assert_eq!(ev("=IF(TRUE,1,1/0)"), "1"); + assert_eq!(ev("=IF(FALSE,1/0,2)"), "2"); + assert_eq!(ev("=IF(1<2;(1/0)+5;3)"), "#DIV/0!"); + assert_eq!(ev("=IF(1/0,1,2)"), "#DIV/0!"); + assert_eq!(ev("=IF(FALSE,SQRT(-1)*2,IF(TRUE,7,1/0))"), "7"); + assert_eq!(ev("=SUM(1,1/0)"), "#DIV/0!", "other functions still need every argument"); + assert_eq!(ev("=IF(TRUE,1 2,3)"), "#ERROR!", "a malformed branch is still an error"); + } + + #[test] + fn arithmetic_and_functions() { + assert_eq!(ev("=2400-2*18"), "2364"); + assert_eq!(ev("=(1+2)^2/4"), "2.25"); + assert_eq!(ev("=ROUND(PI()*2,3)"), "6.283"); + assert_eq!(ev("=SUM(1,2,3)&\" mm\""), "6 mm"); + assert_eq!(ev("=IF(5>3,\"big\",\"small\")"), "big"); + assert_eq!(ev("=MAX(4;9;2)"), "9"); + assert_eq!(ev("=TEXT(1234.5,\"#,##0.00\")"), "1,234.50"); + assert_eq!(ev("=TEXT(0.25,\"0%\")"), "25%"); + assert_eq!(ev("=UPPER(LEFT(\"abc\",2))"), "AB"); + assert_eq!(ev("=MID(\"Hello\",2,3)"), "ell"); + assert_eq!(ev("=50%*10"), "5"); + } + + #[test] + fn dates_follow_the_clock() { + assert_eq!(ev("=TODAY()"), "23.10.2026"); + assert_eq!(ev("=TEXT(TODAY(),\"yyyy-mm-dd\")"), "2026-10-23"); + assert_eq!(ev("=TEXT(NOW(),\"hh:mm\")"), "14:05"); + assert_eq!(ev("=TODAY()+10"), "02.11.2026"); + assert_eq!(ev("=YEAR(DATE(2025,14,1))"), "2026"); + assert_eq!(ev("=TEXT(DATE(2026,1,5),\"d mmm yyyy\")"), "5 Jan 2026"); + assert_eq!(ev("%<\\AcVar date \\f \"dd.MM.yyyy\">%"), "23.10.2026"); + assert_eq!(ev("Date: %<\\AcVar Date \\f \"yyyy-MM-dd HH:mm\">%"), "Date: 2026-10-23 14:05"); + assert_eq!(ev("=FILENAME()&\" / \"&SHEET()"), "plan.dwg / 4"); + assert_eq!(evaluate("%<\\AcObjProp Object(%<\\_ObjId 1>%).Area>%", &env()), None, "unknown fields keep their value"); + } + + #[test] + fn a_dimension_formula_uses_its_measurement() { + let e = Env { measured: Some(1250.0), ..env() }; + assert_eq!(evaluate("=<>/2", &e).as_deref(), Some("625")); + assert_eq!(evaluate("=TEXT(<>+30,\"0.0\")&\" mm\"", &e).as_deref(), Some("1280.0 mm")); + assert_eq!(evaluate("=IF(<><>0,1,2)", &e).as_deref(), Some("1")); + assert!(!is_formula("=1+1\nsecond line")); + } + + #[test] + fn errors_show_as_in_spreadsheets_and_never_panic() { + assert_eq!(ev("=1/0"), "#DIV/0!"); + assert_eq!(ev("=FOO(1)"), "#NAME?"); + assert_eq!(ev("=\"a\"*2"), "#VALUE!"); + assert_eq!(ev("=SQRT(-1)"), "#NUM!"); + assert_eq!(ev("=(1+"), "#ERROR!"); + for f in [ + "=", + "==", + "=(((((", + &format!("={}", "-".repeat(500)), + &format!("={}1", "(".repeat(100)), + "=\"", + "=MID(\"a\",-5,1e300)", + "=DATE(1e300,1,1)", + ] { + let _ = evaluate(f, &env()); + } + assert!(!is_formula("plain")); + assert!(!is_formula("=")); + } +} diff --git a/crates/render/tests/it/annotative_viewport.rs b/crates/render/tests/it/annotative_viewport.rs index 1e93b1a6b5..74d527edb9 100644 --- a/crates/render/tests/it/annotative_viewport.rs +++ b/crates/render/tests/it/annotative_viewport.rs @@ -25,6 +25,7 @@ fn drawing(scale: f64, all_visible: bool) -> Drawing { d.header.set_i64("ANNOALLVISIBLE", i64::from(all_visible)); let anno = Common { anno_scales: vec![AnnoScale::new("1:50", 1.0, 50.0), AnnoScale::new("1:100", 1.0, 100.0)], ..Default::default() }; let text = Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 2.5, diff --git a/crates/render/tests/it/dim_text_fill.rs b/crates/render/tests/it/dim_text_fill.rs index b90e1595d0..2bef5cd227 100644 --- a/crates/render/tests/it/dim_text_fill.rs +++ b/crates/render/tests/it/dim_text_fill.rs @@ -138,6 +138,7 @@ fn a_dimension_read_with_its_block_keeps_the_block_and_gets_the_background() { let circle = EntityKind::Circle(Circle { center: Vec3::new(5.0, 5.0, 0.0), radius: 3.0 }); blk.entities.push(Entity::new(Handle(1), circle)); let text = MText { + formula: None, insert: Vec3::new(20.0, 20.0, 0.0), height: 0.18, width: 0.0, @@ -170,6 +171,7 @@ fn every_text_of_a_block_gets_a_background() { let mut blk = Block::new("*D1"); for (i, (y, s)) in [(20.0, "10.0000"), (22.0, "+0.1")].into_iter().enumerate() { let text = MText { + formula: None, insert: Vec3::new(20.0, y, 0.0), height: 0.18, width: 0.0, @@ -200,6 +202,7 @@ fn a_block_that_holds_its_background_gets_no_second_one() { let solid = cadcraft_doc::Solid { corners: solid.map(|(x, y)| Vec3::new(x, y, 0.0)) }; blk.entities.push(Entity::new(Handle(1), EntityKind::Solid(solid))); let text = MText { + formula: None, insert: Vec3::new(20.0, 20.0, 0.0), height: 0.18, width: 0.0, @@ -230,6 +233,7 @@ fn a_block_with_turned_text_gets_a_turned_background() { d.dim_styles.push(style(1, Color::ByBlock)); let mut blk = Block::new("*D1"); let text = cadcraft_doc::Text { + formula: None, insert: Vec3::new(20.0, 20.0, 0.0), align_pt: None, height: 0.5, diff --git a/crates/render/tests/it/render_props.rs b/crates/render/tests/it/render_props.rs index f210dc4e14..2fb7ee31cb 100644 --- a/crates/render/tests/it/render_props.rs +++ b/crates/render/tests/it/render_props.rs @@ -99,6 +99,7 @@ fn leader_arrows_use_their_style_dimscale() { fn text(x: f64, value: &str) -> Text { Text { + formula: None, insert: Vec3::new(x, 0.0, 0.0), align_pt: None, height: 1.0, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 37de4f1979..e95046d1d3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -26,6 +26,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "about" => about(ctx, &mut open), "preview" => crate::exchange::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), + "formulas" => formulas(ctx, &mut open), "blocks" => blocks(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), @@ -355,6 +356,29 @@ fn about(ctx: &egui::Context, open: &mut bool) { }); } +/// Help ▸ Text Formulas: how formulas in text work and the functions they use. +fn formulas(ctx: &egui::Context, open: &mut bool) { + egui::Window::new(crate::tl!("Text Formulas")).id(egui::Id::unique("Text Formulas")).open(open).default_size(vec2(680.0, 520.0)).show(ctx, |ui| { + ui.label(crate::tl!( + "A text that starts with = shows the result of a formula, as in a spreadsheet: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();\"dd.mm.yyyy\"). The formula stays with the text: editing the text edits the formula. Dates and times follow the computer's clock and are worked out again when the drawing is opened (Tools ▸ Update Fields does it at once). Date fields in AutoCAD drawings are updated the same way." + )); + ui.add_space(4.0); + ui.label(crate::tl!( + "Operators: + - * / ^ (power), % (percent), & (joins texts), = <> < > <= >= (compare). Texts in double quotes. Arguments are separated by commas or semicolons." + )); + ui.separator(); + egui::ScrollArea::vertical().show(ui, |ui| { + egui::Grid::new("formula_functions").striped(true).num_columns(2).show(ui, |ui| { + for (name, args, what) in cadcraft_engine::textformula::FUNCTIONS { + ui.label(egui::RichText::new(format!("{name}({args})")).monospace()); + ui.label(crate::i18n::t(what)); + ui.end_row(); + } + }); + }); + }); +} + /// Command Reference window; filters commands by id or label (English or translated) and starts the clicked command after closing the dialog. fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let mut start = None; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 43b135d195..d68ddee00c 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -67,6 +67,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.updates.check", "Check for Updates…", &["Help", "Check for Updates…"], None), ("ui.dialog.about", "About CADCraft", &["Help", "About CADCraft"], None), ("ui.dialog.commands", "Command Reference", &["Help", "CADCraft Help"], Some("F1")), + ("ui.dialog.formulas", "Text Formulas", &["Help", "Text Formulas"], None), ("ui.toggle.history", "Command History", &["Window", "Command History"], Some("F2")), ("ui.cmdline.lines", "Command Line History Lines", &[], None), ("ui.cmdline.clear", "Clear Command History", &[], None), @@ -369,6 +370,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { app.ui.dialog = Some(id.trim_start_matches("ui.dialog.").to_string()); From 124b7b46fdc30376376d942124b222bf700bdfbe Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:29:24 +0200 Subject: [PATCH 02/30] HATCH: pick points near the view, boundary warnings, open-curve and block boundaries, background colour, custom patterns Split out of #2034. - Pick points look for the boundary among objects in and around the view; a boundary running far outside it is refused with a notice window (Session::notice, notices.rs). - Select objects takes open curves that enclose an area together; objects enclosing nothing are left out with a warning. Block references bound hatches by what they draw, as continuous curves (Options::continuous). - Hatch background colour round-trips as AutoCAD's HATCHBACKGROUNDCOLOR xdata; a background that is not a colour is an error. - Custom Patterns tab: the .pat files of a chosen folder with a preview. - Boundary objects stay highlighted while HATCH runs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- apps/cadcraft/src/main.rs | 1 + crates/engine/src/cmd/hatch.rs | 472 +++++++++++++++++++++-- crates/engine/src/cmd/hatch/edit.rs | 4 + crates/engine/src/cmd/hatch/pick.rs | 91 ++++- crates/engine/src/lib.rs | 30 ++ crates/engine/src/session/interactive.rs | 5 + crates/io/src/dxf_ext.rs | 29 ++ crates/io/src/dxf_raw.rs | 11 +- crates/io/src/dxf_read/hatch.rs | 13 +- crates/io/src/dxf_write/entity.rs | 5 + crates/io/src/dxf_write/sections.rs | 3 +- crates/io/src/pdf.rs | 1 + crates/io/tests/it/hatch_background.rs | 70 ++++ crates/render/src/draw.rs | 3 +- crates/render/src/mline.rs | 2 +- crates/render/src/pipeline.rs | 4 + crates/ui-egui/src/canvas/list.rs | 1 + crates/ui-egui/src/canvas/viewport.rs | 1 + crates/ui-egui/src/custom_patterns.rs | 228 +++++++++++ crates/ui-egui/src/hatchdlg.rs | 144 ++++++- crates/ui-egui/src/lib.rs | 8 + crates/ui-egui/src/notices.rs | 51 +++ crates/ui-egui/src/theme.rs | 3 + 23 files changed, 1113 insertions(+), 67 deletions(-) create mode 100644 crates/io/tests/it/hatch_background.rs create mode 100644 crates/ui-egui/src/custom_patterns.rs create mode 100644 crates/ui-egui/src/notices.rs diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 1007fc0c1a..5679e79604 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -166,6 +166,7 @@ fn services() -> Services { .save_file() .map(|p| p.to_string_lossy().to_string()) })), + pick_folder: Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string()))), // APPLOAD: AutoLISP routines only, starting where the last one was loaded from. pick_lisp: Some(Box::new(|dir: &str| { let dialog = rfd::FileDialog::new().add_filter(i18n::t("AutoLISP (LSP)"), &["lsp"]).add_filter(i18n::t("All files"), &["*"]); diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index d0221a00a2..14ccdbd5ed 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -23,13 +23,13 @@ pub use pick::{HatchPicks, PickMode}; pub fn specs() -> Vec { vec![ - CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))), + CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects, or objects that together enclose an area), pattern?: \"ANSI31\" (built in, or defined by patternFile | patternText), patternFile?: path to a .pat file | patternText?: its contents (loads the patterns it defines), scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION), background?: colour | \"None\"} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))), CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))), CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))), CommandSpec::new("region", "Region", run_region).menu(&["Draw", "Region"]).alias(&["reg"]).params("{handles?}"), - CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))), + CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, background?: colour | \"None\", origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))), CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick) - .params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing") + .params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects, or objects that together enclose an area)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing") .enabled(has_doc) .noundo() .interactive(|_| Ok(Box::new(pick::HatchPickM::default()))), @@ -42,11 +42,12 @@ pub(super) fn outline_tol(ext: Bounds2) -> f64 { } /// Tessellated outlines of every visible curve in the space (hatch boundary candidates), each -/// with the handle of the object it came from. +/// with the handle of the object it came from: only the objects reaching into `near` when given, +/// tessellated finely enough for that area. fn outlines(d: &Drawing, space: &Space, near: Option) -> (Vec>, Vec) { let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) }; let ext = d.extents(space); - let tol = outline_tol(ext); + let tol = near.map_or_else(|| outline_tol(ext), outline_tol); let mut out = Vec::new(); let mut owners = Vec::new(); for e in store.iter() { @@ -69,7 +70,27 @@ fn outlines(d: &Drawing, space: &Space, near: Option) -> (Vec /// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous /// box around the extents `ext`. fn object_polys(d: &Drawing, e: &Entity, tol: f64, ext: Bounds2) -> Vec> { - let mut polys = crate::select::hit_polylines(d, e, tol); + let mut polys = match &e.kind { + // Text and annotation never bound a hatch: their boxes would cut areas in two. + EntityKind::Text(_) + | EntityKind::MText(_) + | EntityKind::AttDef(_) + | EntityKind::Dimension(_) + | EntityKind::Tolerance(_) + | EntityKind::Hatch(_) + | EntityKind::Image(_) => return Vec::new(), + // Blocks, multileaders and tables bound by the lines they draw, not by the box around + // them, and not by their text. + EntityKind::Insert(_) | EntityKind::MLeader(_) | EntityKind::Table(_) => { + let list = cadcraft_render::build_entities( + d, + std::iter::once(e), + &cadcraft_render::Options { tolerance: tol, text: false, fill: false, continuous: true, ..Default::default() }, + ); + return list.prims.iter().filter(|p| matches!(p.kind, cadcraft_render::Kind::Polyline)).map(|p| list.points(p).to_vec()).collect(); + } + _ => crate::select::hit_polylines(d, e, tol), + }; if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) { let r = (ext.width() + ext.height()).max(1.0) * 4.0; for pl in &mut polys { @@ -206,19 +227,76 @@ pub(crate) fn island_style(t: &str) -> Option { } } -/// Boundary loops (outer + islands) around an internal point. +/// The title of the window that explains why a boundary wasn't found. +pub(crate) const BOUNDARY_ERROR: &str = "Hatch - Boundary Definition Error"; + +/// Boundary loops (outer + islands) around an internal point. With a view on screen around the +/// point, the boundary is looked for among the objects in and near the view (as AutoCAD does), +/// and a boundary reaching far outside it is refused: it is almost always a gap that let the +/// area run out into the rest of the drawing. pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { + loops_near(s, p, false) +} + +/// [`loops_at`] for a pick on screen (`picked`): a boundary reaching far outside the view is +/// refused. Otherwise (scripts, JSON) the whole space is searched when the boundary runs out of +/// the area around the view. +pub(crate) fn loops_picked(s: &Session, p: Vec2) -> Result> { + loops_near(s, p, true) +} + +fn loops_near(s: &Session, p: Vec2, picked: bool) -> Result> { + let view = s.view_box().filter(|v| v.contains(p)); + let near = view.map(|v| v.expand(v.width().max(v.height()) * 0.5)); + match loops_in(s, p, near) { + // The boundary runs out of the area around the view: look in the whole space. A pick + // on screen keeps it only when it is not many times the view's size (a gap that let + // the area run out into the rest of the drawing is refused). + Err(e) if near.is_some() => match loops_in(s, p, None) { + Ok(l) => { + let b = Bounds2::from_points(l.iter().flat_map(|l| l.vertices.iter().map(|v| v.p))); + let size = view.map_or(f64::INFINITY, |v| v.width().max(v.height())); + if !picked || b.width().max(b.height()) <= size * FAR_FACTOR { Ok(l) } else { Err(e) } + } + Err(_) => Err(e), + }, + r => r, + } +} + +/// How many times larger than the view a boundary found by a pick on screen may be. +const FAR_FACTOR: f64 = 4.0; + +/// Boundary loops around `p` among the objects reaching into `near` (all objects when `None`). +fn loops_in(s: &Session, p: Vec2, near: Option) -> Result> { let d = s.doc()?; let space = s.space(); let ext = d.extents(&space); let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9); - let (polys, owners) = outlines(d, &space, None); + let (polys, owners) = outlines(d, &space, near); + let segments: usize = polys.iter().map(|pl| pl.len().saturating_sub(1)).sum(); + if segments > cadcraft_geom::region::MAX_SEGMENTS { + return Err(EngineError::Other( + "There are too many objects in the view to find the boundary. Zoom in closer to the area to hatch and pick again.".into(), + )); + } // A line that ends on a flattened curve (an ellipse) can stop short of its chords. - let polys = cadcraft_geom::region::snap_ends(&polys, outline_tol(ext), tol); - let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d)) - .ok_or_else(|| EngineError::Other("Valid hatch boundary not found.".into()))?; + let polys = cadcraft_geom::region::snap_ends(&polys, outline_tol(near.unwrap_or(ext)), tol); + let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d)).ok_or_else(|| { + EngineError::Other( + "Valid hatch boundary not found: the area around the picked point is not closed. Close the gaps in its boundary and pick again.".into(), + ) + })?; let outer = found.outer; let ob = Bounds2::from_points(outer.iter().copied()); + if let Some(n) = near + && !n.contains_box(&ob) + { + return Err(EngineError::Other( + "The boundary around the picked point reaches far outside the visible area. The area is probably not closed: check its boundary for gaps, or zoom out to show the whole area and pick again." + .into(), + )); + } let sources = handles_of(&owners, &found.outer_sources); let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }]; // Islands: closed objects entirely inside the outer loop that don't contain the pick point. @@ -254,18 +332,132 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { Ok(loops) } +/// Most open objects whose shared boundary is traced in one selection. +const MAX_OPEN_OBJECTS: usize = 2000; + +/// Boundary loops from selected objects: each closed object is a loop; open objects (lines, +/// arcs, open polylines…) that together enclose an area make a loop of their outline, as many +/// as there are separate groups of them. Groups that enclose nothing are left out; when nothing +/// at all encloses an area, the selection is refused. pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result> { + loops_from_selection(s, hs).map(|(l, _)| l) +} + +/// [`loops_from_handles`] with the selected objects that were left out (enclosing nothing). +pub(crate) fn loops_from_selection(s: &Session, hs: &[Handle]) -> Result<(Vec, Vec)> { let d = s.doc()?; let mut loops = Vec::new(); + let mut open: Vec = Vec::new(); + let mut left_out: Vec = Vec::new(); for h in hs { - if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) { + let Some(e) = d.entity(*h) else { continue }; + if let Some(vs) = closed_loop(d, e) { loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] }); + } else if island_curve(d, e) { + if !open.contains(h) { + open.push(*h); + } + } else if !left_out.contains(h) { + left_out.push(*h); + } + } + if open.len() > MAX_OPEN_OBJECTS { + return Err(EngineError::Other(format!("Select at most {MAX_OPEN_OBJECTS} open objects for one boundary."))); + } + if !open.is_empty() { + let space = s.space(); + let ext = d.extents(&space); + let b = open.iter().filter_map(|h| d.entity(*h)).fold(Bounds2::EMPTY, |b, e| b.union(&entity_bounds(d, e, 0))); + let size = (b.width() + b.height()).max(1e-9); + let ttol = size / 20000.0; + let polys: Vec<(Handle, Vec)> = + open.iter().filter_map(|h| d.entity(*h)).flat_map(|e| object_polys(d, e, ttol, ext).into_iter().map(move |pl| (e.handle, pl))).collect(); + let tol = (size * 1e-9).max(1e-9); + let gap = gap_tolerance(d); + for group in touching_groups(&polys, (tol * 100.0).max(gap)) { + let pls: Vec> = group.iter().filter_map(|&i| polys.get(i).map(|(_, pl)| pl.clone())).collect(); + let mut sources: Vec = group.iter().filter_map(|&i| polys.get(i).map(|(h, _)| *h)).collect(); + sources.sort_unstable(); + sources.dedup(); + match cadcraft_geom::region::outline(&pls, tol, gap).filter(|o| o.len() >= 3) { + Some(outline) => { + loops.push(HatchLoop { vertices: outline.into_iter().map(PolyVertex::new).collect(), outer: loops.is_empty(), sources }) + } + None => left_out.extend(sources), + } } } if loops.is_empty() { - return Err(EngineError::Other("No closed boundary objects selected.".into())); + let msg = if left_out.is_empty() { + "No boundary objects selected: select closed objects, or objects that together enclose an area." + } else { + "The selected objects don't enclose an area: together they must form a closed boundary. Select the missing objects or close the gaps." + }; + return Err(EngineError::Other(msg.into())); } - Ok(loops) + Ok((loops, left_out)) +} + +/// The warning for selected objects left out of a hatch because they enclose nothing. +pub(crate) const LEFT_OUT: &str = + "Some of the selected objects don't enclose an area and were left out of the hatch. Together, objects must form a closed boundary."; + +/// Groups of polylines that touch or cross each other (directly or through others), as indices. +fn touching_groups(polys: &[(Handle, Vec)], tol: f64) -> Vec> { + let n = polys.len(); + let mut parent: Vec = (0..n).collect(); + fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i) { + if p == i { + break; + } + let gp = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = gp; + } + i = p; + } + i + } + let bounds: Vec = polys.iter().map(|(_, pl)| Bounds2::from_points(pl.iter().copied()).expand(tol)).collect(); + let touch = |a: &[Vec2], b: &[Vec2]| { + a.windows(2).any(|wa| { + let (Some(a0), Some(a1)) = (wa.first(), wa.get(1)) else { return false }; + let la = cadcraft_geom::Line::new(*a0, *a1); + b.windows(2).any(|wb| { + let (Some(b0), Some(b1)) = (wb.first(), wb.get(1)) else { return false }; + let lb = cadcraft_geom::Line::new(*b0, *b1); + cadcraft_geom::line_line(&la, &lb).is_some() + || la.dist(*b0) <= tol + || la.dist(*b1) <= tol + || lb.dist(*a0) <= tol + || lb.dist(*a1) <= tol + }) + }) + }; + for i in 0..n { + for j in (i + 1)..n { + let (Some(bi), Some(bj)) = (bounds.get(i), bounds.get(j)) else { continue }; + if !bi.intersects(bj) { + continue; + } + let (Some((_, pi)), Some((_, pj))) = (polys.get(i), polys.get(j)) else { continue }; + if touch(pi, pj) { + let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); + if ri != rj + && let Some(slot) = parent.get_mut(ri) + { + *slot = rj; + } + } + } + } + let mut groups: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for i in 0..n { + let r = root(&mut parent, i); + groups.entry(r).or_default().push(i); + } + groups.into_values().collect() } /// Gradient fills by name: the shapes the renderer draws (`render/src/hatch.rs`); the INV forms @@ -291,6 +483,27 @@ struct HatchSettings { origin: Vec2, origin_mode: OriginMode, style: u8, + /// Background colour under the pattern (`background`; none by default). + background: Option, +} + +/// A `background` parameter: a colour name, ACI number or `r,g,b`; `"None"`, `""` or null for +/// none. `None` when absent or not a colour. +/// A `background` given that is not a colour, `none` or null: an error, not a silent no-background. +pub(crate) fn check_background(cmd: &str, p: &Value) -> Result<()> { + if p.get("background").is_some() && background_param(p).is_none() { + return Err(bad(cmd, "`background` must be a colour (an ACI number, a name, \"r,g,b\"), \"none\" or null")); + } + Ok(()) +} + +pub(crate) fn background_param(p: &Value) -> Option> { + match p.get("background")? { + Value::Null => Some(None), + Value::String(t) if t.trim().is_empty() || t.trim().eq_ignore_ascii_case("none") || t.trim() == "." => Some(None), + Value::String(t) => cadcraft_color::Color::parse(t.trim()).map(Some), + v => v.as_i64().and_then(|i| i16::try_from(i).ok()).map(|i| Some(cadcraft_color::Color::from_aci(i))), + } } impl HatchSettings { @@ -328,6 +541,7 @@ impl HatchSettings { style: str_param(p, "style") .and_then(island_style) .unwrap_or_else(|| s.doc().map_or(0, |d| d.header.i64("HPISLANDDETECTION", 0).clamp(0, 2) as u8)), + background: background_param(p).flatten(), } } fn hatch(&self, mut loops: Vec) -> EntityKind { @@ -346,7 +560,7 @@ impl HatchSettings { style: self.style, elevation: 0.0, gradient: self.gradient.clone(), - background: None, + background: if solid { None } else { self.background }, pattern_lines: patfile::lines_for(&self.pattern), }) } @@ -463,6 +677,7 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec>) } fn run_hatch(s: &mut Session, p: &Value) -> Result { + check_background("hatch", p)?; patfile::load_param(p)?; // Like the prompt: a name without a definition would be drawn as ANSI31. if let Some(up) = str_param(p, "pattern").map(str::to_ascii_uppercase) @@ -552,6 +767,11 @@ struct HatchM { asking: Option, /// "Select objects" mode instead of "Pick internal point"; the next HATCH starts in it again. selecting: bool, + /// The boundary objects selected so far (highlighted): their loops are traced together, so + /// lines selected one by one can close an area between them. + objects: Vec, + /// The loops of `objects`, when they enclose an area yet (for the preview). + object_loops: Vec, } impl HatchM { @@ -562,6 +782,8 @@ impl HatchM { loops: Vec::new(), asking: None, selecting: s.last_used.hatch_select, + objects: Vec::new(), + object_loops: Vec::new(), } } fn set_mode(&mut self, s: &mut Session, selecting: bool) { @@ -569,9 +791,40 @@ impl HatchM { s.last_used.hatch_select = selecting; } fn finish(&mut self, s: &mut Session) -> Result { + if !self.objects.is_empty() { + match loops_from_selection(s, &self.objects) { + Ok((l, left_out)) => { + if !left_out.is_empty() { + s.notice(BOUNDARY_ERROR, LEFT_OUT); + } + if self.settings.separate { + self.loops.extend(l.into_iter().map(|l| vec![HatchLoop { outer: true, ..l }])); + } else { + self.loops.push(l); + } + } + Err(e) => { + // Stay: more objects can still close the area. + s.notice(BOUNDARY_ERROR, e.to_string()); + return Ok(Step::Continue); + } + } + } + s.set_selection(Vec::new()); add_hatches(s, &self.settings, std::mem::take(&mut self.loops))?; Ok(Step::Done) } + /// Add selected boundary objects: they show highlighted, and their loops are traced again. + fn add_objects(&mut self, s: &mut Session, hs: Vec) { + for h in hs { + if !self.objects.contains(&h) { + self.objects.push(h); + } + } + s.set_selection(self.objects.clone()); + self.object_loops = loops_from_handles(s, &self.objects).unwrap_or_default(); + s.echo(format!("{} object(s) selected{}", self.objects.len(), if self.object_loops.is_empty() { ", not enclosing an area yet" } else { "" })); + } fn set_origin(&mut self, s: &mut Session, origin: Option, mode: OriginMode) -> Result<()> { let h = &mut s.doc_mut()?.header; if let Some(o) = origin.filter(|o| o.is_finite()) { @@ -695,34 +948,33 @@ impl Interactive for HatchM { } match i { Input::Point(p) if !self.selecting => { - match loops_at(s, p) { + match loops_picked(s, p) { Ok(l) => { s.echo(format!("Analyzing the selected data... {} loop(s)", l.len())); self.loops.push(l); } - Err(e) => s.echo(e.to_string()), + Err(e) => s.notice(BOUNDARY_ERROR, e.to_string()), } Ok(Step::Continue) } Input::Pick(hs) => { - match loops_from_handles(s, &hs) { - Ok(l) => { - s.echo(format!("{} found", hs.len())); - if self.settings.separate { - self.loops.extend(l.into_iter().map(|l| vec![HatchLoop { outer: true, ..l }])); - } else { - self.loops.push(l); - } - } - Err(e) => s.echo(e.to_string()), - } + self.add_objects(s, hs); Ok(Step::Continue) } + Input::Cancel => { + s.set_selection(Vec::new()); + Ok(Step::Cancel) + } Input::Keyword(k) => { match k.as_str() { "Select objects" => self.set_mode(s, true), "picK internal point" => self.set_mode(s, false), - "Undo" => self.loops.clear(), + "Undo" => { + self.loops.clear(); + self.objects.clear(); + self.object_loops.clear(); + s.set_selection(Vec::new()); + } "Pattern" | "seTtings" => self.asking = Some(HatchAsk::Pattern), "sCale" => self.asking = Some(HatchAsk::Scale), "Angle" => self.asking = Some(HatchAsk::Angle), @@ -747,10 +999,11 @@ impl Interactive for HatchM { } } fn preview(&self, _s: &Session, _c: Vec2) -> Vec { - if self.loops.is_empty() { + let loops: Vec = self.loops.iter().flatten().chain(self.object_loops.iter()).cloned().collect(); + if loops.is_empty() { return Vec::new(); } - vec![self.settings.hatch(self.loops.iter().flatten().cloned().collect())] + vec![self.settings.hatch(loops)] } } @@ -786,6 +1039,58 @@ mod tests { use super::*; + /// A background that is not a colour is an error, not a quiet "no background" (#2034 review). + #[test] + fn a_bad_background_is_refused() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + for bad in [json!("blu"), json!(true), json!({})] { + assert!(s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "ANSI31", "background": bad })).is_err(), "{bad}"); + } + s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap(); + let (h, _) = only_hatch(&s); + assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": "blu" })).is_err()); + assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": "none" })).is_ok()); + } + + /// A block whose lines are drawn with a dashed linetype: its outline still bounds a hatch, and + /// its lines still cut, across the gaps between dashes (#2034 review). + #[test] + fn dashed_lines_in_a_block_bound_hatches_and_cut() { + let mut s = Session::new(); + s.doc_mut().unwrap().linetypes.push(cadcraft_doc::Linetype::simple("DASHED", "", &[2.0, -1.0])); + let r = s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + let rect = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let mid = s.execute("line", &json!({ "points": [[5, 0], [5, 10]] })).unwrap(); + let mid = mid["handles"][0].as_str().unwrap().to_string(); + for h in [&rect, &mid] { + let h = Handle::parse_hex(h).unwrap(); + s.doc_mut().unwrap().modify_entity(h, |e| e.common.linetype = "DASHED".into()).unwrap(); + } + s.execute("block", &json!({ "name": "ROOM", "base": [0, 0], "handles": [rect, mid], "keep": "convert" })).unwrap(); + s.execute("hatch", &json!({ "points": [[2, 5]], "pattern": "SOLID" })).unwrap(); + let (_, h) = only_hatch(&s); + let b = cadcraft_geom::Bounds2::from_points(h.loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p))); + assert!((b.min.x - 0.0).abs() < 1e-6 && (b.max.x - 5.0).abs() < 1e-6, "the left half of the room: {b:?}"); + // A line across the room, trimmed at the block's dashed middle line where a gap is + // drawn (5 to 6 above the start of the dashes). + let l = s.execute("line", &json!({ "points": [[1, 5.5], [9, 5.5]] })).unwrap(); + let l = l["handles"][0].as_str().unwrap().to_string(); + s.execute("trim", &json!({ "handle": l, "pick": [8, 5.5] })).unwrap(); + let lines: Vec = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) if (l.a.y - 5.5).abs() < 1e-9 => Some(l.clone()), + _ => None, + }) + .collect(); + let [line] = lines.as_slice() else { panic!("one trimmed line is left: {lines:?}") }; + assert!((line.a.x.max(line.b.x) - 5.0).abs() < 1e-6, "cut at the dashed line: {line:?}"); + } + /// The drawing's only hatch and its handle (hatches go to the back of the draw order, so not the last entity). fn only_hatch(s: &Session) -> (String, Hatch) { let d = s.doc().unwrap(); @@ -937,4 +1242,109 @@ mod tests { let (_, hg) = only_hatch(&s); assert_eq!(hg.loops.len(), 1, "gradient with repeated picks in same region must deduplicate loops"); } + + fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle { + let r = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap() + } + + #[test] + fn selected_lines_that_close_an_area_bound_a_hatch() { + let mut s = Session::new(); + // A square of four lines running past each other at the corners. + let hs = vec![ + line(&mut s, [-2.0, 0.0], [12.0, 0.0]), + line(&mut s, [10.0, -2.0], [10.0, 12.0]), + line(&mut s, [12.0, 10.0], [-2.0, 10.0]), + line(&mut s, [0.0, 12.0], [0.0, -2.0]), + ]; + let hex: Vec = hs.iter().map(|h| h.hex()).collect(); + s.execute("hatch", &json!({ "handles": hex, "pattern": "SOLID" })).unwrap(); + let (_, h) = only_hatch(&s); + assert_eq!(h.loops.len(), 1); + let b = Bounds2::from_points(h.loops[0].vertices.iter().map(|v| v.p)); + assert!(b.min.near(Vec2::new(0.0, 0.0), 1e-6) && b.max.near(Vec2::new(10.0, 10.0), 1e-6), "{b:?}"); + let mut src = h.loops[0].sources.clone(); + src.sort_unstable(); + let mut want = hs.clone(); + want.sort_unstable(); + assert_eq!(src, want); + } + + #[test] + fn selected_lines_that_leave_a_gap_are_refused() { + let mut s = Session::new(); + let hs = [line(&mut s, [0.0, 0.0], [10.0, 0.0]), line(&mut s, [10.0, 0.0], [10.0, 10.0]), line(&mut s, [10.0, 10.0], [0.0, 10.0])]; + let hex: Vec = hs.iter().map(|h| h.hex()).collect(); + let e = s.execute("hatch", &json!({ "handles": hex })).unwrap_err().to_string(); + assert!(e.contains("don't enclose an area"), "{e}"); + } + + #[test] + fn select_objects_highlights_them_and_warns_when_they_dont_close() { + let mut s = Session::new(); + let a = line(&mut s, [0.0, 0.0], [10.0, 0.0]); + let b = line(&mut s, [10.0, 0.0], [10.0, 10.0]); + let c = line(&mut s, [10.0, 10.0], [0.0, 10.0]); + let d = line(&mut s, [0.0, 10.0], [0.0, 0.0]); + s.cmdline("-HATCH").unwrap(); + s.input(Input::Keyword("Select objects".into())).unwrap(); + s.input(Input::Pick(vec![a])).unwrap(); + s.input(Input::Pick(vec![b, c])).unwrap(); + assert_eq!(s.selection(), &[a, b, c]); + // Three lines: Enter warns in a window and the command waits for more. + s.input(Input::Enter).unwrap(); + assert!(s.running.is_some()); + assert_eq!(s.notices.len(), 1); + assert_eq!(s.notices[0].title, BOUNDARY_ERROR); + s.notices.clear(); + s.input(Input::Pick(vec![d])).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none()); + assert!(s.selection().is_empty()); + let (_, h) = only_hatch(&s); + assert_eq!(h.loops.len(), 1); + } + + #[test] + fn a_pick_in_an_open_area_warns_and_creates_nothing() { + let mut s = Session::new(); + line(&mut s, [0.0, 0.0], [10.0, 0.0]); + line(&mut s, [10.0, 0.0], [10.0, 10.0]); + s.cmdline("-HATCH").unwrap(); + s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap(); + assert_eq!(s.notices.len(), 1); + assert!(s.notices[0].message.contains("not closed"), "{}", s.notices[0].message); + } + + #[test] + fn a_boundary_far_outside_the_view_is_refused() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10000, 10000] })).unwrap(); + // A small window on screen inside the big rectangle. + s.execute("zoom", &json!({ "mode": "window", "p1": [100, 100], "p2": [110, 110] })).unwrap(); + s.cmdline("-HATCH").unwrap(); + s.input(Input::Point(Vec2::new(105.0, 105.0))).unwrap(); + assert!(s.notices.first().is_some_and(|n| n.message.contains("far outside the visible area")), "{:?}", s.notices); + s.cancel(); + // Zoomed out to show it, the same pick hatches; a script's pick isn't refused. + s.execute("zoom", &json!({ "mode": "extents" })).unwrap(); + s.execute("hatch", &json!({ "points": [[105, 105]] })).unwrap(); + s.execute("zoom", &json!({ "mode": "window", "p1": [100, 100], "p2": [110, 110] })).unwrap(); + s.execute("hatch", &json!({ "points": [[105, 105]] })).unwrap(); + } + + #[test] + fn text_and_block_boxes_do_not_bound_a_hatch() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 50] })).unwrap(); + // A multileader whose text box crosses the room. + s.execute("mleader", &json!({ "points": [[50, 25], [130, 25]], "text": "Glass glass glass glass" })).unwrap(); + s.execute("text", &json!({ "at": [-20, 20], "text": "A very long label running into the room", "height": 5.0 })).unwrap(); + s.execute("zoom", &json!({ "mode": "extents" })).unwrap(); + s.execute("hatch", &json!({ "points": [[20, 10]], "pattern": "SOLID" })).unwrap(); + let (_, h) = only_hatch(&s); + let b = Bounds2::from_points(h.loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p))); + assert!(b.min.near(Vec2::new(0.0, 0.0), 1e-6) && b.max.near(Vec2::new(100.0, 50.0), 1e-6), "{b:?}"); + } } diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index c0f5c74400..8181fc6046 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -362,6 +362,7 @@ fn edit_loops(h: &mut Hatch, added: &[HatchLoop], removed: &[usize]) -> Result<( pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result { check_numbers(p)?; + super::check_background("hatchedit", p)?; let hs = hatches(s, p)?; let (added, removed) = boundary_changes(s, p, &hs)?; let style = match str_param(p, "style") { @@ -425,6 +426,9 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result { if let Some(st) = style { h.style = st; } + if let Some(bg) = super::background_param(p) { + h.background = bg; + } if origin.is_some() || mode.is_some() { h.origin = mode.unwrap_or_default().origin(&h.loops, origin.unwrap_or(h.origin)); } diff --git a/crates/engine/src/cmd/hatch/pick.rs b/crates/engine/src/cmd/hatch/pick.rs index b5fc607c26..fa10ea12e9 100644 --- a/crates/engine/src/cmd/hatch/pick.rs +++ b/crates/engine/src/cmd/hatch/pick.rs @@ -6,7 +6,7 @@ use cadcraft_doc::{EntityKind, Handle, HatchLoop}; use cadcraft_geom::Vec2; use serde_json::{Value, json}; -use super::{HatchSettings, closed_loop, loops_at, loops_from_handles}; +use super::{BOUNDARY_ERROR, HatchSettings, LEFT_OUT, loops_at, loops_from_handles, loops_from_selection, loops_picked}; use crate::cmd::{bad, points_param, targets}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; @@ -73,13 +73,8 @@ pub(super) fn run_hatchpick(s: &mut Session, p: &Value) -> Result { if hs.len() > MAX_PICKS { return Err(bad("hatchpick", format!("at most {MAX_PICKS} objects"))); } - let d = s.doc()?; - for h in hs { - match d.entity(h) { - Some(e) if closed_loop(d, e).is_some() => picks.handles.push(h), - _ => return Err(bad("hatchpick", format!("{} is not a closed object", h.hex()))), - } - } + let (loops, _) = loops_from_selection(s, &hs).map_err(|e| bad("hatchpick", e.to_string()))?; + picks.handles = hs.into_iter().filter(|h| loops.iter().any(|l| l.sources.contains(h))).collect(); if picks.points.is_empty() { picks.mode = PickMode::Objects; } @@ -102,6 +97,8 @@ enum Pick { pub(super) struct HatchPickM { mode: Option, picks: Vec, + /// The loops of all the objects picked so far, traced together (for the preview). + object_loops: Vec, } impl HatchPickM { @@ -114,6 +111,21 @@ impl HatchPickM { }) .sum() } + fn objects(&self) -> Vec { + let mut out: Vec = Vec::new(); + for p in &self.picks { + if let Pick::Objects(hs, _) = p { + out.extend(hs.iter().copied().filter(|h| !out.contains(h)).collect::>()); + } + } + out + } + /// Show the picked objects highlighted and trace their loops again. + fn objects_changed(&mut self, s: &mut Session) { + let all = self.objects(); + s.set_selection(all.clone()); + self.object_loops = if all.is_empty() { Vec::new() } else { loops_from_handles(s, &all).unwrap_or_default() }; + } fn keep(&self, s: &mut Session, mode: PickMode) { let mut out = HatchPicks { mode, ..HatchPicks::default() }; for p in &self.picks { @@ -149,14 +161,48 @@ impl Interactive for HatchPickM { return Ok(Step::Continue); }; match (mode, i) { - (_, Input::Cancel) => Ok(Step::Cancel), + (_, Input::Cancel) => { + if mode == PickMode::Objects { + s.set_selection(Vec::new()); + } + Ok(Step::Cancel) + } (PickMode::Points | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => { if self.picks.pop().is_none() { s.echo("Nothing to undo."); } + if mode == PickMode::Objects { + self.objects_changed(s); + } Ok(Step::Continue) } - (PickMode::Points | PickMode::Objects, Input::Enter) => { + (PickMode::Objects, Input::Enter) => { + let all = self.objects(); + // Only the objects that bound an area are kept. + let mut used: Vec = Vec::new(); + if !all.is_empty() { + match loops_from_selection(s, &all) { + Ok((loops, left_out)) => { + if !left_out.is_empty() { + s.notice(BOUNDARY_ERROR, LEFT_OUT); + } + used = all.into_iter().filter(|h| loops.iter().any(|l| l.sources.contains(h))).collect(); + } + Err(e) => { + // Stay: more objects can still close the area. + s.notice(BOUNDARY_ERROR, e.to_string()); + return Ok(Step::Continue); + } + } + } + s.set_selection(Vec::new()); + self.keep(s, mode); + if let Some(p) = s.hatch_picks.as_mut() { + p.handles = used; + } + Ok(Step::Done) + } + (PickMode::Points, Input::Enter) => { self.keep(s, mode); Ok(Step::Done) } @@ -165,27 +211,29 @@ impl Interactive for HatchPickM { s.echo(format!("At most {MAX_PICKS} picks.")); return Ok(Step::Continue); } - match loops_at(s, q) { + match loops_picked(s, q) { Ok(l) => { s.echo(format!("Analyzing the selected data... {} loop(s)", l.len())); self.picks.push(Pick::Point(q, l)); } - Err(e) => s.echo(e.to_string()), + Err(e) => s.notice(BOUNDARY_ERROR, e.to_string()), } Ok(Step::Continue) } (PickMode::Objects, Input::Pick(hs)) => { let room = MAX_PICKS.saturating_sub(self.count()); - let closed: Vec = { - let d = s.doc()?; - hs.iter().copied().filter(|h| d.entity(*h).is_some_and(|e| closed_loop(d, e).is_some())).take(room).collect() - }; - let others = hs.len().saturating_sub(closed.len()); - if !closed.is_empty() { - let loops = loops_from_handles(s, &closed)?; - self.picks.push(Pick::Objects(closed.clone(), loops)); + let known = self.objects(); + let new: Vec = hs.into_iter().filter(|h| !known.contains(h)).take(room).collect(); + if !new.is_empty() { + self.picks.push(Pick::Objects(new, Vec::new())); } - s.echo(if others == 0 { format!("{} found", closed.len()) } else { format!("{} found, {others} not closed", closed.len()) }); + self.objects_changed(s); + let n = self.objects().len(); + s.echo(if self.object_loops.is_empty() { + format!("{n} object(s) selected, not enclosing an area yet") + } else { + format!("{n} object(s) selected, {} loop(s)", self.object_loops.len()) + }); Ok(Step::Continue) } (PickMode::Origin, Input::Point(q)) => { @@ -215,6 +263,7 @@ impl Interactive for HatchPickM { .flat_map(|p| match p { Pick::Point(_, l) | Pick::Objects(_, l) => l.iter().cloned(), }) + .chain(self.object_loops.iter().cloned()) .collect(); if loops.is_empty() { return Vec::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index caeda8d7d5..78245627af 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -132,6 +132,16 @@ pub struct Session { lisp_last: Option>, /// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks). pub hatch_picks: Option, + /// Warnings a command shows in a window (a hatch boundary that isn't closed): the UI shows + /// the first one and takes it off when it is closed. + pub notices: Vec, +} + +/// A warning shown in a window ([`Session::notices`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notice { + pub title: String, + pub message: String, } impl Default for Session { @@ -182,6 +192,7 @@ impl Session { lisp: lisp::LispState::default(), lisp_last: None, hatch_picks: None, + notices: Vec::new(), } } @@ -225,6 +236,15 @@ impl Session { } } + /// Show a warning in a window (and on the command line). + pub fn notice(&mut self, title: impl Into, message: impl Into) { + let message = message.into(); + self.echo(message.clone()); + if self.notices.len() < 8 { + self.notices.push(Notice { title: title.into(), message }); + } + } + /// Message on the command line history. pub fn echo(&mut self, msg: impl Into) { let m = msg.into(); @@ -282,6 +302,16 @@ impl Session { Ok(h) } + /// The area of the space being edited shown on screen (the canvas, or the active viewport's + /// model view), or `None` without a drawing. + pub fn view_box(&self) -> Option { + let v = self.state().ok()?.view(); + let h = v.height; + let w = h * self.viewport_px.0.max(1.0) / self.viewport_px.1.max(1.0); + let b = cadcraft_geom::Bounds2::new(v.center - Vec2::new(w, h) * 0.5, v.center + Vec2::new(w, h) * 0.5); + (w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0).then_some(b) + } + /// World units per pixel at the current view. pub fn pixel_size(&self) -> f64 { let v = self.state().map(DocState::view).unwrap_or_default(); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 3350043496..4ee6e6d8ab 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -354,6 +354,11 @@ impl Session { } self.pending_window = None; self.select_mode = None; + // HATCH keeps its boundary objects selected (highlighted) while it runs; they stay + // selected no longer than the command, however it ends. + if matches!(run.id.as_str(), "hatch" | "gradient" | "hatchpick") { + self.set_selection(Vec::new()); + } let label = find_command(&run.id).map(|c| c.label).unwrap_or("Command"); let _ = cancelled; if let Some(m) = cmd::blocks::refedit::after_command(self, &run.before, &run.id) { diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 392ee14002..f295264ebc 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -20,6 +20,35 @@ use serde_json::Value; /// Registered application name of CADCraft's extended data. pub(crate) const APP: &str = "CADCRAFT"; +/// AutoCAD's hatch background colour xdata application (one `1071` colour value). +pub(crate) const HATCH_BACKGROUND_APP: &str = "HATCHBACKGROUNDCOLOR"; + +/// An AutoCAD colour value (`1071`/`420`-style, top byte the method): 0xC2 RGB, 0xC3 an index +/// colour in the low byte, 0xC0 ByLayer, 0xC1 ByBlock; `None` for none or anything else. +pub(crate) fn acad_color(v: i64) -> Option { + let v = v as u32; + match v >> 24 { + 0xC2 => Some(cadcraft_color::Color::True(cadcraft_color::Rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))), + 0xC3 => match (v & 0xFF) as u8 { + 0 => None, + i => Some(cadcraft_color::Color::Index(i)), + }, + 0xC0 => Some(cadcraft_color::Color::ByLayer), + 0xC1 => Some(cadcraft_color::Color::ByBlock), + _ => None, + } +} + +/// [`acad_color`] the other way. +pub(crate) fn acad_color_value(c: cadcraft_color::Color) -> i64 { + let v: u32 = match c { + cadcraft_color::Color::True(cadcraft_color::Rgb(r, g, b)) => 0xC200_0000 | (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b), + cadcraft_color::Color::Index(i) => 0xC300_0000 | u32::from(i), + cadcraft_color::Color::ByLayer => 0xC000_0000, + cadcraft_color::Color::ByBlock => 0xC100_0000, + }; + i64::from(v as i32) +} /// Named-object-dictionary key of the constraint XRECORD. pub(crate) const CONSTRAINTS_KEY: &str = "CADCRAFT_CONSTRAINTS"; /// Named-object-dictionary key of the saved layer states XRECORD. diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index a1103056f5..54a3ac7ba1 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -42,8 +42,9 @@ const MODELLED_KEYS: &[&str] = &[ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"]; /// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides -/// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. -const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; +/// (DSTYLE) on dimensions and dimension styles, `HATCHBACKGROUNDCOLOR` the background of +/// hatches; elsewhere they are kept. +const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD", "CADCRAFTFORMULA"]; /// Most objects kept from one file. const MAX_OBJECTS: usize = 1_000_000; @@ -234,7 +235,11 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { let chunk = rest.get(i..i + 1 + len).unwrap_or(&[]); i += 1 + len; let app = up(&first.str()); - let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE")); + // A hatch's background colour is written from the hatch (none once it is cleared), so a + // kept copy would bring a cleared background back. + let own = OWN_APPS.contains(&app.as_str()) + || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE")) + || (app == crate::dxf_ext::HATCH_BACKGROUND_APP && kind == "HATCH"); if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS { continue; } diff --git a/crates/io/src/dxf_read/hatch.rs b/crates/io/src/dxf_read/hatch.rs index 18fe81531c..6cbe0b7b1c 100644 --- a/crates/io/src/dxf_read/hatch.rs +++ b/crates/io/src/dxf_read/hatch.rs @@ -281,12 +281,21 @@ fn pattern_definition(tags: &[Tag], scale: f64, angle: f64, origin: Vec2) -> Vec fn hatch_xdata(tags: &[Tag]) -> (Vec2, Option) { let x = crate::dxf_ext::xdata(tags, crate::dxf_ext::APP); let Some(at) = x.windows(2).position(|w| matches!(w, [m, o] if m.code == 1000 && m.str() == "HATCH" && o.code == 1011)) else { - return (Vec2::ZERO, None); + return (Vec2::ZERO, acad_background(tags)); }; let val = |k: usize, code: i32| x.get(at + k).filter(|t| t.code == code); let coord = |k: usize, code: i32| val(k, code).map(Tag::f64).filter(|v| v.is_finite()).unwrap_or(0.0); let origin = Vec2::new(coord(1, 1011), coord(2, 1021)); - (origin, val(4, 1000).and_then(|t| Color::parse(&t.str()))) + (origin, val(4, 1000).and_then(|t| Color::parse(&t.str())).or_else(|| acad_background(tags))) +} + +/// The background colour AutoCAD keeps in `HATCHBACKGROUNDCOLOR` xdata (`1071`). +fn acad_background(tags: &[Tag]) -> Option { + crate::dxf_ext::xdata(tags, crate::dxf_ext::HATCH_BACKGROUND_APP) + .iter() + .find(|t| t.code == 1071 || t.code == 1070) + .and_then(|t| t.str().trim().parse::().ok()) + .and_then(crate::dxf_ext::acad_color) } /// Gradient values missing from a file fall back to the GRADIENT command's defaults. diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 6c58cdfacc..4736eaebd3 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -720,4 +720,9 @@ fn hatch_xdata(w: &mut W, h: &Hatch) { w.s(1000, "HATCH"); w.p(1011, h.origin.to3(0.0)); w.s(1000, h.background.map(Color::name).unwrap_or_default()); + // As AutoCAD keeps it, so AutoCAD shows the background too. + if let Some(c) = h.background { + w.s(1001, dxf_ext::HATCH_BACKGROUND_APP); + w.i(1071, dxf_ext::acad_color_value(c)); + } } diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 7198eeee84..20fd84afbd 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -460,7 +460,8 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec) -> EntityKind { + let sq = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]; + EntityKind::Hatch(Hatch { + pattern: "ANSI31".into(), + solid: false, + loops: vec![HatchLoop { vertices: sq.iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(), outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: bg, + pattern_lines: Vec::new(), + }) +} + +#[test] +fn background_colour_round_trips_and_is_written_for_autocad() { + for bg in [Color::Index(3), Color::True(Rgb(250, 240, 10))] { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), hatch(Some(bg))).unwrap(); + let text = cadcraft_io::write_dxf(&d); + assert!(text.contains("HATCHBACKGROUNDCOLOR")); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let h = back.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.background, Some(bg)); + } +} + +#[test] +fn autocads_background_xdata_alone_gives_the_colour() { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), hatch(Some(Color::Index(5)))).unwrap(); + // Without CADCraft's own xdata (a file AutoCAD wrote): only HATCHBACKGROUNDCOLOR is left. + let text = cadcraft_io::write_dxf(&d).replace("1000\r\nHATCH\r\n", "1000\r\nOTHER\r\n").replace("1000\nHATCH\n", "1000\nOTHER\n"); + assert!(text.contains("OTHER"), "CADCraft's own background is out of the way"); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let h = back.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.background, Some(Color::Index(5))); +} + +#[test] +fn a_cleared_background_stays_cleared() { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), hatch(Some(Color::Index(3)))).unwrap(); + let mut back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + let h = back.model.iter().next().unwrap().handle; + back.modify_entity(h, |e| { + if let EntityKind::Hatch(x) = &mut e.kind { + x.background = None; + } + }) + .unwrap(); + let text = cadcraft_io::write_dxf(&back); + // Only the application's registration is left; no hatch carries the colour any more. + let groups = text.lines().map(str::trim).collect::>(); + assert!(!groups.windows(2).any(|w| w[0] == "1001" && w[1] == "HATCHBACKGROUNDCOLOR"), "the old background is not written again"); + let again = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let h = again.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.background, None); +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 5ce0bd6c0f..764141c5fc 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -71,6 +71,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { Some(over) => over, None => lt, }; + let lt = if b.opts.continuous { None } else { lt }; let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12); let lw = if b.opts.lineweights { lw } else { 0.0 }; // Stroke a polyline with the entity's linetype. @@ -340,7 +341,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { /// Draw a polyline with a linetype (None: continuous). pub(crate) fn stroke_with(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, ltscale: f64, pts: &[Vec2]) { - match lt { + match lt.filter(|_| !b.opts.continuous) { Some(lt) => { let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12); for dash in linetype::apply(pts, lt, ltscale, min) { diff --git a/crates/render/src/mline.rs b/crates/render/src/mline.rs index bbaacb5cc7..ba0e9cb624 100644 --- a/crates/render/src/mline.rs +++ b/crates/render/src/mline.rs @@ -59,7 +59,7 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &MLine, rgb: Ink, #[allow(clippy::too_many_arguments)] fn stroke(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, scale: f64, min: f64, pts: &[Vec2]) { - match lt { + match lt.filter(|_| !b.opts.continuous) { Some(lt) => { for dash in linetype::apply(pts, lt, scale, min) { match dash.as_slice() { diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 3427c61a43..9584dabfa7 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -37,6 +37,9 @@ pub struct Options { /// rebuild the view no longer needs). A cancelled build returns a partial list, which the /// caller must discard; see [`Options::cancelled`]. pub cancel: Option>, + /// Draw every curve as one continuous stroke, without its linetype's dashes: the geometry + /// itself, for hatch boundaries and cutting edges taken from what blocks draw. + pub continuous: bool, } impl Options { @@ -60,6 +63,7 @@ impl Default for Options { skip_viewport: None, transparency: false, cancel: None, + continuous: false, } } } diff --git a/crates/ui-egui/src/canvas/list.rs b/crates/ui-egui/src/canvas/list.rs index 0e15fc01e1..cd32f1c790 100644 --- a/crates/ui-egui/src/canvas/list.rs +++ b/crates/ui-egui/src/canvas/list.rs @@ -123,6 +123,7 @@ pub(super) fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], c app.canvas.job = None; let t0 = crate::now_ms(); let opts = cadcraft_render::Options { + continuous: false, tolerance: 2f64.powi(band(px)) * 0.5, // Two pixels at the band's finest zoom: the list serves every zoom in the band, so its // level of detail must hold at the finest one. diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index c96a2bc83b..c28a3f992b 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -125,6 +125,7 @@ pub(super) fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Con // only moves the geometry. let area = rect.expand(rect.width().max(rect.height()) * 0.5); let opts = cadcraft_render::Options { + continuous: false, tolerance: 2f64.powi(band) * 0.5, min_dash: 2f64.powi(band) * 2.0, text: true, diff --git a/crates/ui-egui/src/custom_patterns.rs b/crates/ui-egui/src/custom_patterns.rs new file mode 100644 index 0000000000..7b8b8cdb47 --- /dev/null +++ b/crates/ui-egui/src/custom_patterns.rs @@ -0,0 +1,228 @@ +//! The Hatch and Gradient dialog's Custom Patterns tab: the hatch patterns of the `.pat` files in +//! a folder the user names, listed with a preview of the one selected. +//! +//! The folder is read when it changes or on Reload, not every frame. A pattern used for a hatch is +//! loaded into the session's pattern list from its file when OK is pressed (HATCH.PATTERNS), so +//! the hatch keeps its line families like any pattern loaded from a file. + +use std::cell::RefCell; + +use cadcraft_doc::library::PatternLine; +use cadcraft_doc::library::files::parse_pat; +use egui::{Rect, Sense, Stroke, pos2, vec2}; + +use crate::theme::Tokens; + +/// Most `.pat` files read from the folder, and most patterns listed. +const MAX_FILES: usize = 500; +const MAX_PATTERNS: usize = 5000; +/// Largest `.pat` file read. +const MAX_FILE_BYTES: u64 = 4 << 20; + +/// A pattern found in the folder. +#[derive(Clone, Debug, PartialEq)] +pub struct Found { + /// The `.pat` file it is in. + pub file: String, + pub name: String, + pub description: String, + pub lines: Vec, +} + +/// What the folder held when last read. +#[derive(Clone, Debug, Default)] +struct Listing { + folder: String, + generation: u64, + patterns: std::rc::Rc>, + problem: Option, +} + +thread_local! { + static LISTING: RefCell = RefCell::new(Listing { generation: u64::MAX, ..Listing::default() }); + static GENERATION: RefCell = const { RefCell::new(0) }; +} + +/// Read the folder again on the next frame (files were added or changed). +pub fn reload() { + GENERATION.with(|g| *g.borrow_mut() += 1); +} + +/// The patterns of every `.pat` file in `folder` (not its subfolders), by file then name. +pub fn scan(folder: &str) -> (Vec, Option) { + let dir = folder.trim(); + if dir.is_empty() { + return (Vec::new(), None); + } + let Ok(rd) = std::fs::read_dir(dir) else { + return (Vec::new(), Some(crate::tl!("This folder does not exist").to_string())); + }; + let mut files: Vec = Vec::new(); + for entry in rd.take(MAX_FILES * 20) { + let entry = match entry { + Ok(e) => e, + Err(e) => return (Vec::new(), Some(format!("{}: {e}", crate::tl!("The folder can't be read")))), + }; + // `file_type` does not follow symbolic links: a link to a file elsewhere is not read. + let path = entry.path(); + if entry.file_type().is_ok_and(|t| t.is_file()) && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("pat")) { + files.push(path); + } + } + // The same files every time: sorted, then the first ones kept. + files.sort(); + files.truncate(MAX_FILES); + let mut out = Vec::new(); + for path in files { + if std::fs::metadata(&path).map(|m| m.len()).unwrap_or(u64::MAX) > MAX_FILE_BYTES { + continue; + } + let Ok(bytes) = std::fs::read(&path) else { continue }; + // Pattern files are ASCII, often written in a Windows code page: decode leniently. + let text = String::from_utf8_lossy(&bytes); + for p in parse_pat(&text).items { + if out.len() >= MAX_PATTERNS { + break; + } + out.push(Found { file: path.to_string_lossy().to_string(), name: p.name, description: p.description, lines: p.lines }); + } + } + let problem = out.is_empty().then(|| crate::tl!("No hatch patterns (.pat files) in this folder").to_string()); + (out, problem) +} + +/// The folder's patterns, read again when the folder or the reload count changed. +/// Shared, not copied: the tab asks for it every frame and a folder may hold thousands. +fn listing(folder: &str) -> (std::rc::Rc>, Option) { + let generation = GENERATION.with(|g| *g.borrow()); + LISTING.with(|cell| { + let mut l = cell.borrow_mut(); + if l.folder != folder || l.generation != generation { + let (patterns, problem) = scan(folder); + *l = Listing { folder: folder.to_string(), generation, patterns: std::rc::Rc::new(patterns), problem }; + } + (l.patterns.clone(), l.problem.clone()) + }) +} + +/// Draw a pattern's preview in `r`: its lines over a few repeats, or "SOLID" filled. +pub fn preview(p: &egui::Painter, r: Rect, lines: &[PatternLine]) { + let t = Tokens::get(); + p.rect_filled(r, 3.0, t.field); + let inner = r.shrink(4.0); + let runs = cadcraft_engine::render::pattern_swatch(lines, 1.0); + let at = |v: &cadcraft_engine::geom::Vec2| pos2(inner.min.x + v.x as f32 * inner.width(), inner.max.y - v.y as f32 * inner.height()); + let clip = p.with_clip_rect(inner); + for run in &runs { + match run.as_slice() { + [] => {} + [dot] => { + clip.circle_filled(at(dot), 0.9, t.text); + } + pts => { + clip.add(egui::Shape::line(pts.iter().map(at).collect(), Stroke::new(1.0, t.text))); + } + } + } + p.rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); +} + +/// What the tab asks the dialog to do. +pub enum TabAction { + None, + /// Pick the folder with the system's folder dialog. + Browse, +} + +/// The tab: the folder, the list of its patterns and the preview of the chosen one. A click sets +/// `pattern` and `file`. +pub fn tab_ui(ui: &mut egui::Ui, folder: &mut String, pattern: &mut String, file: &mut Option, can_browse: bool) -> TabAction { + let mut action = TabAction::None; + ui.label(crate::tl!("Folder with hatch pattern files (.pat):")); + ui.horizontal(|ui| { + let w = ui.available_width() - if can_browse { 150.0 } else { 70.0 }; + ui.add(egui::TextEdit::singleline(folder).desired_width(w.max(120.0)).hint_text(crate::tl!("Folder path"))); + if can_browse && ui.button(crate::tl!("Browse...")).clicked() { + action = TabAction::Browse; + } + if ui.button(crate::tl!("Reload")).on_hover_text(crate::tl!("Read the folder again")).clicked() { + reload(); + } + }); + let (found, problem) = listing(folder); + if let Some(p) = &problem { + ui.colored_label(Tokens::get().text_dim, p); + } + ui.add_space(4.0); + let selected = found.iter().find(|f| f.name.eq_ignore_ascii_case(pattern) && file.as_deref() == Some(f.file.as_str())); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(190.0); + egui::Frame::NONE.stroke(Stroke::new(1.0, Tokens::get().border)).inner_margin(2.0).show(ui, |ui| { + egui::ScrollArea::vertical() + .id_salt("custom_patterns_list") + .auto_shrink([false, false]) + .max_height(200.0) + .min_scrolled_height(200.0) + .show(ui, |ui| { + ui.set_width(182.0); + for f in found.iter() { + let on = selected.is_some_and(|s| s.name == f.name && s.file == f.file); + let tip = if f.description.is_empty() { f.file.clone() } else { format!("{}\n{}", f.description, f.file) }; + if ui.selectable_label(on, &f.name).on_hover_text(tip).clicked() { + *pattern = f.name.clone(); + *file = Some(f.file.clone()); + } + } + }); + }); + }); + ui.vertical(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(170.0, 170.0), Sense::hover()); + match selected { + Some(f) => { + preview(ui.painter(), r, &f.lines); + ui.label(egui::RichText::new(&f.name).strong()); + if !f.description.is_empty() { + ui.add(egui::Label::new(egui::RichText::new(&f.description).small()).wrap()); + } + } + None => { + let t = Tokens::get(); + ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, crate::tl!("Preview"), crate::theme::small(), t.text_faint); + } + } + }); + }); + action +} + +#[cfg(test)] +mod tests { + #[test] + fn a_folder_of_pat_files_lists_their_patterns() { + let dir = std::env::temp_dir().join(format!("cadcraft-custom-pat-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("mine.pat"), "*MYLINES, my lines\n0, 0,0, 0,1\n*MYGRID, grid\n0, 0,0, 0,1\n90, 0,0, 0,1\n").unwrap(); + std::fs::write(dir.join("notes.txt"), "not a pattern").unwrap(); + let (found, problem) = super::scan(&dir.to_string_lossy()); + assert!(problem.is_none()); + let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["MYLINES", "MYGRID"]); + assert_eq!(found.get(1).map(|f| f.lines.len()), Some(2)); + let (none, problem) = super::scan(&dir.join("missing").to_string_lossy()); + assert!(none.is_empty() && problem.is_some()); + // A symbolic link to a pattern file elsewhere is not read. + #[cfg(unix)] + { + let outside = std::env::temp_dir().join(format!("cadcraft-outside-{}.pat", std::process::id())); + std::fs::write(&outside, "*OUTSIDE, x\n0, 0,0, 0,1\n").unwrap(); + let _ = std::os::unix::fs::symlink(&outside, dir.join("link.pat")); + let (found, _) = super::scan(&dir.to_string_lossy()); + assert!(!found.iter().any(|f| f.name == "OUTSIDE"), "a link is skipped"); + let _ = std::fs::remove_file(outside); + } + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/ui-egui/src/hatchdlg.rs b/crates/ui-egui/src/hatchdlg.rs index 098395e16e..3f8dc941b6 100644 --- a/crates/ui-egui/src/hatchdlg.rs +++ b/crates/ui-egui/src/hatchdlg.rs @@ -22,6 +22,10 @@ pub(crate) const ORIGIN_MODES: [&str; 5] = ["bottomLeft", "bottomRight", "topRig #[derive(Clone, Debug, PartialEq)] pub struct Fill { pub gradient: bool, + /// The Custom Patterns tab is open (a pattern from a `.pat` file in the user's folder). + pub custom: bool, + /// The `.pat` file of a custom pattern: loaded when OK is pressed. + pub pattern_file: Option, pub pattern: String, pub scale: f64, /// Pattern or gradient angle, degrees. @@ -41,6 +45,8 @@ pub struct Fill { pub associative: bool, /// Island detection: 0 normal, 1 outer, 2 ignore. pub style: u8, + /// Background colour under a pattern (none: the drawing shows through). + pub background: Option, } /// The dialog while open (and while a pick it started runs). @@ -80,6 +86,8 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState { let origin_mode = mode.checked_sub(1).and_then(|i| usize::try_from(i).ok()).and_then(|i| ORIGIN_MODES.get(i)).copied().unwrap_or("bottomLeft"); let fill = Fill { gradient, + custom: false, + pattern_file: None, pattern: h.str("HPNAME", "ANSI31"), scale, angle, @@ -94,6 +102,7 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState { origin_mode: origin_mode.into(), associative: h.i64("HPASSOC", 1) != 0, style: u8::try_from(h.i64("HPISLANDDETECTION", 0).clamp(0, 2)).unwrap_or(0), + background: None, }; HatchDlgState { opened: fill.clone(), @@ -128,6 +137,7 @@ pub fn edit_state(d: &Drawing, uid: u64, handles: Vec) -> Option Option<(&'static str, Value)> { p.insert("associative".into(), json!(f.associative)); p.insert("separate".into(), json!(st.separate)); p.insert("style".into(), json!(style_name(f.style))); + if let (Some(c), false) = (f.background, f.gradient) { + p.insert("background".into(), json!(c.name())); + } match (f.specified, f.origin) { (true, Some(o)) => p.insert("origin".into(), json!(o)), (true, None) => p.insert("originMode".into(), json!(f.origin_mode)), @@ -244,6 +257,9 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> { if f.style != o.style { p.insert("style".into(), json!(style_name(f.style))); } + if f.background != o.background && !f.gradient { + p.insert("background".into(), json!(f.background.map_or_else(|| "None".to_string(), |c| c.name()))); + } if f.specified { match f.origin { Some(q) => p.insert("origin".into(), json!(q)), @@ -365,6 +381,16 @@ pub fn resume(app: &mut CadApp) { /// OK: run the dialog's command. True when the dialog closes; a failed command keeps it open /// with the error (the drawing is unchanged). pub fn ok(app: &mut CadApp) -> bool { + // A custom pattern joins the pattern list from its file first. + let file = app.hatch_dlg.as_ref().filter(|st| st.fill.custom && !st.fill.gradient).and_then(|st| st.fill.pattern_file.clone()); + if let Some(file) = file + && let Err(e) = app.run("hatch.patterns", json!({ "file": file })) + { + if let Some(st) = app.hatch_dlg.as_mut() { + st.error = Some(e); + } + return false; + } let Some(call) = app.hatch_dlg.as_ref().map(ok_call) else { return true }; let Some((cmd, p)) = call else { app.hatch_dlg = None; @@ -389,6 +415,68 @@ enum Action { Ok, Cancel, Pick(PickMode), + /// Choose the Custom Patterns folder. + BrowseFolder, +} + +/// The hatch background colour picker: None, ByLayer/ByBlock, the standard colours and any +/// colour; the choice as HATCH takes it (a colour name or `"None"`). +pub fn background_menu(ui: &mut egui::Ui, current: Option) -> Option { + let shown = match current { + None => crate::tl!("None").to_string(), + Some(c) => crate::i18n::t(&c.name()).to_string(), + }; + let mut out = None; + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover()); + match current { + Some(c) => { + let rgb = c.resolve(Color::Index(7), Color::Index(7)); + ui.painter().rect_filled(r, 2.0, egui::Color32::from_rgb(rgb.0, rgb.1, rgb.2)); + } + None => { + ui.painter().rect_stroke(r, 2.0, egui::Stroke::new(1.0, crate::theme::Tokens::get().text_dim), egui::StrokeKind::Inside); + } + } + ui.menu_button(shown, |ui| { + if ui.button(crate::tl!("None")).clicked() { + out = Some("None".to_string()); + ui.close(); + } + ui.separator(); + for (n, c) in [ + ("ByLayer", Color::ByLayer), + ("ByBlock", Color::ByBlock), + ("Red", Color::Index(1)), + ("Yellow", Color::Index(2)), + ("Green", Color::Index(3)), + ("Cyan", Color::Index(4)), + ("Blue", Color::Index(5)), + ("Magenta", Color::Index(6)), + ("White", Color::Index(7)), + ("Color 8", Color::Index(8)), + ("Color 9", Color::Index(9)), + ] { + if ui.button(crate::i18n::t(n)).clicked() { + out = Some(c.name()); + ui.close(); + } + } + ui.separator(); + // Any colour. + let mut rgb = match current { + Some(Color::True(c)) => [c.0, c.1, c.2], + _ => [255, 255, 255], + }; + ui.horizontal(|ui| { + ui.label(crate::tl!("Other color")); + if ui.color_edit_button_srgb(&mut rgb).changed() { + out = Some(Color::True(cadcraft_color::Rgb(rgb[0], rgb[1], rgb[2])).name()); + } + }); + }); + }); + out } fn shape_label(name: &str) -> &'static str { @@ -430,11 +518,13 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }; let title = if st.edit.is_empty() { crate::tl!("Hatch and Gradient") } else { crate::tl!("Hatch Edit") }; let mut action = Action::None; + let mut folder = app.ui.pattern_folder.clone(); + let can_browse = app.services.pick_folder.is_some(); egui::Window::new(title).id(egui::Id::unique("hatch_dialog")).open(open).collapsible(false).resizable(false).show(ctx, |ui| { ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(340.0); - fill_ui(ui, &mut st.fill, &mut action); + ui.set_width(if st.fill.custom { 400.0 } else { 340.0 }); + fill_ui(ui, &mut st.fill, &mut action, &mut folder, can_browse); }); // Space, not a vertical separator: a separator takes the height available, and the // window grew by it every frame until the buttons left the screen. @@ -459,6 +549,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }); }); app.hatch_dlg = Some(st); + app.ui.pattern_folder = folder; match action { Action::Ok => { if ok(app) { @@ -470,6 +561,12 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { *open = false; } Action::Pick(mode) => start_pick(app, mode), + Action::BrowseFolder => { + if let Some(dir) = app.services.pick_folder.as_ref().and_then(|pick| pick()) { + app.ui.pattern_folder = dir; + crate::custom_patterns::reload(); + } + } Action::None => { if !*open { app.hatch_dlg = None; @@ -478,14 +575,39 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } } -/// Pattern/gradient fill selector and its controls; an origin pick is reported through `action`. -fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) { +/// Pattern/gradient/custom-pattern fill selector and its controls; an origin pick or a folder +/// browse is reported through `action`. +fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action, folder: &mut String, can_browse: bool) { ui.horizontal(|ui| { - ui.selectable_value(&mut f.gradient, false, crate::tl!("Pattern")); - ui.selectable_value(&mut f.gradient, true, crate::tl!("Gradient")); + if ui.selectable_label(!f.gradient && !f.custom, crate::tl!("Pattern")).clicked() { + f.gradient = false; + f.custom = false; + } + if ui.selectable_label(f.gradient, crate::tl!("Gradient")).clicked() { + f.gradient = true; + f.custom = false; + } + if ui.selectable_label(!f.gradient && f.custom, crate::tl!("Custom Patterns")).clicked() { + f.gradient = false; + f.custom = true; + } }); ui.separator(); - if f.gradient { + if f.custom && !f.gradient { + if let crate::custom_patterns::TabAction::Browse = crate::custom_patterns::tab_ui(ui, folder, &mut f.pattern, &mut f.pattern_file, can_browse) + { + *action = Action::BrowseFolder; + } + ui.add_space(4.0); + egui::Grid::new("hatch_custom_pattern").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { + ui.label(crate::tl!("Angle")); + ui.add(egui::DragValue::new(&mut f.angle).speed(1.0).range(-360.0..=360.0).clamp_existing_to_range(false).suffix("°")); + ui.end_row(); + ui.label(crate::tl!("Scale")); + ui.add(egui::DragValue::new(&mut f.scale).speed(0.05).range(0.0001..=1.0e6).clamp_existing_to_range(false)); + ui.end_row(); + }); + } else if f.gradient { egui::Grid::new("hatch_gradient").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { ui.label(crate::tl!("Color 1")); if let Some(c) = crate::layers::color_button(ui, egui::Id::unique("hatch_color1"), f.color1, false, 160.0) { @@ -594,6 +716,14 @@ fn options_ui(ui: &mut egui::Ui, st: &mut HatchDlgState, action: &mut Action) { if st.edit.is_empty() { ui.checkbox(&mut st.separate, crate::tl!("Create separate hatches")); } + if !st.fill.gradient { + ui.horizontal(|ui| { + ui.label(crate::tl!("Background color")); + if let Some(v) = background_menu(ui, st.fill.background) { + st.fill.background = if v == "None" { None } else { Color::parse(&v) }; + } + }); + } ui.label(crate::tl!("Island detection")); ui.radio_value(&mut st.fill.style, 0, crate::tl!("Normal")); ui.radio_value(&mut st.fill.style, 1, crate::tl!("Outer")); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 017cf5a42a..92bc560609 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -21,6 +21,7 @@ pub mod cmdline; pub mod context_menu; pub mod control; pub mod credits; +pub mod custom_patterns; pub mod dialogs; pub mod docking; pub mod hatchdlg; @@ -40,6 +41,7 @@ pub mod layers; pub mod managers; pub mod menus; pub mod modal; +pub mod notices; pub mod opening; pub mod options; pub mod palettes; @@ -93,6 +95,8 @@ pub struct UiState { /// "Drafting" or "Modeling". pub toolset_tab: String, pub collapsed_groups: Vec, + /// The folder the Hatch and Gradient dialog's Custom Patterns tab lists `.pat` files from. + pub pattern_folder: String, /// Tools the user took out of the Tool Sets palette (command ids); each category's gear /// menu puts them back. pub hidden_tools: Vec, @@ -176,6 +180,7 @@ impl Default for UiState { system_cursor: std::env::var("CADCRAFT_SYSTEM_CURSOR").is_ok_and(|v| !matches!(v.trim(), "" | "0" | "false" | "off")), toolset_tab: "Drafting".into(), collapsed_groups: Vec::new(), + pattern_folder: String::new(), hidden_tools: Vec::new(), properties_all: true, in_window_menu: !cfg!(target_os = "macos"), @@ -197,6 +202,8 @@ impl Default for UiState { pub struct Services { pub pick_open: Option Option>>, pub pick_save: Option Option>>, + /// Pick a folder (the Custom Patterns folder); `None` where the host has no folder dialog. + pub pick_folder: Option Option>>, /// Pick a `.lsp` file for APPLOAD, starting in the given folder (empty for the default one). /// `None` where there is no native file dialog: the desktop without one asks for the name, /// and the web (no file system) says to drop the file (`no_file_system`). @@ -845,6 +852,7 @@ impl CadApp { closing::prompt(self, ui.ctx()); autosave::show(self, ui.ctx()); autosave::gpu_notice(self, ui.ctx()); + notices::show(self, ui.ctx()); self.frame_ms = now_ms() - t0; } diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs new file mode 100644 index 0000000000..7af5e454cb --- /dev/null +++ b/crates/ui-egui/src/notices.rs @@ -0,0 +1,51 @@ +//! Warnings commands show in a window ([`cadcraft_engine::Session::notices`]): a hatch boundary +//! that isn't closed, selected objects that don't enclose an area. The first one shows until OK +//! closes it; the keys stay with the command line. + +use egui::vec2; + +use crate::CadApp; +use crate::theme::Tokens; + +pub fn show(app: &mut CadApp, ctx: &egui::Context) { + let Some(n) = app.session.notices.first().cloned() else { return }; + let t = Tokens::get(); + let mut close = false; + egui::Window::new(crate::i18n::t(&n.title)) + .id(egui::Id::unique("cc_notice")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, -60.0)) + .show(ctx, |ui| { + ui.set_width(420.0); + ui.horizontal(|ui| { + // A warning triangle with an exclamation mark. + let (r, _) = ui.allocate_exact_size(vec2(30.0, 28.0), egui::Sense::hover()); + let p = ui.painter(); + let pts = vec![ + egui::pos2(r.center().x, r.top() + 1.0), + egui::pos2(r.right() - 1.0, r.bottom() - 1.0), + egui::pos2(r.left() + 1.0, r.bottom() - 1.0), + ]; + p.add(egui::Shape::convex_polygon(pts, t.warning, egui::Stroke::NONE)); + p.text( + egui::pos2(r.center().x, r.center().y + 3.0), + egui::Align2::CENTER_CENTER, + "!", + egui::FontId::proportional(17.0), + egui::Color32::BLACK, + ); + ui.add_space(6.0); + ui.add(egui::Label::new(crate::i18n::t(&n.message)).wrap()); + }); + ui.add_space(6.0); + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("OK")).clicked() { + close = true; + } + }); + }); + if close { + app.session.notices.remove(0); + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9aeac31a10..07588336e7 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -94,6 +94,8 @@ pub struct Tokens { /// Grips of dynamic block references (AutoCAD's GRIPDYNCOLOR). pub grip_dyn: Color32, pub snap: Color32, + /// The warning sign of notice windows. + pub warning: Color32, /// COMPARE: objects only in this drawing, only in the other one, and the areas of change. pub compare_this: Color32, pub compare_other: Color32, @@ -153,6 +155,7 @@ impl Tokens { grip_hot: Color32::from_rgb(0xff, 0x3b, 0x3b), grip_dyn: Color32::from_rgb(0x26, 0xc6, 0xe8), snap: Color32::from_rgb(0x2f, 0xd0, 0x62), + warning: Color32::from_rgb(0xf2, 0xb2, 0x33), compare_this: Color32::from_rgb(0x4c, 0xd9, 0x7b), compare_other: Color32::from_rgb(0xff, 0x5c, 0x5c), compare_area: Color32::from_rgb(0xff, 0xb4, 0x3c), From 453f62c678ee175382529be433c68bc964959cf5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:41:10 +0200 Subject: [PATCH 03/30] TRIM/EXTEND: hover glow, trimming hatches, blocks as edges Split out of #2034. Builds on the HATCH part (continuous block outlines). - Interactive::glow / Glow: TRIM shows in red what a pick cuts away, EXTEND in blue what it adds, before the pick (under the panic guard). - TRIM on a hatch takes the picked part of the area out (trim_hatch.rs); the hatch stays behind the lines. - Block references cut and bound by what they draw; cutting edges are looked for around the trimmed object only. - Pre-selected objects are the cutting edges and stay highlighted; a pick in empty space starts a fence; edges are deselected at the end. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/hatch.rs | 14 + crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/trim.rs | 117 ++++-- crates/engine/src/cmd/trim_hatch.rs | 345 ++++++++++++++++++ crates/engine/src/cmd/trimextend.rs | 242 +++++++++++- crates/engine/src/guard.rs | 9 + crates/engine/src/lib.rs | 2 +- crates/engine/src/prompt.rs | 13 + crates/engine/src/session/interactive.rs | 18 +- crates/engine/tests/it/trim_extend_options.rs | 145 ++++++++ crates/ui-egui/src/canvas.rs | 25 ++ 12 files changed, 889 insertions(+), 44 deletions(-) create mode 100644 crates/engine/src/cmd/trim_hatch.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 1856c6a150..802701c56c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -40,6 +40,7 @@ mod settings; mod spline_opts; mod table; mod tolerance; +mod trim_hatch; mod trimextend; mod txt2mtxt; pub use txt2mtxt::Txt2MtxtOptions; diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 14ccdbd5ed..8d29328db9 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -1039,6 +1039,20 @@ mod tests { use super::*; + /// A trimmed hatch stays behind the lines it touches (#2034 review). + #[test] + fn a_trimmed_hatch_stays_at_the_back() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap(); + let (h, _) = only_hatch(&s); + let l = s.execute("line", &json!({ "points": [[4, -1], [4, 11]] })).unwrap(); + let l = l["handles"][0].as_str().unwrap().to_string(); + s.execute("trim", &json!({ "handle": h, "pick": [2, 5], "edges": [l] })).unwrap(); + let first = s.doc().unwrap().model.iter().next().map(|e| matches!(e.kind, EntityKind::Hatch(_))); + assert_eq!(first, Some(true), "the trimmed hatch is drawn first, under the lines"); + } + /// A background that is not a colour is an error, not a quiet "no background" (#2034 review). #[test] fn a_bad_background_is_refused() { diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index bbcd25267e..a67d4bf5ee 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -34,7 +34,7 @@ use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; pub(crate) use transform::transform_entities; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; -pub(crate) use trim::{Edges, extend, trim}; +pub(crate) use trim::{Edges, edge_segments_owned, extend, extend_result, prim_to_segments, trim, trim_edges, trim_result}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 4caaadfb60..a326e75260 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -13,13 +13,43 @@ pub(crate) struct Edges<'a> { } /// All primitives of the cutting edges (excluding `exclude`). -fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result> { +pub(crate) fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result> { + Ok(edge_segments_owned(s, edges, None)?.into_iter().filter(|(h, _)| *h != exclude).map(|(_, sg)| sg).collect()) +} + +/// The cutting edges a trim of `h` can meet: only the objects reaching its extents (all of them +/// with implied edges, which run on without end). +pub(crate) fn trim_edges(s: &Session, edges: Edges, h: Handle) -> Result> { + let d = s.doc()?; + let near = d.entity(h).map(|e| { + let b = cadcraft_doc::entity_bounds(d, e, 0); + b.expand((b.width() + b.height()) * 0.01 + 1e-6) + }); + Ok(edge_segments_owned(s, edges, near)?.into_iter().filter(|(o, _)| *o != h).map(|(_, sg)| sg).collect()) +} + +/// [`edge_segments`] of every edge object (only those reaching `near` when given), each with +/// the object it comes from. +pub(crate) fn edge_segments_owned(s: &Session, edges: Edges, near: Option) -> Result> { let d = s.doc()?; let space = s.space(); let store = d.space(&space).ok_or(EngineError::NoDocument)?; + let ix = near.filter(|n| !edges.implied && !n.is_empty()).and_then(|_| crate::spatial::index(d, &space)); + let picked: Option>> = match (&ix, near) { + (Some(ix), Some(n)) => ix.query(&n, true).map(|v| v.into_iter().filter_map(|i| ix.entity(i).cloned()).collect()), + _ => None, + }; + let all: Vec>; + let ents: &[std::sync::Arc] = match &picked { + Some(v) => v, + None => { + all = store.iter().cloned().collect(); + &all + } + }; let mut out = Vec::new(); - for e in store.iter() { - if e.handle == exclude || !d.is_visible(e) { + for e in ents { + if !d.is_visible(e) { continue; } if let Some(es) = edges.only @@ -30,11 +60,26 @@ fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result Option> { } } -fn prim_to_segments(p: &Prim) -> Vec { +pub(crate) fn prim_to_segments(p: &Prim) -> Vec { match p { Prim::Seg(s) => vec![*s], Prim::Circle(c) => vec![Segment::Arc { arc: Arc { center: c.center, radius: c.radius, start: 0.0, end: TAU - 1e-12 }, ccw: true }], @@ -93,8 +138,32 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu if crate::cmd::curves::is_locked(s, h) { return Err(EngineError::Other("The object is on a locked layer.".into())); } + let cut = trim_edges(s, edges, h)?; + let (e, pieces) = trim_result(s, h, pick, &cut)?; + let common = e.common.clone(); + let space = s.space(); + let d = s.doc_mut()?; + d.remove_entity(h); + let mut out = Vec::new(); + for k in pieces { + let nh = d.new_handle(); + // A hatch goes behind the lines again, as a new hatch does. + let hatch = matches!(k, EntityKind::Hatch(_)); + if let Some(st) = d.space_mut(&space) { + st.push(Entity { handle: nh, common: common.clone(), kind: k }); + if hatch { + st.send_to_back(nh); + } + out.push(nh); + } + } + Ok(out) +} + +/// What trimming `h` at `pick` against the cutting edges `cut` leaves: the object and the +/// pieces that replace it (the drawing is not changed). +pub(crate) fn trim_result(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) -> Result<(Entity, Vec)> { let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; - let cut = edge_segments(s, edges, h)?; let pieces: Vec = match &e.kind { EntityKind::Line(l) => { let ln = Line::new(l.a.xy(), l.b.xy()); @@ -164,22 +233,11 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu } keep.into_iter().collect() } - EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?, - k => crate::cmd::modify2::trim_other(k, &cut, pick)?, + EntityKind::LwPolyline(p) => trim_polyline(p, cut, pick)?, + EntityKind::Hatch(hatch) => crate::cmd::trim_hatch::trim_hatch(hatch, cut, pick)?.0.into_iter().collect(), + k => crate::cmd::modify2::trim_other(k, cut, pick)?, }; - let common = e.common.clone(); - let space = s.space(); - let d = s.doc_mut()?; - d.remove_entity(h); - let mut out = Vec::new(); - for k in pieces { - let nh = d.new_handle(); - if let Some(st) = d.space_mut(&space) { - st.push(Entity { handle: nh, common: common.clone(), kind: k }); - out.push(nh); - } - } - Ok(out) + Ok((e, pieces)) } /// Sub-polyline between length parameters `a` and `b` (open polylines). @@ -285,8 +343,16 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re if crate::cmd::curves::is_locked(s, h) { return Err(EngineError::Other("The object is on a locked layer.".into())); } - let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let cut = edge_segments(s, edges, h)?; + let new_kind = extend_result(s, h, pick, &cut)?.1; + s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?; + Ok(()) +} + +/// What extending `h` at `pick` to the boundary edges `cut` makes of it: the object and its +/// new geometry (the drawing is not changed). +pub(crate) fn extend_result(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) -> Result<(Entity, EntityKind)> { + let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let new_kind = match &e.kind { EntityKind::Line(l) => { let (a, b) = (l.a.xy(), l.b.xy()); @@ -336,8 +402,7 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re } lwpoly(vs, false) } - k => crate::cmd::modify2::extend_other(k, &cut, pick)?, + k => crate::cmd::modify2::extend_other(k, cut, pick)?, }; - s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?; - Ok(()) + Ok((e, new_kind)) } diff --git a/crates/engine/src/cmd/trim_hatch.rs b/crates/engine/src/cmd/trim_hatch.rs new file mode 100644 index 0000000000..4d04fac586 --- /dev/null +++ b/crates/engine/src/cmd/trim_hatch.rs @@ -0,0 +1,345 @@ +//! TRIM on a hatch: the cutting edges divide the hatched area, and the part picked is taken out +//! of it. The area left is traced again as boundary loops (arcs in the boundary become short +//! lines), and the hatch stops being associative, as AutoCAD's does. + +use cadcraft_doc::{EntityKind, Hatch, HatchLoop}; +use cadcraft_geom::{Bounds2, Line, PolyVertex, Segment, Vec2, point_in_polygon, region}; + +use crate::{EngineError, Result}; + +/// Most cutting-edge points taken into the area tracing (hostile drawings). +const MAX_CUT_POINTS: usize = 200_000; +/// Most boundary edges handled. +const MAX_EDGES: usize = 200_000; + +fn no_cut() -> EngineError { + EngineError::Other("Object does not intersect a cutting edge.".into()) +} + +/// Closed polygon edges as (a, b) pairs. +fn edges_of(poly: &[Vec2]) -> Vec<(Vec2, Vec2)> { + let n = poly.len(); + if n < 2 { + return Vec::new(); + } + (0..n).filter_map(|i| Some((*poly.get(i)?, *poly.get((i + 1) % n)?))).filter(|(a, b)| a.dist(*b) > 0.0).collect() +} + +/// Split the edge a→b at the points of `pts` lying on it (within `tol`). +fn split_at(a: Vec2, b: Vec2, pts: &[Vec2], tol: f64, out: &mut Vec<(Vec2, Vec2)>) { + let ln = Line::new(a, b); + let len = a.dist(b); + let mut ts: Vec = + pts.iter().filter(|p| ln.dist(**p) <= tol).map(|p| ln.param_of(*p)).filter(|t| *t * len > tol && (1.0 - *t) * len > tol).collect(); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|x, y| (*x - *y).abs() * len <= tol); + let mut prev = a; + for t in ts { + let q = ln.at(t); + out.push((prev, q)); + prev = q; + } + out.push((prev, b)); +} + +/// A face's outline without the dangling curves it runs out along and back (A→B→A). +fn despike(mut poly: Vec, tol: f64) -> Vec { + let mut changed = true; + while changed && poly.len() >= 3 { + changed = false; + let n = poly.len(); + for i in 0..n { + let (Some(prev), Some(next)) = (poly.get((i + n - 1) % n), poly.get((i + 1) % n)) else { continue }; + if prev.near(*next, tol) { + // Drop the tip and one of the two equal neighbours. + let (a, b) = if (i + 1) % n > i { (i, i + 1) } else { (0, i) }; + poly.remove(b); + poly.remove(a); + changed = true; + break; + } + } + } + poly +} + +/// Chain directed edges into closed loops (start of one = end of the last). +fn chain(mut edges: Vec<(Vec2, Vec2)>, tol: f64) -> Vec> { + let mut loops = Vec::new(); + while let Some((a, b)) = edges.pop() { + let mut pts = vec![a]; + let mut end = b; + let mut guard = 0usize; + while !end.near(a, tol) && guard < MAX_EDGES { + guard += 1; + let Some(i) = edges.iter().position(|(p, _)| p.near(end, tol)) else { break }; + let (p, q) = edges.swap_remove(i); + pts.push(p); + end = q; + } + if end.near(a, tol) && pts.len() >= 3 { + loops.push(pts); + } + } + loops +} + +/// Trim the hatch at `pick` against the cutting edges `cut`: the hatch that is left (`None`: none +/// of its area is) and the outline of the part taken away (its outer loop, then its islands). +pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Option, Vec>)> { + // The exact extents, arcs included: a circle kept as two half-circle arcs is as tall as it is + // wide, not the flat sliver its chords make. + let bounds = Bounds2::from_points( + h.loops + .iter() + .map(|l| cadcraft_geom::Polyline { vertices: l.vertices.clone(), closed: true }.bounds()) + .flat_map(|b| [b.min, b.max]) + .filter(|p| p.is_finite()), + ); + let size = bounds.width().hypot(bounds.height()); + if !size.is_finite() || size <= 0.0 { + return Err(EngineError::Other("Cannot trim that object.".into())); + } + let tess = size * 2e-4; + let tol = size * 1e-9; + let mut loops = cadcraft_render::hatch_fill_loops(h, tess); + for l in &mut loops { + if l.len() > 1 && l.first().zip(l.last()).is_some_and(|(f, z)| f.near(*z, tol)) { + l.pop(); + } + } + let in_hatch = |p: Vec2| loops.iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1; + // A pick on the hatch's edge (the hatch is picked along its boundary too) trims the part + // just inside it. + let pick = if in_hatch(pick) { + pick + } else { + [1e-3, 3e-3, 1e-2, 3e-2] + .iter() + .flat_map(|r| (0..16).map(move |k| Vec2::polar(pick, size * r, std::f64::consts::TAU * f64::from(k) / 16.0))) + .find(|q| in_hatch(*q)) + .ok_or_else(|| EngineError::Other("Pick the hatch inside its area.".into()))? + }; + // The cutting edges near the hatch, as polylines. + let near = bounds.expand(size * 0.01); + let mut cuts: Vec> = Vec::new(); + let mut n = 0usize; + for c in cut { + let mut pts = Vec::new(); + c.tessellate(tess, &mut pts); + let cb = Bounds2::from_points(pts.iter().copied()); + if !cb.intersects(&near) { + continue; + } + n += pts.len(); + if n > MAX_CUT_POINTS { + return Err(EngineError::Other("Too many cutting edges near the hatch.".into())); + } + cuts.push(pts); + } + let mut polys: Vec> = loops + .iter() + .map(|l| { + let mut c = l.clone(); + c.extend(l.first().copied()); + c + }) + .collect(); + polys.extend(cuts); + let b = region::boundary_at(&polys, pick, tol.max(size * 1e-7)) + .ok_or_else(|| EngineError::Other("Could not work out the part of the hatch to trim.".into()))?; + let snap = size * 1e-7; + let face: Vec> = std::iter::once(b.outer.clone()) + .chain(b.islands.iter().map(|i| i.outline.clone())) + .map(|l| despike(l, snap)) + .filter(|l| l.len() >= 3) + .collect(); + let Some(outer) = face.first().cloned() else { return Err(no_cut()) }; + let in_face = |p: Vec2| point_in_polygon(&outer, p) && !face.iter().skip(1).any(|i| point_in_polygon(i, p)); + // A face made of the hatch's own boundary only: no cutting edge crosses this area. + let on_hatch = |a: Vec2, z: Vec2| { + let m = (a + z) * 0.5; + loops.iter().any(|l| edges_of(l).iter().any(|(p, q)| Line::new(*p, *q).dist(m) <= snap * 10.0)) + }; + if face.iter().all(|f| edges_of(f).iter().all(|(a, z)| on_hatch(*a, *z))) { + return Err(no_cut()); + } + // Every candidate edge: the hatch's loops split where the face's corners touch them, and the + // face's own edges. + let corners: Vec = face.iter().flatten().copied().collect(); + let mut cand: Vec<(Vec2, Vec2)> = Vec::new(); + for l in &loops { + for (a, z) in edges_of(l) { + split_at(a, z, &corners, snap, &mut cand); + if cand.len() > MAX_EDGES { + return Err(EngineError::Other("The hatch is too complex to trim.".into())); + } + } + } + cand.extend(face.iter().flat_map(|f| edges_of(f))); + // Keep the edges with the area left on exactly one side, turned to have it on the left. + let off = size * 1e-6; + let left_over = |p: Vec2| in_hatch(p) && !in_face(p); + let mut kept: Vec<(Vec2, Vec2)> = Vec::new(); + for (a, z) in cand { + let d = (z - a).normalized(); + let m = (a + z) * 0.5; + let nrm = Vec2::new(-d.y, d.x) * off; + let (l, r) = (left_over(m + nrm), left_over(m - nrm)); + if l == r { + continue; + } + let e = if l { (a, z) } else { (z, a) }; + // The same piece of boundary twice (a loop edge that is also a face edge). + if kept.iter().any(|(p, q)| p.near(e.0, snap) && q.near(e.1, snap)) { + continue; + } + kept.push(e); + } + let outlines = chain(kept, snap * 10.0); + if outlines.is_empty() { + return Ok((None, face)); + } + let depth = |i: usize, l: &[Vec2]| { + let Some(p) = l.first().zip(l.get(1)).map(|(a, z)| (*a + *z) * 0.5) else { return 0 }; + outlines.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count() + }; + let new_loops: Vec = outlines + .iter() + .enumerate() + .map(|(i, l)| HatchLoop { vertices: l.iter().map(|p| PolyVertex::new(*p)).collect(), outer: depth(i, l) == 0, sources: Vec::new() }) + .collect(); + let out = Hatch { loops: new_loops, associative: false, style: 0, ..h.clone() }; + Ok((Some(EntityKind::Hatch(out)), face)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(lo: f64, hi: f64) -> HatchLoop { + let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(); + HatchLoop { vertices, outer: true, sources: Vec::new() } + } + + fn hatch(loops: Vec) -> Hatch { + Hatch { + pattern: "SOLID".into(), + solid: true, + loops, + scale: 1.0, + angle: 0.0, + associative: true, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + } + } + + fn area(k: &EntityKind) -> f64 { + let EntityKind::Hatch(h) = k else { return f64::NAN }; + let ls = cadcraft_render::hatch_fill_loops(h, 1e-3); + // Odd-parity area by sampling. + let mut n = 0; + for i in 0..200 { + for j in 0..200 { + let p = Vec2::new(-1.0 + i as f64 * 0.06 + 0.03, -1.0 + j as f64 * 0.06 + 0.03); + if ls.iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1 { + n += 1; + } + } + } + f64::from(n) * 0.06 * 0.06 + } + + #[test] + fn a_line_across_a_hatch_trims_the_picked_half() { + let h = hatch(vec![square(0.0, 10.0)]); + let cut = [Segment::Line(Line::new(Vec2::new(4.0, -5.0), Vec2::new(4.0, 15.0)))]; + let (left, face) = trim_hatch(&h, &cut, Vec2::new(2.0, 5.0)).unwrap(); + let left = left.unwrap(); + assert!((area(&left) - 60.0).abs() < 1.0, "{}", area(&left)); + let EntityKind::Hatch(lh) = &left else { panic!() }; + assert!(!lh.associative); + assert!(face.first().is_some_and(|f| f.iter().all(|p| p.x <= 4.0 + 1e-6))); + } + + /// A round hatch kept as two half-circle arcs (bulge 1): a line across its top is found as a + /// cutting edge and only the cap above it is taken away (#2034 review). + #[test] + fn a_line_across_a_circular_hatch_trims_the_cap() { + let circle = HatchLoop { + vertices: vec![ + PolyVertex { p: Vec2::new(10.0, 0.0), bulge: 1.0, ..PolyVertex::new(Vec2::ZERO) }, + PolyVertex { p: Vec2::new(-10.0, 0.0), bulge: 1.0, ..PolyVertex::new(Vec2::ZERO) }, + ], + outer: true, + sources: Vec::new(), + }; + let h = hatch(vec![circle]); + let cut = [Segment::Line(Line::new(Vec2::new(-20.0, 5.0), Vec2::new(20.0, 5.0)))]; + let (left, _) = trim_hatch(&h, &cut, Vec2::new(0.0, 8.0)).unwrap(); + let Some(EntityKind::Hatch(left)) = left else { panic!("the hatch below the line is left") }; + let pts: Vec = cadcraft_render::hatch_fill_loops(&left, 1e-2).into_iter().flatten().collect(); + let top = pts.iter().map(|p| p.y).fold(f64::MIN, f64::max); + let bottom = pts.iter().map(|p| p.y).fold(f64::MAX, f64::min); + assert!((top - 5.0).abs() < 1e-3, "the cap above y=5 is gone: top {top}"); + assert!((bottom + 10.0).abs() < 0.05, "the rest stays: bottom {bottom}"); + } + + #[test] + fn a_hole_cut_out_of_a_hatch() { + let h = hatch(vec![square(0.0, 10.0)]); + // A closed square of cutting edges inside the hatch: picking inside it takes it out. + let c = [(3.0, 3.0), (6.0, 3.0), (6.0, 6.0), (3.0, 6.0), (3.0, 3.0)]; + let cut: Vec = c.windows(2).map(|w| Segment::Line(Line::new(Vec2::new(w[0].0, w[0].1), Vec2::new(w[1].0, w[1].1)))).collect(); + let (left, _) = trim_hatch(&h, &cut, Vec2::new(4.5, 4.5)).unwrap(); + assert!((area(&left.unwrap()) - 91.0).abs() < 1.0); + } + + #[test] + fn no_cutting_edge_no_trim() { + let h = hatch(vec![square(0.0, 10.0)]); + let cut = [Segment::Line(Line::new(Vec2::new(20.0, 0.0), Vec2::new(20.0, 10.0)))]; + assert!(trim_hatch(&h, &cut, Vec2::new(5.0, 5.0)).is_err()); + } + + #[test] + fn hostile_hatches_do_not_panic() { + let h = hatch(vec![HatchLoop { vertices: vec![PolyVertex::new(Vec2::new(f64::NAN, 0.0))], outer: true, sources: Vec::new() }]); + let _ = trim_hatch(&h, &[], Vec2::ZERO); + let h = hatch(Vec::new()); + let _ = trim_hatch(&h, &[], Vec2::ZERO); + } + + #[test] + fn walls_along_the_hatch_boundary_do_not_stop_the_trim() { + // The hatch fills a room whose walls run along its boundary and past its corners; a + // line crosses the room. + let h = hatch(vec![square(0.0, 10.0)]); + let l = |a: (f64, f64), b: (f64, f64)| Segment::Line(Line::new(Vec2::new(a.0, a.1), Vec2::new(b.0, b.1))); + let cut = [ + l((-5.0, 0.0), (15.0, 0.0)), + l((10.0, -5.0), (10.0, 15.0)), + l((15.0, 10.0), (-5.0, 10.0)), + l((0.0, 15.0), (0.0, -5.0)), + // A wall piece covering part of an edge only. + l((2.0, 0.0), (6.0, 0.0)), + l((4.0, -5.0), (4.0, 15.0)), + ]; + let (left, _) = trim_hatch(&h, &cut, Vec2::new(2.0, 5.0)).unwrap(); + assert!((area(&left.unwrap()) - 60.0).abs() < 1.0); + } + + #[test] + fn a_pick_on_the_hatch_edge_trims_the_part_inside() { + let h = hatch(vec![square(0.0, 10.0)]); + let cut = [Segment::Line(Line::new(Vec2::new(4.0, -5.0), Vec2::new(4.0, 15.0)))]; + // On the left edge of the hatch. + let (left, _) = trim_hatch(&h, &cut, Vec2::new(0.0, 5.0)).unwrap(); + assert!((area(&left.unwrap()) - 60.0).abs() < 1.0); + } +} diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 4640c58acb..211c8f65a6 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -2,16 +2,16 @@ //! (TRIMEXTENDMODE), cutting/boundary edges, Fence, Crossing, Project (PROJMODE), Edge (EDGEMODE), //! eRase and Undo. The geometry of one trim or extend is in modify.rs. -use std::sync::Arc; +use std::sync::{Arc, Mutex}; -use cadcraft_doc::{Drawing, EntityKind, Handle}; -use cadcraft_geom::{Bounds2, Line, Vec2, line_line}; +use cadcraft_doc::{Drawing, EntityKind, Handle, Space}; +use cadcraft_geom::{Bounds2, Line, PolyVertex, Segment, Vec2, line_line}; use serde_json::{Value, json}; use super::helpers::{line, lwpoly, rect_vertices}; -use super::modify::{Edges, extend, trim}; +use super::modify::{Edges, edge_segments_owned, extend, extend_result, prim_to_segments, trim, trim_edges, trim_result}; use super::{bad, point_param, points_param}; -use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; +use crate::{Accept, EngineError, Glow, Input, Interactive, Prompt, Result, Session, Step}; /// Most fence points the JSON form takes. const MAX_FENCE: usize = 10_000; @@ -31,6 +31,18 @@ fn proj_mode(s: &Session) -> i64 { } /// Whether a trim error says the object meets no cutting edge (a Quick-mode trim then erases it). +/// What trimming a hatch takes away, as the glow shows it: the outline of that part and the +/// part filled. +fn hatch_glow(hatch: &cadcraft_doc::Hatch, face: Vec>) -> Vec { + let mut out: Vec = face.iter().map(|l| lwpoly(l.iter().copied().map(PolyVertex::new).collect(), true)).collect(); + let loops = face + .into_iter() + .map(|l| cadcraft_doc::HatchLoop { vertices: l.into_iter().map(PolyVertex::new).collect(), outer: false, sources: Vec::new() }) + .collect(); + out.push(EntityKind::Hatch(cadcraft_doc::Hatch { pattern: "SOLID".into(), solid: true, loops, gradient: None, style: 0, ..hatch.clone() })); + out +} + fn misses_edges(e: &EngineError) -> bool { e.to_string().contains("intersect") } @@ -222,6 +234,8 @@ enum Stage { Fence(Vec), /// A crossing window: its first corner once picked. Crossing(Option), + /// A pick in empty space: a line from this point; everything it crosses is trimmed (extended). + Line(Vec2), Mode, Project, Edge, @@ -229,6 +243,12 @@ enum Stage { Erase(Vec), } +/// The cutting (boundary) edges of one drawing and space, kept while the cursor moves: the +/// drawing (by address), the space, whether edges are implied, and the edges with their objects. +type EdgeCache = (usize, Space, bool, Arc>); +/// The last glow worked out: the drawing (by address), the cursor and the result. +type GlowCache = (usize, (u64, u64), Option); + pub(crate) struct TrimM { extend: bool, /// Cutting/boundary edges; `None`: all objects. @@ -236,11 +256,143 @@ pub(crate) struct TrimM { stage: Stage, /// The drawing before each trim, extend or erase, for Undo. undo: Vec>, + edge_cache: Mutex>, + glow_cache: Mutex>, +} + +/// Samples along an object when finding the part of it a trim takes away or an extend adds. +const GLOW_SAMPLES: f64 = 512.0; + +/// The parts of `orig` that `others` don't run along, as open polylines: what a trim takes away +/// (`others` the pieces left) or an extend adds (`orig` the extended object, `others` it before). +fn uncovered(orig: &EntityKind, others: &[EntityKind]) -> Vec { + let segs: Vec = orig.prims().iter().flat_map(prim_to_segments).collect(); + let total: f64 = segs.iter().map(Segment::len).sum(); + if !total.is_finite() || total <= 0.0 { + return Vec::new(); + } + let other: Vec = others.iter().flat_map(|k| k.prims()).flat_map(|p| prim_to_segments(&p)).collect(); + let tol = total * 2e-4; + let covered = |p: Vec2| other.iter().any(|sg| sg.closest(p).dist(p) <= tol); + let step = total / GLOW_SAMPLES; + let mut out: Vec> = Vec::new(); + let mut cur: Vec = Vec::new(); + let flush = |cur: &mut Vec, out: &mut Vec>| { + if cur.len() >= 2 { + out.push(std::mem::take(cur)); + } else { + cur.clear(); + } + }; + for sg in &segs { + let len = sg.len(); + if !len.is_finite() || len <= 0.0 { + continue; + } + if cur.last().is_some_and(|l| !l.near(sg.at(0.0), tol)) { + flush(&mut cur, &mut out); + } + let n = (len / step).ceil().clamp(1.0, 4096.0) as usize; + let mut prev: Option<(f64, bool)> = None; + for i in 0..=n { + let t = i as f64 / n as f64; + let c = covered(sg.at(t)); + if let Some((pt, pc)) = prev + && pc != c + { + // Where coverage changes between the samples. + let (mut lo, mut hi) = (pt, t); + for _ in 0..20 { + let mid = (lo + hi) * 0.5; + if covered(sg.at(mid)) == pc { + lo = mid; + } else { + hi = mid; + } + } + let x = sg.at((lo + hi) * 0.5); + // The transition lies `tol` off the end of the piece that covers the rest: snap + // to that end. + let x = other + .iter() + .flat_map(|o| [o.at(0.0), o.at(1.0)]) + .filter(|e| e.dist(x) <= 3.0 * tol) + .min_by(|a, b| a.dist(x).total_cmp(&b.dist(x))) + .unwrap_or(x); + if c { + cur.push(x); + flush(&mut cur, &mut out); + } else { + cur.push(x); + } + } + if !c { + cur.push(sg.at(t)); + } + prev = Some((t, c)); + } + if prev.is_some_and(|(_, c)| c) { + flush(&mut cur, &mut out); + } + } + flush(&mut cur, &mut out); + out.into_iter().map(|pts| lwpoly(pts.into_iter().map(PolyVertex::new).collect(), false)).collect() } impl TrimM { pub(crate) fn new(extend: bool) -> Self { - TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new() } + TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new(), edge_cache: Mutex::new(None), glow_cache: Mutex::new(None) } + } + /// The cutting (boundary) edges with their objects, from the cache while the drawing is the + /// same. + fn cached_edges(&self, s: &Session, implied: bool) -> Option>> { + let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize; + let space = s.space(); + let mut cache = self.edge_cache.lock().ok()?; + if let Some((d, sp, i, e)) = cache.as_ref() + && *d == doc + && *sp == space + && *i == implied + { + return Some(e.clone()); + } + let e = Arc::new(edge_segments_owned(s, Edges { only: self.edges.as_deref(), implied }, None).ok()?); + *cache = Some((doc, space, implied, e.clone())); + Some(e) + } + /// What a pick at `c` would trim away or extend by. + fn work_out_glow(&self, s: &Session, c: Vec2) -> Option { + let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; + let space = s.space(); + let d = s.doc().ok()?; + let h = crate::select::pick(d, &space, c, ap)?; + if super::curves::is_locked(s, h) { + return None; + } + let quick = quick_mode(s); + let implied = !quick && edge_mode(s); + if self.extend { + let edges = self.cached_edges(s, implied)?; + let cut: Vec = edges.iter().filter(|(o, _)| *o != h).map(|(_, sg)| *sg).collect(); + let (e, new) = extend_result(s, h, c, &cut).ok()?; + let kinds = uncovered(&new, std::slice::from_ref(&e.kind)); + return (!kinds.is_empty()).then_some(Glow { kinds, removing: false }); + } + // A trim only meets the edges around the object. + let cut = trim_edges(s, Edges { only: self.edges.as_deref(), implied }, h).ok()?; + // A hatch's trim is worked out once, for the part it takes away (`trim_result` would + // work it out again only to drop that part). + let result = match &d.entity(h)?.kind { + EntityKind::Hatch(hatch) => super::trim_hatch::trim_hatch(hatch, &cut, c).map(|(_, face)| hatch_glow(hatch, face)), + _ => trim_result(s, h, c, &cut).map(|(e, pieces)| uncovered(&e.kind, &pieces)), + }; + let kinds = match result { + Ok(kinds) => kinds, + // A Quick-mode trim of an object no edge crosses erases all of it. + Err(err) if quick && misses_edges(&err) => vec![d.entity(h)?.kind.clone()], + Err(_) => return None, + }; + (!kinds.is_empty()).then_some(Glow { kinds, removing: true }) } fn edges(&self, quick: bool, implied: bool) -> Edges<'_> { Edges { only: self.edges.as_deref(), implied: !quick && implied } @@ -250,6 +402,15 @@ impl TrimM { s.set_selection(Vec::new()); self.stage = Stage::Edges(Vec::new()); } + /// The cutting (boundary) edges stay selected, so they show highlighted until the command + /// ends; with no edges (every object cuts) nothing is. + fn show_edges(&self, s: &mut Session) { + let shown: Vec = match (&self.edges, s.doc()) { + (Some(edges), Ok(d)) => edges.iter().copied().filter(|h| d.entity(*h).is_some()).collect(), + _ => Vec::new(), + }; + s.set_selection(shown); + } /// Run `f` as one undoable step of the command; a step that changed nothing records none. fn step(&mut self, s: &mut Session, f: impl FnOnce(&mut Self, &mut Session) -> Result<()>) -> Result<()> { let before = s.state()?.doc.clone(); @@ -315,7 +476,8 @@ impl Interactive for TrimM { if self.extend { "EXTEND" } else { "TRIM" } } fn begin(&mut self, s: &mut Session) -> Result { - s.set_selection(Vec::new()); + // Objects selected before the command are its cutting (boundary) edges. + let pre = s.selection().to_vec(); let quick = quick_mode(s); let proj = match proj_mode(s) { 0 => "None", @@ -327,7 +489,13 @@ impl Interactive for TrimM { if edge_mode(s) { "Extend" } else { "None" }, if quick { "Quick" } else { "Standard" } )); - if !quick { + if !pre.is_empty() { + let n = pre.len(); + self.edges = Some(pre); + self.show_edges(s); + let what = if self.extend { "boundary" } else { "cutting" }; + s.echo(format!("{n} {what} edge{} selected.", if n == 1 { "" } else { "s" })); + } else if !quick { self.select_edges(s); } Ok(Step::Continue) @@ -357,6 +525,7 @@ impl Interactive for TrimM { Some(l) => Prompt::new("Specify next fence point", Accept::POINT).kw(&["Undo"]).base(*l), }, Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT), + Stage::Line(a) => Prompt::new("Specify end point of the fence line", Accept::POINT).base(*a), Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT), Stage::Mode => { let msg = if self.extend { "Enter an extend mode option" } else { "Enter a trim mode option" }; @@ -378,6 +547,13 @@ impl Interactive for TrimM { } } fn input(&mut self, s: &mut Session, i: Input) -> Result { + // Edges and settings may change: work the glow out afresh. + if let Ok(c) = self.edge_cache.get_mut() { + *c = None; + } + if let Ok(c) = self.glow_cache.get_mut() { + *c = None; + } let quick = quick_mode(s); let implied = edge_mode(s); let extending = self.extend; @@ -395,8 +571,8 @@ impl Interactive for TrimM { self.stage = Stage::Edges(picked); } Input::Enter => { - s.set_selection(Vec::new()); self.edges = if picked.is_empty() { None } else { Some(picked) }; + self.show_edges(s); self.stage = Stage::Pick; } _ => {} @@ -415,7 +591,7 @@ impl Interactive for TrimM { self.stage = Stage::Erase(picked); } Input::Enter => { - s.set_selection(Vec::new()); + self.show_edges(s); self.step(s, |_, s| { let d = s.doc_mut()?; for h in &picked { @@ -455,6 +631,21 @@ impl Interactive for TrimM { } Ok(Step::Continue) } + Stage::Line(a) => { + match i { + Input::Point(b) => { + self.stage = Stage::Pick; + let r = self.step(s, |m, s| fence(s, &[a, b], extending, m.edges(quick, implied), quick).map(|_| ())); + if let Err(e) = r { + s.echo(e.to_string()); + } + self.show_edges(s); + } + Input::Enter | Input::Keyword(_) => self.stage = Stage::Pick, + _ => {} + } + Ok(Step::Continue) + } Stage::Crossing(first) => { match (first, i) { (None, Input::Point(p)) => self.stage = Stage::Crossing(Some(p)), @@ -475,17 +666,22 @@ impl Interactive for TrimM { let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; let space = s.space(); let Some(h) = crate::select::pick(s.doc()?, &space, p, ap) else { - // A pick in empty space opens a crossing window there. - self.stage = Stage::Crossing(Some(p)); + // A pick in empty space starts a fence line there: what it crosses is + // trimmed (extended) once its end point is picked. + self.stage = Stage::Line(p); return Ok(Step::Continue); }; let r = self.step(s, |m, s| apply(s, h, p, extending, m.edges(quick, implied), quick).map(|_| ())); if let Err(e) = r { s.echo(e.to_string()); } + self.show_edges(s); Ok(Step::Continue) } - Input::Enter => Ok(Step::Done), + Input::Enter => { + s.set_selection(Vec::new()); + Ok(Step::Done) + } Input::Keyword(k) => { match k.as_str() { "cuTting edges" | "Boundary edges" => self.select_edges(s), @@ -515,6 +711,25 @@ impl Interactive for TrimM { }, } } + fn glow(&self, s: &Session, c: Vec2) -> Option { + if self.stage != Stage::Pick { + return None; + } + let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize; + let key = (c.x.to_bits(), c.y.to_bits()); + if let Ok(cache) = self.glow_cache.lock() + && let Some((d, k, g)) = cache.as_ref() + && *d == doc + && *k == key + { + return g.clone(); + } + let g = self.work_out_glow(s, c); + if let Ok(mut cache) = self.glow_cache.lock() { + *cache = Some((doc, key, g.clone())); + } + g + } fn preview(&self, _s: &Session, c: Vec2) -> Vec { match &self.stage { Stage::Fence(pts) if !pts.is_empty() => pts @@ -526,6 +741,7 @@ impl Interactive for TrimM { .filter_map(|w| Some(line(*w.first()?, *w.get(1)?))) .collect(), Stage::Crossing(Some(a)) => vec![lwpoly(rect_vertices(*a, c), true)], + Stage::Line(a) => vec![line(*a, c)], _ => Vec::new(), } } diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 8a64e2b74c..ee611b59a2 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -75,6 +75,15 @@ impl Interactive for Guarded { Vec::new() }) } + fn glow(&self, s: &Session, cursor: Vec2) -> Option { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.glow(s, cursor))).unwrap_or_else(|_| { + self.broken.set(Some("panic in preview")); + None + }) + } fn preview_objects(&self, s: &Session, cursor: Vec2) -> Vec { if self.broken.get().is_some() { return Vec::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 78245627af..22a1da2aee 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -47,7 +47,7 @@ pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; -pub use prompt::{Accept, Drag, Input, Interactive, Picker, Prompt, Step}; +pub use prompt::{Accept, Drag, Glow, Input, Interactive, Picker, Prompt, Step}; mod doc_state; mod error; diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index c02551b80e..80adaff802 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -226,6 +226,11 @@ pub trait Interactive: Send { fn preview(&self, _s: &Session, _cursor: Vec2) -> Vec { Vec::new() } + /// Geometry shown glowing under the cursor: what picking there would take away or add + /// (TRIM, EXTEND), drawn over the drawing as a highlight. + fn glow(&self, _s: &Session, _cursor: Vec2) -> Option { + None + } /// Preview objects drawn with their own properties (colour, layer, linetype) rather than /// the current layer's, as [`Interactive::preview`]'s are: a block reference re-evaluated /// under the cursor, drawn as it will look. Drawn under the rubber band. @@ -245,6 +250,14 @@ pub trait Interactive: Send { } } +/// See [`Interactive::glow`]. +#[derive(Clone, Debug, PartialEq)] +pub struct Glow { + pub kinds: Vec, + /// The geometry is what a pick takes away (a trim), not what it adds (an extend). + pub removing: bool, +} + /// See [`Interactive::drag`]. #[derive(Clone, Debug)] pub struct Drag { diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 4ee6e6d8ab..c2e547a3c9 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -354,9 +354,9 @@ impl Session { } self.pending_window = None; self.select_mode = None; - // HATCH keeps its boundary objects selected (highlighted) while it runs; they stay - // selected no longer than the command, however it ends. - if matches!(run.id.as_str(), "hatch" | "gradient" | "hatchpick") { + // TRIM and EXTEND keep their edges selected (highlighted) while they run, and HATCH its + // boundary objects; they stay selected no longer than the command, however it ends. + if matches!(run.id.as_str(), "trim" | "extend" | "hatch" | "gradient" | "hatchpick") { self.set_selection(Vec::new()); } let label = find_command(&run.id).map(|c| c.label).unwrap_or("Command"); @@ -504,6 +504,18 @@ impl Session { out } + /// What the active command shows glowing under the cursor ([`Interactive::glow`]), as + /// entities with the current properties, and whether it is what a pick would take away. + pub fn glow(&self, cursor: Vec2) -> Option<(Vec, bool)> { + if self.lisp_prompt().is_some() { + return None; + } + let r = self.running.as_ref()?; + let g = r.machine.glow(self, cursor)?; + let common = self.current_common(); + Some((g.kinds.into_iter().map(|k| Entity { handle: Handle(0), common: common.clone(), kind: k }).collect(), g.removing)) + } + /// The active command's preview as a transform of existing objects (see /// [`Interactive::drag`]), with its extra rubber-band geometry as entities. pub fn drag(&self, cursor: Vec2) -> Option<(Drag, Vec)> { diff --git a/crates/engine/tests/it/trim_extend_options.rs b/crates/engine/tests/it/trim_extend_options.rs index 5302a68c95..a0ee4e366a 100644 --- a/crates/engine/tests/it/trim_extend_options.rs +++ b/crates/engine/tests/it/trim_extend_options.rs @@ -201,3 +201,148 @@ fn json_forms_take_fence_crossing_edge_mode_and_mode() { assert_eq!(r["extended"], 1); assert_eq!(lines(&s), vec![((0.0, 0.0), (10.0, 0.0)), ((10.0, -5.0), (10.0, 5.0))]); } + +/// The handle of the line with these ends. +fn handle_of(s: &Session, seg: Seg) -> cadcraft_engine::doc::Handle { + s.doc() + .unwrap() + .model + .iter() + .find(|e| matches!(&e.kind, EntityKind::Line(l) if ((r(l.a.x), r(l.a.y)), (r(l.b.x), r(l.b.y))) == seg)) + .unwrap() + .handle +} + +#[test] +fn objects_selected_before_trim_are_its_cutting_edges_and_stay_highlighted() { + let mut s = ladder(); + let edge = handle_of(&s, ((0.0, -5.0), (0.0, 5.0))); + s.set_selection(vec![edge]); + s.cmdline("TRIM").unwrap(); + assert_eq!(s.selection(), [edge], "the edge stays selected (highlighted) while TRIM runs"); + // Only the x = 0 line cuts: the y = 0 line loses its left part, the x = 10 line doesn't cut. + s.script("-2,0\n").unwrap(); + assert_eq!(s.selection(), [edge]); + assert!(lines(&s).contains(&((0.0, 0.0), (15.0, 0.0))), "{:?}", lines(&s)); + s.script("\n").unwrap(); + assert!(s.running.is_none()); + assert!(s.selection().is_empty(), "the highlight ends with the command"); + // Cancelling ends it too. + s.set_selection(vec![edge]); + s.cmdline("EXTEND").unwrap(); + assert_eq!(s.selection(), [edge]); + s.cancel(); + assert!(s.selection().is_empty()); +} + +#[test] +fn a_pick_in_empty_space_draws_a_fence_line_and_trims_what_it_crosses() { + let mut s = ladder(); + // Quick mode. From empty space at 5,-3 to 5,3: both horizontal lines are cut between the edges. + s.script("TRIM 5,-3\n").unwrap(); + assert_eq!(s.current_prompt().map(|p| p.message), Some("Specify end point of the fence line".into())); + s.script("5,3\n\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!( + lines(&s), + with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (0.0, 2.0)), ((10.0, 0.0), (15.0, 0.0)), ((10.0, 2.0), (15.0, 2.0))]) + ); +} + +/// The glow under the cursor: its polylines' points (rounded). +fn glow_points(s: &Session, at: (f64, f64)) -> Option<(Vec>, bool)> { + let (ents, removing) = s.glow(cadcraft_engine::geom::Vec2::new(at.0, at.1))?; + let pts = ents + .iter() + .filter_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.vertices.iter().map(|v| (r(v.p.x), r(v.p.y))).collect()) } else { None }) + .collect(); + Some((pts, removing)) +} + +#[test] +fn trim_glows_the_part_a_pick_takes_away() { + let mut s = ladder(); + s.cmdline("TRIM").unwrap(); + let (pts, removing) = glow_points(&s, (5.0, 0.0)).expect("a glow over the line"); + assert!(removing); + assert_eq!(pts.len(), 1); + let run = &pts[0]; + let (lo, hi) = run.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); + assert!((lo - 0.0).abs() < 1e-3 && (hi - 10.0).abs() < 1e-3, "{lo} {hi}"); + assert!(run.iter().all(|p| p.1 == 0.0)); + // Nothing under the cursor: no glow. Nothing changes in the drawing. + assert!(s.glow(cadcraft_engine::geom::Vec2::new(5.0, 30.0)).is_none()); + assert_eq!(lines(&s).len(), 4); +} + +#[test] +fn extend_glows_the_part_a_pick_adds() { + let mut s = session(&["0,0 5,0", "10,-5 10,5"]); + s.cmdline("EXTEND").unwrap(); + let (pts, removing) = glow_points(&s, (4.0, 0.0)).expect("a glow over the line"); + assert!(!removing); + let (lo, hi) = pts.iter().flatten().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); + assert!((lo - 5.0).abs() < 1e-2 && (hi - 10.0).abs() < 1e-3, "{lo} {hi}"); +} + +#[test] +fn trim_cuts_a_hatch_area() { + use cadcraft_engine::doc::{Common, Hatch, HatchLoop, Space}; + use cadcraft_engine::geom::{PolyVertex, Vec2}; + let mut s = session(&["4,-5 4,15"]); + let vertices = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(); + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + let h = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Hatch(hatch)).unwrap(); + s.execute("trim", &json!({ "handle": h.hex(), "pick": [2.0, 5.0] })).unwrap(); + let left: Vec<_> = + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).collect(); + assert_eq!(left.len(), 1); + let xs: Vec = left[0].loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p.x)).collect(); + assert!(xs.iter().all(|x| *x >= 4.0 - 1e-6), "{xs:?}"); + assert!(xs.iter().any(|x| (*x - 10.0).abs() < 1e-6)); +} + +#[test] +fn lines_inside_a_block_cut_a_hatch() { + use cadcraft_engine::doc::{Common, Hatch, HatchLoop, Space}; + use cadcraft_engine::geom::{PolyVertex, Vec2}; + let mut s = Session::new(); + // A block whose line crosses the hatch at x = 4. + let l = s.execute("line", &json!({ "points": [[4, -5], [4, 15]] })).unwrap()["handles"][0].as_str().unwrap().to_string(); + s.execute("block", &json!({ "name": "DIVIDER", "base": [0, 0], "handles": [l], "keep": "convert" })).unwrap(); + let vertices = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(); + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + let h = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Hatch(hatch)).unwrap(); + // Quick mode: a hatch no edge crossed would be erased. + s.execute("trim", &json!({ "handle": h.hex(), "pick": [2.0, 5.0], "mode": "quick" })).unwrap(); + let left: Vec<_> = + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).collect(); + assert_eq!(left.len(), 1, "trimmed, not erased"); + assert!(left[0].loops.iter().flat_map(|l| l.vertices.iter()).all(|v| v.p.x >= 4.0 - 1e-6)); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 787aa1a2fa..48eced01b8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -644,6 +644,16 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.cycle_badge_at = None; } + // What a pick would trim away or extend by (TRIM, EXTEND) glows instead of the whole object + // under the cursor highlighting. + let glow = match (app.canvas.cursor, app.session.prompting()) { + (Some(c), true) => app.session.glow(c), + _ => None, + }; + if glow.is_some() { + app.canvas.hover = None; + } + // ---------- paint ---------- painter.rect_filled(rect, 0.0, t.canvas); let t0 = crate::now_ms(); @@ -833,6 +843,21 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } crate::dyngrips::draw(app, &painter, &xf, rect, hover_pos); } + // What a pick would trim away or extend by (TRIM, EXTEND), glowing under the cursor. + if let Some((ents, removing)) = glow + && let Ok(st) = app.session.state() + { + let list = rebuilt_preview(&st.doc, ents.iter(), scale); + let all: Vec = (0..list.prims.len()).collect(); + // The halo around lines only; a filled area (a hatch) is tinted once. + let lines: Vec = + all.iter().copied().filter(|&i| list.prims.get(i).is_some_and(|p| !matches!(p.kind, Kind::Tris | Kind::Mask))).collect(); + let col = if removing { Color32::from_rgb(0xff, 0x5a, 0x3c) } else { Color32::from_rgb(0x3c, 0xc8, 0xff) }; + for (width, alpha) in [(11.0, 0.12), (7.0, 0.22)] { + draw_highlight(&painter, &xf, &list, &lines, col.gamma_multiply(alpha), Look { width, dashed: false }); + } + draw_highlight(&painter, &xf, &list, &all, col, Look { width: 2.0, dashed: false }); + } // Rubber band preview of the active command. // `xf` is the space being edited: paper space, or model space inside the active viewport. let drag = match (app.canvas.cursor, app.canvas.gpu.is_some()) { From cd15b3e65e1e13ca72c040ba78749ff7eba657dd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:56:41 +0200 Subject: [PATCH 04/30] Keep the hatch background helpers beside the other xdata applications Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/src/dxf_ext.rs | 58 ++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index f295264ebc..2aa74babcc 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -20,35 +20,6 @@ use serde_json::Value; /// Registered application name of CADCraft's extended data. pub(crate) const APP: &str = "CADCRAFT"; -/// AutoCAD's hatch background colour xdata application (one `1071` colour value). -pub(crate) const HATCH_BACKGROUND_APP: &str = "HATCHBACKGROUNDCOLOR"; - -/// An AutoCAD colour value (`1071`/`420`-style, top byte the method): 0xC2 RGB, 0xC3 an index -/// colour in the low byte, 0xC0 ByLayer, 0xC1 ByBlock; `None` for none or anything else. -pub(crate) fn acad_color(v: i64) -> Option { - let v = v as u32; - match v >> 24 { - 0xC2 => Some(cadcraft_color::Color::True(cadcraft_color::Rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))), - 0xC3 => match (v & 0xFF) as u8 { - 0 => None, - i => Some(cadcraft_color::Color::Index(i)), - }, - 0xC0 => Some(cadcraft_color::Color::ByLayer), - 0xC1 => Some(cadcraft_color::Color::ByBlock), - _ => None, - } -} - -/// [`acad_color`] the other way. -pub(crate) fn acad_color_value(c: cadcraft_color::Color) -> i64 { - let v: u32 = match c { - cadcraft_color::Color::True(cadcraft_color::Rgb(r, g, b)) => 0xC200_0000 | (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b), - cadcraft_color::Color::Index(i) => 0xC300_0000 | u32::from(i), - cadcraft_color::Color::ByLayer => 0xC000_0000, - cadcraft_color::Color::ByBlock => 0xC100_0000, - }; - i64::from(v as i32) -} /// Named-object-dictionary key of the constraint XRECORD. pub(crate) const CONSTRAINTS_KEY: &str = "CADCRAFT_CONSTRAINTS"; /// Named-object-dictionary key of the saved layer states XRECORD. @@ -339,6 +310,35 @@ pub(crate) fn arrow_block_name(name: &str) -> Option<(String, Arrowhead)> { /// Applications whose xdata carries layer properties: transparency and description. pub(crate) const LAYER_TRANSPARENCY_APP: &str = "AcCmTransparency"; pub(crate) const LAYER_DESCRIPTION_APP: &str = "AcAecLayerStandard"; +/// AutoCAD's hatch background colour xdata application (one `1071` colour value). +pub(crate) const HATCH_BACKGROUND_APP: &str = "HATCHBACKGROUNDCOLOR"; + +/// An AutoCAD colour value (`1071`/`420`-style, top byte the method): 0xC2 RGB, 0xC3 an index +/// colour in the low byte, 0xC0 ByLayer, 0xC1 ByBlock; `None` for none or anything else. +pub(crate) fn acad_color(v: i64) -> Option { + let v = v as u32; + match v >> 24 { + 0xC2 => Some(cadcraft_color::Color::True(cadcraft_color::Rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))), + 0xC3 => match (v & 0xFF) as u8 { + 0 => None, + i => Some(cadcraft_color::Color::Index(i)), + }, + 0xC0 => Some(cadcraft_color::Color::ByLayer), + 0xC1 => Some(cadcraft_color::Color::ByBlock), + _ => None, + } +} + +/// [`acad_color`] the other way. +pub(crate) fn acad_color_value(c: cadcraft_color::Color) -> i64 { + let v: u32 = match c { + cadcraft_color::Color::True(cadcraft_color::Rgb(r, g, b)) => 0xC200_0000 | (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b), + cadcraft_color::Color::Index(i) => 0xC300_0000 | u32::from(i), + cadcraft_color::Color::ByLayer => 0xC000_0000, + cadcraft_color::Color::ByBlock => 0xC100_0000, + }; + i64::from(v as i32) +} /// A transparency percentage (0..=90) as an `AcCmTransparency` value: the alpha with the /// "by alpha" flag (0x02 in the top byte). From 43087b5a279bca836fad9ff84ddd7d1de3195761 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:58:04 +0200 Subject: [PATCH 05/30] Register the CADCRAFTFORMULA xdata application in the APPID table AutoCAD refuses extended data of an application the file does not register. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/src/dxf_write/sections.rs | 2 +- crates/io/tests/it/text_formula_roundtrip.rs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 7198eeee84..0bffa48b87 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -460,7 +460,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec= 3, "registered once, used twice"); let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); let kinds: Vec = back.model.iter().map(|e| e.kind.clone()).collect(); assert!(kinds.iter().any(|k| matches!(k, EntityKind::Text(t) if t.formula.as_deref() == Some("=1+1")))); From 35b7a3530d98968a008f21eca7382469dffc2e30 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 13:58:19 +0200 Subject: [PATCH 06/30] Export Glow on a line of its own Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c4fa2d5de9..739ee25166 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -49,7 +49,7 @@ pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; -pub use prompt::{Accept, Drag, Glow, Input, Interactive, Picker, Prompt, Step}; +pub use prompt::{Accept, Drag, Input, Interactive, Picker, Prompt, Step}; mod doc_state; mod error; @@ -64,6 +64,8 @@ pub use error::{EngineError, Result}; pub use last_used::{LastUsed, LeaderOrder, LeaderType, MLeaderOptions}; pub use running::{PendingWindow, Running}; pub use settings::Settings; +// What TRIM and EXTEND show glowing under the cursor. +pub use prompt::Glow; pub use view::{ModelTile, ModelTiles, View}; /// The editor session: open drawings, settings, the running command and the command log. From 70c18585efaea9c5ffdf9a6c6049f3834671fcd4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 15:03:54 +0200 Subject: [PATCH 07/30] Same description of the folder picker in every part Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/ui-egui/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 92bc560609..5aba163fa9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -202,7 +202,7 @@ impl Default for UiState { pub struct Services { pub pick_open: Option Option>>, pub pick_save: Option Option>>, - /// Pick a folder (the Custom Patterns folder); `None` where the host has no folder dialog. + /// Pick a folder (Options ▸ Fonts, the Custom Patterns folder); `None` where the host has no folder dialog. pub pick_folder: Option Option>>, /// Pick a `.lsp` file for APPLOAD, starting in the given folder (empty for the default one). /// `None` where there is no native file dialog: the desktop without one asks for the name, From 867542496b31c1e4a1e356eecd7001347b6ff8c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 19:59:39 +0200 Subject: [PATCH 08/30] Text formulas: review fixes - CADCRAFTFORMULA is our own xdata: a cleared formula is not written back from the old raw data. - Attribute definitions, attributes and multileaders save their formulas. - A dimension's <> is its numeric measurement (DIMLFAC, DIMRND, shown resolution), not a number read from the formatted text; the stored text is the result. - Rendering keeps the engine's result where the file, layout or clock is unknown (no fabricated web date; FILENAME()/SHEET() not replaced by empty/Model). - One-line text keeps braces and backslashes in a formula. - A dimension override typed in Properties replaces its formula. - TXT2MTXT of one text keeps its formula. - POWER chains count toward the nesting limit; quoted words are not date formats. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/modify2/textedit.rs | 5 + crates/engine/src/cmd/props.rs | 7 ++ crates/engine/src/cmd/txt2mtxt.rs | 3 +- crates/engine/src/session/cmdline.rs | 2 + crates/engine/src/textformula.rs | 50 ++++++-- crates/engine/tests/it/text_formulas.rs | 67 +++++++++++ crates/io/src/dxf_ext.rs | 2 +- crates/io/src/dxf_raw.rs | 2 +- crates/io/src/dxf_read/entities.rs | 5 + crates/io/src/dxf_read/text.rs | 2 + crates/io/src/dxf_write/entity.rs | 3 + crates/io/tests/it/text_formula_roundtrip.rs | 120 +++++++++++++++++++ crates/render/src/dim.rs | 13 +- crates/render/src/dim/text.rs | 25 +++- crates/render/src/textformula.rs | 115 +++++++++++++----- 15 files changed, 376 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index 9b952b0e09..5e70583b51 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -49,6 +49,11 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { } pub(super) fn run_updatefield(s: &mut Session, _p: &Value) -> Result { + // Without a formula or field the drawing is left as it is (not marked changed). + if !crate::textformula::has_any(s.doc()?) { + s.echo("0 field(s) updated"); + return Ok(json!({ "updated": 0 })); + } let env = crate::textformula::env(s); let n = crate::textformula::refresh(s.doc_mut()?, &env); s.echo(format!("{n} field(s) updated")); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index fd892eb5d0..f9270a9bed 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -220,6 +220,11 @@ fn run_set(s: &mut Session, p: &Value) -> Result { let dim_over = dim_overrides(p)?; let anno_scale = d.current_anno_scale(); for h in &hs { + // A dimension's measurement, which `<>` in a new formula stands for. + let formula_env = match d.entity(*h).map(|e| &e.kind) { + Some(EntityKind::Dimension(dm)) => crate::textformula::Env { measured: crate::textformula::measured(d, dm), ..formula_env.clone() }, + _ => formula_env.clone(), + }; d.modify_entity(*h, |e| { let mut new_text = false; // Annotative: Yes supports the current annotation scale; No drops every scale. @@ -390,6 +395,8 @@ fn run_set(s: &mut Session, p: &Value) -> Result { if let Some(v) = str_param(p, "textOverride") { dm.text = v.to_string(); dm.block = None; + // Like typing over it: a formula becomes the formula, other text drops it. + new_text = true; } if let Some(st) = &dim_style { dm.style.clone_from(st); diff --git a/crates/engine/src/cmd/txt2mtxt.rs b/crates/engine/src/cmd/txt2mtxt.rs index 7302280db3..174996e806 100644 --- a/crates/engine/src/cmd/txt2mtxt.rs +++ b/crates/engine/src/cmd/txt2mtxt.rs @@ -187,7 +187,8 @@ fn single(t: &Text) -> MText { _ => 2, }; MText { - formula: None, + // The text's formula carries over (its result is the contents). + formula: t.formula.clone(), insert: v3(t.justify_point()), height: t.height, width: 0.0, diff --git a/crates/engine/src/session/cmdline.rs b/crates/engine/src/session/cmdline.rs index edb6b6ef12..1cd07f5140 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -83,7 +83,9 @@ impl Session { return self.start(tt); } // A formula (`=1200+350*2`) where a distance or number is asked: its value is the answer. + // Not where text is also an answer: there `=…` is the text itself. if (prompt.accept.number || prompt.accept.point) + && !prompt.accept.text && let Some(r) = crate::formula::eval(tt) { return match r { diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs index c3532bff4c..58ae6c6b19 100644 --- a/crates/engine/src/textformula.rs +++ b/crates/engine/src/textformula.rs @@ -21,7 +21,10 @@ pub fn env(s: &crate::Session) -> Env { // ---------- applying to a drawing ---------- -/// The measurement a dimension shows (for `<>` in its formula). +/// The measurement a dimension shows (for `<>` in its formula): the measured value with +/// DIMLFAC, DIMRND and the shown resolution applied (degrees for an angle), taken from the +/// dimension itself, not read back from its formatted text (a DIMPOST prefix, architectural +/// units or a decimal comma would give the wrong number). pub fn measured(d: &Drawing, dm: &cadcraft_doc::Dimension) -> Option { let plain = cadcraft_doc::Dimension { text: String::new(), @@ -29,13 +32,7 @@ pub fn measured(d: &Drawing, dm: &cadcraft_doc::Dimension) -> Option { marks: cadcraft_doc::DimMarks { formula: None, ..dm.marks.clone() }, ..dm.clone() }; - let v = cadcraft_render::dimension_in(d, &plain).value; - let s: String = v - .chars() - .skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.') - .take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')) - .collect(); - s.replace(' ', "").replace(',', ".").parse().ok() + cadcraft_render::dimension_in(d, &plain).formula_value.filter(|v| v.is_finite()) } /// A text object's formula, worked out into what it shows: a value that is a formula (one line @@ -57,7 +54,9 @@ pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { _ => return, }; if edited { - let plain = cadcraft_fonts::plain_mtext(value); + // Multiline text is read without its formatting codes; one-line text and dimension text + // as typed (their braces and backslashes are letters). + let plain = if mtext { cadcraft_fonts::plain_mtext(value) } else { value.clone() }; if is_formula(&plain) { *formula = Some(plain.trim().to_string()); } else { @@ -68,10 +67,22 @@ pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { if let Some(f) = formula.as_deref() && let Some(v) = evaluate(f, env) { - *value = if mtext { cadcraft_doc::mtext_literal(&v) } else { v }; + // A formula's result is plain text: in multiline text its `\`, `{` and `}` are letters. + // An AutoCAD field's text is the multiline text around the fields, codes included. + *value = if mtext && is_formula(f) { cadcraft_doc::mtext_literal(&v) } else { v }; } } +/// Whether a drawing has any formula or field to work out (UPDATEFIELD on a drawing without +/// one changes nothing, not even its saved state). +pub fn has_any(d: &Drawing) -> bool { + d.model + .iter() + .chain(d.layouts.iter().flat_map(|l| l.entities.iter())) + .chain(d.blocks.values().flat_map(|b| b.entities.iter())) + .any(|e| has_formula(&e.kind)) +} + /// Whether an entity has a formula or field to work out. fn has_formula(k: &EntityKind) -> bool { match k { @@ -84,6 +95,14 @@ fn has_formula(k: &EntityKind) -> bool { } } +/// A dimension's text, to see whether working out its formula changed it. +fn dim_text(k: &EntityKind) -> Option<&str> { + match k { + EntityKind::Dimension(d) => Some(d.text.as_str()), + _ => None, + } +} + /// Work out every formula and known field of a drawing again (when it is opened): model space, /// layouts and block definitions. The number of texts worked out. pub fn refresh(d: &mut Drawing, env: &Env) -> usize { @@ -107,7 +126,16 @@ pub fn refresh(d: &mut Drawing, env: &Env) -> usize { if let Some(sheet) = sheet { env.sheet = sheet.to_string(); } - store.modify(h, |e| apply(&mut e.kind, &env, false)); + store.modify(h, |e| { + let before = dim_text(&e.kind).map(str::to_string); + apply(&mut e.kind, &env, false); + // A dimension whose text changed draws itself again (not its old block). + if before.as_deref() != dim_text(&e.kind) + && let EntityKind::Dimension(dm) = &mut e.kind + { + dm.block = None; + } + }); *n += 1; } }; diff --git a/crates/engine/tests/it/text_formulas.rs b/crates/engine/tests/it/text_formulas.rs index cc1a8a0fd6..974afe1d3d 100644 --- a/crates/engine/tests/it/text_formulas.rs +++ b/crates/engine/tests/it/text_formulas.rs @@ -132,3 +132,70 @@ fn a_dimension_formula_uses_the_measurement_not_the_shown_text() { let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; assert_eq!(cadcraft_render::dimension_in(d, dm).value, "625"); } + +/// The stored text of a `=<>/2` dimension with a DIMPOST prefix is the formula's result +/// (properties and DXF group 1 show it), not a number read from the prefix (#2318 review). +#[test] +fn a_dimension_formula_stores_its_result_with_a_prefix() { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "DIMPOST", "value": "2X<>" })).unwrap(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [1250, 0], "at": [600, 100] })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": h, "text": "=<>/2" })).unwrap(); + s.execute("updatefield", &json!({})).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + assert_eq!(dm.text, "625"); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap(); + let dm = back.model.iter().find_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm.clone()) } else { None }).unwrap(); + assert_eq!((dm.text.as_str(), dm.marks.formula.as_deref()), ("625", Some("=<>/2"))); +} + +/// Typing a plain override in the properties drops a dimension's formula; UPDATEFIELD keeps +/// the typed text (#2318 review). +#[test] +fn a_dimension_override_in_properties_replaces_its_formula() { + let mut s = Session::new(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [1250, 0], "at": [600, 100] })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": h, "text": "=<>/2" })).unwrap(); + s.execute("properties.set", &json!({ "handles": [h], "textOverride": "ABC" })).unwrap(); + s.execute("updatefield", &json!({})).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + assert_eq!((dm.text.as_str(), dm.marks.formula.as_deref()), ("ABC", None)); + assert_eq!(cadcraft_render::dimension_in(d, dm).value, "ABC"); + // A formula typed there becomes the formula, `<>` the measurement. + s.execute("properties.set", &json!({ "handles": [h], "textOverride": "=<>*2" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + assert_eq!((dm.text.as_str(), dm.marks.formula.as_deref()), ("2500", Some("=<>*2"))); +} + +/// TXT2MTXT of one text keeps its formula, which still recalculates (#2318 review). +#[test] +fn txt2mtxt_keeps_a_texts_formula() { + let mut s = Session::new(); + let r = s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=2+3" })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("txt2mtxt", &json!({ "handles": [h], "combine": false })).unwrap(); + let mt = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!((cadcraft_fonts::plain_mtext(&mt.contents).as_str(), mt.formula.as_deref()), ("5", Some("=2+3"))); +} + +/// One-line text keeps braces and backslashes in its formula: they are letters there, not +/// multiline formatting (#2318 review). +#[test] +fn one_line_text_formulas_keep_braces() { + let mut s = Session::new(); + s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=LEN(\"a{b}\")" })).unwrap(); + s.execute("text", &json!({ "at": [0, 5], "height": 1, "text": "=UPPER(\"{a}\\x\")" })).unwrap(); + let got: Vec<(String, Option)> = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| if let EntityKind::Text(t) = &e.kind { Some((t.value.clone(), t.formula.clone())) } else { None }) + .collect(); + assert_eq!(got, [("4".to_string(), Some("=LEN(\"a{b}\")".to_string())), ("{A}\\X".to_string(), Some("=UPPER(\"{a}\\x\")".to_string()))]); +} diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 0d728611ef..3581b1a68a 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -36,7 +36,7 @@ pub(crate) fn formula_chunks(f: &str) -> Vec { // bytes each, so the pieces are cut by bytes, between letters. let mut out = Vec::new(); let mut cur = String::new(); - for c in f.chars().take(4000) { + for c in f.chars() { if cur.len() + c.len_utf8() > 250 { out.push(std::mem::take(&mut cur)); } diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index a1103056f5..fc60843a02 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -43,7 +43,7 @@ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCO /// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides /// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. -const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; +const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD", "CADCRAFTFORMULA"]; /// Most objects kept from one file. const MAX_OBJECTS: usize = 1_000_000; diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 8270c9a6ac..f43fd57a58 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -448,6 +448,9 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK } ("MULTILEADER" | "MLEADER", EntityKind::MLeader(m)) => { let pending = crate::dxf_mleader::resolve(tags, m, &rx.styles, &rx.brs); + if let Some(t) = &mut m.text { + t.formula = crate::dxf_ext::formula(tags); + } if let Some(b) = &m.block { rx.inserted.insert(b.block.to_ascii_uppercase()); } @@ -532,6 +535,8 @@ pub(super) fn insert_attribs(recs: &[(String, Vec)], i: &mut usize, ins_lay if let Some(m) = &multiline { text.value.clone_from(&m.read_as); } + // The formula's xdata closes the record, after any embedded multiline text. + text.formula = crate::dxf_ext::formula(t2); attribs.push(Attrib { tag: own.s(2).unwrap_or_default(), text, diff --git a/crates/io/src/dxf_read/text.rs b/crates/io/src/dxf_read/text.rs index f4b29050b5..e4c2fb1306 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -164,6 +164,8 @@ pub(super) fn attdef(tags: &[Tag], c: &Common) -> Attrib { if let Some(m) = &multiline { text.value.clone_from(&m.read_as); } + // The formula's xdata closes the record, after any embedded multiline text. + text.formula = crate::dxf_ext::formula(tags); Attrib { tag: own.s(2).unwrap_or_default(), text, diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 8f8cfc726a..a584c08eda 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -228,6 +228,7 @@ pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo if cx.target >= Version::R2007 { multiline_tags(w, a, true); } + formula_xdata(w, a.text.formula.as_deref()); } EntityKind::MText(t) => { w.s(0, "MTEXT"); @@ -293,6 +294,7 @@ pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo if cx.target >= Version::R2007 { multiline_tags(w, a, false); } + formula_xdata(w, a.text.formula.as_deref()); } let sh = w.h(); w.s(0, "SEQEND"); @@ -458,6 +460,7 @@ pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo block: m.block.as_ref().and_then(|b| cx.block_records.get(&b.block.to_ascii_uppercase()).cloned()), }; w.t.extend(crate::dxf_mleader::entity_tags(d, m, &refs)); + formula_xdata(w, m.text.as_ref().and_then(|t| t.formula.as_deref())); } EntityKind::Leader(l) => { w.s(0, "LEADER"); diff --git a/crates/io/tests/it/text_formula_roundtrip.rs b/crates/io/tests/it/text_formula_roundtrip.rs index de2ad911d1..c94134afc3 100644 --- a/crates/io/tests/it/text_formula_roundtrip.rs +++ b/crates/io/tests/it/text_formula_roundtrip.rs @@ -45,3 +45,123 @@ fn text_and_mtext_formulas_roundtrip() { assert!(kinds.iter().any(|k| matches!(k, EntityKind::Text(t) if t.formula.as_deref() == Some("=1+1")))); assert!(kinds.iter().any(|k| matches!(k, EntityKind::MText(m) if m.formula.as_deref() == Some(long.as_str())))); } + +fn text(value: &str, formula: Option<&str>) -> Text { + Text { + insert: Vec3::new(0.0, 0.0, 0.0), + align_pt: None, + height: 2.5, + value: value.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + formula: formula.map(str::to_string), + } +} + +fn mtext(contents: &str, formula: Option<&str>) -> MText { + MText { + formula: formula.map(str::to_string), + insert: Vec3::new(0.0, 10.0, 0.0), + height: 2.5, + width: 40.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: contents.into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + } +} + +/// Attribute definitions, attributes and multileaders keep their formulas too (#2318 review). +#[test] +fn attribute_and_multileader_formulas_roundtrip() { + let mut d = Drawing::new_metric(); + let def = cadcraft_doc::Attrib { + tag: "T".into(), + text: text("2", Some("=1+1")), + invisible: false, + constant: false, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }; + d.add(&Space::Model, Common::default(), EntityKind::AttDef(def.clone())).unwrap(); + d.blocks.insert("B".into(), cadcraft_doc::Block::new("B").into()); + let ins = cadcraft_doc::Insert { + block: "B".into(), + insert: Vec3::new(5.0, 0.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: vec![cadcraft_doc::Attrib { text: text("6", Some("=2*3")), ..def }], + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + let ml = cadcraft_doc::MLeader { + leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 0.0)]], + landing: Vec3::new(10.0, 10.0, 0.0), + dogleg: 2.0, + text: Some(mtext("9", Some("=3*3"))), + style: "Standard".into(), + arrow_size: 1.0, + spline: false, + block: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::MLeader(ml)).unwrap(); + let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let mut found = Vec::new(); + for e in back.model.iter() { + match &e.kind { + EntityKind::AttDef(a) => found.push(a.text.formula.clone()), + EntityKind::Insert(i) => found.extend(i.attribs.iter().map(|a| a.text.formula.clone())), + EntityKind::MLeader(m) => found.push(m.text.as_ref().and_then(|t| t.formula.clone())), + _ => {} + } + } + found.sort(); + assert_eq!(found, [Some("=1+1".to_string()), Some("=2*3".to_string()), Some("=3*3".to_string())]); +} + +/// A formula replaced by plain text after reopening stays gone: its old extended data is not +/// kept as another program's data and written back (#2318 review). +#[test] +fn a_cleared_formula_is_not_restored_from_old_xdata() { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Text(text("2", Some("=1+1")))).unwrap(); + d.add(&Space::Model, Common::default(), EntityKind::MText(mtext("4", Some("=2+2")))).unwrap(); + let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); + let mut back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let hs: Vec<_> = back.model.iter().map(|e| e.handle).collect(); + for h in hs { + back.modify_entity(h, |e| match &mut e.kind { + EntityKind::Text(t) => { + t.value = "plain".into(); + t.formula = None; + } + EntityKind::MText(m) => { + m.contents = "plain".into(); + m.formula = None; + } + _ => {} + }) + .unwrap(); + } + let again = cadcraft_io::read(&cadcraft_io::write(&back, "a.dxf").unwrap(), "a.dxf").unwrap(); + for e in again.model.iter() { + match &e.kind { + EntityKind::Text(t) => assert_eq!((t.value.as_str(), t.formula.as_deref()), ("plain", None)), + EntityKind::MText(m) => assert_eq!((m.contents.as_str(), m.formula.as_deref()), ("plain", None)), + _ => {} + } + } +} diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index c86576a34b..98af2edb58 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -18,7 +18,7 @@ mod text; use arrowheads::tick; pub use arrowheads::{ArrowGeom, Arrowhead, arrow, arrowhead}; pub use text::{DimText, format_linear_value}; -use text::{apply_override, inspected, linear_text, shown_value}; +use text::{angular_formula_value, apply_override, inspected, linear_formula_value, linear_text}; /// Most DIMBREAK gaps drawn per dimension. const MAX_BREAKS: usize = 1000; @@ -55,6 +55,9 @@ pub struct DimGeometry { pub text_pos: Vec2, /// The measured value (DXF group 42): a length, or the angle in radians. pub measurement: f64, + /// What a formula's `<>` stands for: the measurement as the dimension shows it (DIMLFAC, + /// DIMRND and the shown resolution applied; degrees for an angle). + pub formula_value: Option, pub text_angle: f64, pub text_height: f64, /// Plain text of the dimension. @@ -282,6 +285,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let f2 = foot(p2); // The measurement is along the dimension direction whatever the extension lines do. let meas = (p2 - p1).dot(dir).abs(); + g.formula_value = Some(linear_formula_value(meas, st)); g.mtext = linear_text(meas, d, st, ""); g.measurement = meas; // From here on: the length drawn between the extension lines. @@ -474,6 +478,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let r = center.dist(tip); let j = d.marks.jogged.clone().unwrap_or_default(); let (o, jp) = (j.center.xy(), j.jog.xy()); + g.formula_value = Some(linear_formula_value(r, st)); g.mtext = linear_text(r, d, st, "R"); // A NaN or infinite radius leaves no line to draw (and NaN is no bound for `clamp`). if !r.is_finite() { @@ -507,6 +512,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let radius = matches!(d.kind, DimKind::Radius); let (center, r) = if radius { (a, a.dist(b)) } else { (a.mid(b), a.dist(b) / 2.0) }; let meas = if radius { r } else { 2.0 * r }; + g.formula_value = Some(linear_formula_value(meas, st)); g.mtext = linear_text(meas, d, st, if radius { "R" } else { "%%c" }); g.measurement = meas; let (tw, tht) = measure(&g.mtext); @@ -602,7 +608,8 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let azin = (st.angular_zero_suppression & 3) * 4; let txt = format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator); // DIMPOST is a linear-dimension prefix/suffix; angles have their own format only. - g.mtext = inspected(apply_override(&txt, d, Some(shown_value(sweep.to_degrees(), st.angular_decimals))), d); + g.formula_value = Some(angular_formula_value(sweep, st)); + g.mtext = inspected(apply_override(&txt, d, g.formula_value), d); let mut pts = Vec::new(); arc.tessellate(r * 1e-3, &mut pts); g.dim(pts); @@ -637,6 +644,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let leader_end = d.p14.xy(); let origin = d.defpt.xy(); let meas = if x_type { (feature.x - origin.x).abs() } else { (feature.y - origin.y).abs() }; + g.formula_value = Some(linear_formula_value(meas, st)); g.mtext = linear_text(meas, d, st, ""); g.measurement = meas; let (tw, _) = measure(&g.mtext); @@ -656,6 +664,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let arc = Arc::new(c, c.dist(d.defpt.xy()).max(1e-9), c.angle_to(d.p13.xy()), c.angle_to(d.p14.xy())); let meas = r * arc.sweep(); // DIMARCSYM: the arc symbol before the text (0), over it (1) or none (2). + g.formula_value = Some(linear_formula_value(meas, st)); g.mtext = linear_text(meas, d, st, if st.arc_symbol == 0 { "⌒" } else { "" }); g.measurement = meas; let mut pts = Vec::new(); diff --git a/crates/render/src/dim/text.rs b/crates/render/src/dim/text.rs index 18672dbb3a..62fdf33d44 100644 --- a/crates/render/src/dim/text.rs +++ b/crates/render/src/dim/text.rs @@ -49,7 +49,7 @@ pub(super) fn linear_text(meas: f64, d: &Dimension, st: &DimStyle, prefix: &str) let alt = format_linear(v * st.alt_factor, &af).1; s += &format!(" [{}]", post(&st.alt_post, &alt)); } - inspected(apply_override(&s, d, Some(shown_value(v, nf.decimals))), d) + inspected(apply_override(&s, d, Some(linear_formula_value(meas, st))), d) } /// A measurement rounded as the dimension shows it (`decimals` places), for a formula's `<>`: @@ -60,6 +60,29 @@ pub(super) fn shown_value(v: f64, decimals: u8) -> f64 { if r.is_finite() { r } else { v } } +/// What a formula's `<>` stands for in a linear dimension: the measurement (`meas`, drawing +/// units) times DIMLFAC, rounded by DIMRND and then to the resolution the dimension shows +/// (decimal places, or 1/2^n of a unit in architectural and fractional units). +pub(crate) fn linear_formula_value(meas: f64, st: &DimStyle) -> f64 { + let v = meas * st.linear_factor; + let v = if st.round > 0.0 && st.round.is_finite() { (v / st.round).round() * st.round } else { v }; + if matches!(st.linear_unit, 4 | 5) { + let k = 2f64.powi(i32::from(st.decimals.min(8))); + let r = (v * k).round() / k; + if r.is_finite() { r } else { v } + } else { + shown_value(v, st.decimals) + } +} + +/// What a formula's `<>` stands for in an angular dimension: the angle in degrees, rounded to +/// the decimal places shown in decimal degrees; in other angle units (degrees/minutes/seconds, +/// grads, radians, surveyor's) the exact angle. +pub(crate) fn angular_formula_value(radians: f64, st: &DimStyle) -> f64 { + let deg = radians.to_degrees(); + if st.angular_unit == 0 { shown_value(deg, st.angular_decimals) } else { deg } +} + /// DIMINSPECT: the label and the rate either side of the value, two spaces apart. pub(super) fn inspected(value: String, d: &Dimension) -> String { match &d.marks.inspect { diff --git a/crates/render/src/textformula.rs b/crates/render/src/textformula.rs index 9bf6d62d00..fcb0a071e8 100644 --- a/crates/render/src/textformula.rs +++ b/crates/render/src/textformula.rs @@ -69,33 +69,32 @@ pub const FUNCTIONS: &[(&str, &str, &str)] = &[ ]; /// What a formula can refer to: the time, the file and the layout. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct Env { - /// Local date and time: year, month, day, hour, minute, second. - pub now: (i32, u32, u32, u32, u32, u32), + /// Local date and time: year, month, day, hour, minute, second; `None` where there is no + /// clock to read (then date formulas and fields keep the result they have). + pub now: Option<(i32, u32, u32, u32, u32, u32)>, + /// The drawing's file name and the sheet (layout) name; empty when not known here (then + /// FILENAME() and SHEET() keep the result they have). pub file: String, pub sheet: String, /// A dimension's measurement, which `<>` stands for in its formula. pub measured: Option, } -impl Default for Env { - fn default() -> Self { - Env { now: (2000, 1, 1, 0, 0, 0), file: String::new(), sheet: "Model".into(), measured: None } - } -} - -/// The local date and time now (UTC where the time zone is unknown). -pub fn local_now() -> (i32, u32, u32, u32, u32, u32) { +/// The local date and time now (UTC where the time zone is unknown); `None` on the web build, +/// which has no clock to read here: date formulas and fields then keep their saved results +/// instead of showing a made-up date. +pub fn local_now() -> Option<(i32, u32, u32, u32, u32, u32)> { #[cfg(not(target_arch = "wasm32"))] { let z = jiff::Zoned::now(); let clamp = |v: i8| u32::try_from(v).unwrap_or(0); - (i32::from(z.year()), clamp(z.month()), clamp(z.day()), clamp(z.hour()), clamp(z.minute()), clamp(z.second())) + Some((i32::from(z.year()), clamp(z.month()), clamp(z.day()), clamp(z.hour()), clamp(z.minute()), clamp(z.second()))) } #[cfg(target_arch = "wasm32")] { - (2000, 1, 1, 0, 0, 0) + None } } @@ -116,6 +115,9 @@ pub fn evaluate(formula: &str, env: &Env) -> Option { if is_formula(formula) { return Some(match eval(formula.trim_start().trim_start_matches('='), env) { Ok(v) => v.show(), + // Something this place can't know (the clock, the file or sheet name): the formula + // keeps the result it has. + Err(Err::Unknown) => return None, Err(e) => e.to_string(), }); } @@ -148,6 +150,8 @@ enum Err { Num, /// The formula can't be read. Syntax, + /// A value not known here (no clock, no file or sheet name): not an error to show. + Unknown, } impl std::fmt::Display for Err { @@ -158,6 +162,7 @@ impl std::fmt::Display for Err { Err::Div0 => "#DIV/0!", Err::Num => "#NUM!", Err::Syntax => "#ERROR!", + Err::Unknown => "#N/A", }) } } @@ -340,8 +345,24 @@ fn format_number(v: f64, fmt: &str) -> String { } fn looks_like_date_format(f: &str) -> bool { - let l = f.to_ascii_lowercase(); - l.contains('y') || l.contains('d') || l.contains("mm") && !l.contains('0') || l.contains('h') + // Text in double quotes is literal (`0.0" days"`), and a format with digit placeholders + // (`0`, `#`) is a number format. + let mut quoted = false; + let l: String = f + .chars() + .filter(|c| { + if *c == '"' { + quoted = !quoted; + return false; + } + !quoted + }) + .collect::() + .to_ascii_lowercase(); + if l.contains(['0', '#']) { + return false; + } + l.contains('y') || l.contains('d') || l.contains("mm") || l.contains('h') } // ---------- parsing and evaluation ---------- @@ -549,7 +570,14 @@ impl P<'_> { let a = self.unary()?; if self.is_op(&["^"]).is_some() { self.i += 1; - let b = self.power()?; + // Each `^` of a chain nests one level deeper: counted like parentheses. + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(Err::Syntax); + } + let b = self.power(); + self.depth -= 1; + let b = b?; let v = a.num()?.powf(b.num()?); return if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; } @@ -678,8 +706,10 @@ fn call(name: &str, a: &[Val], env: &Env) -> R { let checked = |v: f64| if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; let chars = |v: &Val| v.text().chars().collect::>(); let count = |v: f64| if v.is_finite() { usize::try_from(v.clamp(0.0, 1e6) as i64).unwrap_or(0) } else { 0 }; - let (y, mo, d, h, mi, s) = env.now; - let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + let now = env.now.map(|(y, mo, d, h, mi, s)| { + serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0 + }); + let known = |t: &str| if t.is_empty() { Err(Err::Unknown) } else { Ok(Val::Text(t.to_string())) }; match name { "ABS" => Ok(Val::Num(n0(a)?.abs())), "ACOS" => checked(n0(a)?.acos()), @@ -748,8 +778,8 @@ fn call(name: &str, a: &[Val], env: &Env) -> R { _ => format_number(v.num()?, &f), })) } - "TODAY" => Ok(Val::Date(now.floor())), - "NOW" => Ok(Val::Date(now)), + "TODAY" => Ok(Val::Date(now.ok_or(Err::Unknown)?.floor())), + "NOW" => Ok(Val::Date(now.ok_or(Err::Unknown)?)), "DATE" => { let (yy, mm, dd) = (n0(a)?, n1(a)?, arg(a, 2)?.num()?); if !(yy.is_finite() && mm.is_finite() && dd.is_finite()) || yy.abs() > 9999.0 || mm.abs() > 12_000.0 || dd.abs() > 1e6 { @@ -762,8 +792,8 @@ fn call(name: &str, a: &[Val], env: &Env) -> R { "DAY" => Ok(Val::Num(parts(n0(a)?).2 as f64)), "HOUR" => Ok(Val::Num(parts(n0(a)?).3 as f64)), "MINUTE" => Ok(Val::Num(parts(n0(a)?).4 as f64)), - "FILENAME" => Ok(Val::Text(env.file.clone())), - "SHEET" => Ok(Val::Text(env.sheet.clone())), + "FILENAME" => known(&env.file), + "SHEET" => known(&env.sheet), _ => Err(Err::Name), } } @@ -799,12 +829,14 @@ fn field(code: &str, env: &Env) -> Option { Some((n, f)) => (n.trim(), Some(f.trim().trim_matches('"'))), None => (body, None), }; - let (y, mo, d, h, mi, s) = env.now; - let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + let now = env.now.map(|(y, mo, d, h, mi, s)| { + serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0 + }); match name.to_ascii_lowercase().as_str() { - // AutoCAD's date formats are .NET's: MM month, mm minutes, HH hours. - "date" => Some(format_date(now, &net_to_sheet(fmt.unwrap_or("dd.MM.yyyy")))), - "filename" => Some(env.file.clone()), + // AutoCAD's date formats are .NET's: MM month, mm minutes, HH hours. Without a clock the + // field is not known here. + "date" => Some(format_date(now?, &net_to_sheet(fmt.unwrap_or("dd.MM.yyyy")))), + "filename" => Some(env.file.clone()).filter(|f| !f.is_empty()), _ => None, } } @@ -821,13 +853,40 @@ mod tests { use super::*; fn env() -> Env { - Env { now: (2026, 10, 23, 14, 5, 9), file: "plan.dwg".into(), sheet: "4".into(), measured: None } + Env { now: Some((2026, 10, 23, 14, 5, 9)), file: "plan.dwg".into(), sheet: "4".into(), measured: None } } fn ev(f: &str) -> String { evaluate(f, &env()).unwrap_or_default() } + /// Without a clock (the web build) or a file and sheet name (drawing a dimension), date, + /// FILENAME() and SHEET() formulas and date fields keep their saved result instead of + /// showing a made-up one (#2318 review). + #[test] + fn unknown_clock_or_names_keep_the_saved_result() { + let blind = Env::default(); + assert_eq!(evaluate("=TODAY()", &blind), None); + assert_eq!(evaluate("=FILENAME()", &blind), None); + assert_eq!(evaluate("=SHEET()", &blind), None); + assert_eq!(evaluate("%<\\AcVar date \\f \"dd.MM.yyyy\">%", &blind), None); + assert_eq!(evaluate("=1+1", &blind).as_deref(), Some("2")); + assert_eq!(ev("=FILENAME()"), "plan.dwg"); + } + + /// A long chain of `^` is refused at the nesting limit, not run into deep recursion (#2318 + /// review); quoted text in a number format doesn't make it a date format. + #[test] + fn power_chains_are_bounded_and_quoted_words_are_not_dates() { + let chain = format!("={}2", "2^".repeat(5000)); + assert_eq!(ev(&chain), "#ERROR!"); + assert_eq!(ev("=2^3^2"), "512"); + assert!(!looks_like_date_format("0.0\" days\"")); + assert!(!looks_like_date_format("0 \"thick\"")); + assert!(looks_like_date_format("dd.mm.yyyy")); + assert!(looks_like_date_format("hh:mm")); + } + /// Huge or infinite dates never overflow (a crash in a test build, nonsense otherwise). #[test] fn huge_date_serials_do_not_overflow() { From 5af81aba38744056d6088a40a9ebf8484699c999 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:53:46 +0200 Subject: [PATCH 09/30] Hatch: review fixes - Hatch patterns inside a block are not boundary or cutting-edge geometry: a continuous (geometry-only) build leaves their strokes out. - The background colour is read from HATCHBACKGROUNDCOLOR first, CADCraft's own copy only when that is missing. - The hatch background tests are registered (they were not being run). - Custom pattern folder: an unreadable folder says why instead of "does not exist", unreadable entries are skipped, and the pattern limit stops the scan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/tests/it/hatch_options.rs | 37 +++++++++++++++++++++++++ crates/io/src/dxf_read/hatch.rs | 7 +++-- crates/io/tests/it/hatch_background.rs | 27 ++++++++++++++++++ crates/io/tests/it/main.rs | 1 + crates/render/src/hatch.rs | 4 +++ crates/render/src/pipeline.rs | 3 +- crates/ui-egui/src/custom_patterns.rs | 36 ++++++++++++++++++------ 7 files changed, 104 insertions(+), 11 deletions(-) diff --git a/crates/engine/tests/it/hatch_options.rs b/crates/engine/tests/it/hatch_options.rs index 7916681d9e..6200945db5 100644 --- a/crates/engine/tests/it/hatch_options.rs +++ b/crates/engine/tests/it/hatch_options.rs @@ -279,3 +279,40 @@ fn multiline_wall_hatch_keeps_the_room_as_an_island() { let h = handle(&s.execute("hatch", &json!({ "points": [[0, 5]], "pattern": "SOLID" })).unwrap()); assert_eq!(hatch(&s, &h).loops.len(), 2, "outer face + the room as an island"); } + +/// A block holding a room outline and a patterned hatch bounds a picked area by the outline, +/// not by the hatch's pattern strokes (#2323 review). +#[test] +fn a_blocks_hatch_pattern_does_not_bound_a_pick() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [10.0, 10.0]); + let inner = handle(&s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "ANSI31", "scale": 1 })).unwrap()); + assert!(!hatch(&s, &inner).solid); + s.execute("block", &json!({ "name": "ROOM", "base": [0, 0], "handles": [r, inner], "keep": "delete" })).unwrap(); + s.execute("insert", &json!({ "name": "ROOM", "at": [0, 0] })).unwrap(); + let h = handle(&s.execute("hatch", &json!({ "points": [[5, 5]] })).unwrap()); + let hh = hatch(&s, &h); + assert_eq!(hh.loops.len(), 1, "{:?}", hh.loops.iter().map(|l| l.vertices.len()).collect::>()); + let l = &hh.loops[0]; + let b = cadcraft_engine::geom::Bounds2::from_points(l.vertices.iter().map(|v| v.p)); + assert!((b.width() - 10.0).abs() < 1e-6 && (b.height() - 10.0).abs() < 1e-6, "the whole room: {b:?}"); +} +/// The outline a block gives hatch boundaries and cutting edges: its lines, not the strokes of a +/// patterned hatch inside it (#2323 review). +#[test] +fn a_blocks_boundary_geometry_leaves_out_hatch_patterns() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [10.0, 10.0]); + let inner = handle(&s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "ANSI31", "scale": 1 })).unwrap()); + s.execute("block", &json!({ "name": "ROOM", "base": [0, 0], "handles": [r, inner], "keep": "delete" })).unwrap(); + s.execute("insert", &json!({ "name": "ROOM", "at": [0, 0] })).unwrap(); + let d = s.doc().unwrap(); + let e = d.model.iter().next().unwrap(); + let opts = cadcraft_render::Options { tolerance: 0.01, text: false, fill: false, continuous: true, ..Default::default() }; + let list = cadcraft_render::build_entities(d, std::iter::once(&**e), &opts); + let lines = list.prims.iter().filter(|p| matches!(p.kind, cadcraft_render::Kind::Polyline)).count(); + assert_eq!(lines, 1, "the room's outline alone"); + // Drawn, the pattern is there. + let list = cadcraft_render::build_entities(d, std::iter::once(&**e), &cadcraft_render::Options::default()); + assert!(list.prims.iter().filter(|p| matches!(p.kind, cadcraft_render::Kind::Polyline)).count() > 10); +} diff --git a/crates/io/src/dxf_read/hatch.rs b/crates/io/src/dxf_read/hatch.rs index 6cbe0b7b1c..94cbde2622 100644 --- a/crates/io/src/dxf_read/hatch.rs +++ b/crates/io/src/dxf_read/hatch.rs @@ -277,7 +277,8 @@ fn pattern_definition(tags: &[Tag], scale: f64, angle: f64, origin: Vec2) -> Vec } /// Hatch origin and background colour from `CADCRAFT` xdata: `1000 HATCH`, `1011` origin, -/// `1000` background colour name (empty for none). Defaults when absent. +/// `1000` background colour name (empty for none), the background from `HATCHBACKGROUNDCOLOR` +/// where that is present. Defaults when absent. fn hatch_xdata(tags: &[Tag]) -> (Vec2, Option) { let x = crate::dxf_ext::xdata(tags, crate::dxf_ext::APP); let Some(at) = x.windows(2).position(|w| matches!(w, [m, o] if m.code == 1000 && m.str() == "HATCH" && o.code == 1011)) else { @@ -286,7 +287,9 @@ fn hatch_xdata(tags: &[Tag]) -> (Vec2, Option) { let val = |k: usize, code: i32| x.get(at + k).filter(|t| t.code == code); let coord = |k: usize, code: i32| val(k, code).map(Tag::f64).filter(|v| v.is_finite()).unwrap_or(0.0); let origin = Vec2::new(coord(1, 1011), coord(2, 1021)); - (origin, val(4, 1000).and_then(|t| Color::parse(&t.str())).or_else(|| acad_background(tags))) + // The interoperable HATCHBACKGROUNDCOLOR first (another program may have changed it), our + // own copy when it is missing. + (origin, acad_background(tags).or_else(|| val(4, 1000).and_then(|t| Color::parse(&t.str())))) } /// The background colour AutoCAD keeps in `HATCHBACKGROUNDCOLOR` xdata (`1071`). diff --git a/crates/io/tests/it/hatch_background.rs b/crates/io/tests/it/hatch_background.rs index 6032044deb..78bed2ce22 100644 --- a/crates/io/tests/it/hatch_background.rs +++ b/crates/io/tests/it/hatch_background.rs @@ -68,3 +68,30 @@ fn a_cleared_background_stays_cleared() { let h = again.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); assert_eq!(h.background, None); } + +/// Another program changed HATCHBACKGROUNDCOLOR but kept CADCraft's own copy: the standard +/// value wins (#2323 review). +#[test] +fn autocads_background_wins_over_a_stale_private_copy() { + // The 1071 value AutoCAD's xdata holds for a colour. + let acad_value = |c: Color| { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), hatch(Some(c))).unwrap(); + let text = cadcraft_io::write_dxf(&d); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let at = lines.windows(2).rposition(|w| w[0] == "1001" && w[1] == "HATCHBACKGROUNDCOLOR").unwrap(); + let v = lines[at + 2..].windows(2).find(|w| w[0] == "1071").unwrap()[1].to_string(); + (text, v) + }; + let (text, old) = acad_value(Color::Index(3)); + let (_, new) = acad_value(Color::Index(5)); + let edited = text.replacen(&format!("1071\n{old}\n"), &format!("1071\n{new}\n"), 1).replacen( + &format!("1071\r\n{old}\r\n"), + &format!("1071\r\n{new}\r\n"), + 1, + ); + assert_ne!(edited, text); + let back = cadcraft_io::read_dxf(edited.as_bytes()).unwrap(); + let h = back.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.background, Some(Color::Index(5))); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index a88ff5f4e5..20a581183c 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -27,6 +27,7 @@ mod entity_props_roundtrip; mod followups_626; mod groups_roundtrip; mod hatch_assoc_roundtrip; +mod hatch_background; mod hatch_pattern_def; mod helix_roundtrip; mod layout_paper_units; diff --git a/crates/render/src/hatch.rs b/crates/render/src/hatch.rs index 1bfeb1b6ce..366e56d2e6 100644 --- a/crates/render/src/hatch.rs +++ b/crates/render/src/hatch.rs @@ -46,6 +46,10 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, h: &Hatch, rgb: Ink, { b.tris(ctx, ink(bg, layer_color, ctx.block_color), &fill::triangulate_evenodd(&loops)); } + // Geometry for hatch boundaries and cutting edges: a pattern's strokes bound nothing. + if b.opts.continuous { + return; + } // The area being looked at, in the hatch's units. let view = b.opts.view.and_then(|v| { let inv = ctx.xf.inverse()?; diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 9584dabfa7..39cbb38a00 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -38,7 +38,8 @@ pub struct Options { /// caller must discard; see [`Options::cancelled`]. pub cancel: Option>, /// Draw every curve as one continuous stroke, without its linetype's dashes: the geometry - /// itself, for hatch boundaries and cutting edges taken from what blocks draw. + /// itself, for hatch boundaries and cutting edges taken from what blocks draw. Hatch + /// patterns are left out then (their strokes bound nothing). pub continuous: bool, } diff --git a/crates/ui-egui/src/custom_patterns.rs b/crates/ui-egui/src/custom_patterns.rs index 7b8b8cdb47..48677864f6 100644 --- a/crates/ui-egui/src/custom_patterns.rs +++ b/crates/ui-egui/src/custom_patterns.rs @@ -54,15 +54,16 @@ pub fn scan(folder: &str) -> (Vec, Option) { if dir.is_empty() { return (Vec::new(), None); } - let Ok(rd) = std::fs::read_dir(dir) else { - return (Vec::new(), Some(crate::tl!("This folder does not exist").to_string())); + let rd = match std::fs::read_dir(dir) { + Ok(rd) => rd, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Vec::new(), Some(crate::tl!("This folder does not exist").to_string())), + // There but not readable (permissions, not a folder…): say why. + Err(e) => return (Vec::new(), Some(format!("{}: {e}", crate::tl!("The folder can't be read")))), }; let mut files: Vec = Vec::new(); for entry in rd.take(MAX_FILES * 20) { - let entry = match entry { - Ok(e) => e, - Err(e) => return (Vec::new(), Some(format!("{}: {e}", crate::tl!("The folder can't be read")))), - }; + // An entry that can't be read (removed meanwhile, no permission) is left out. + let Ok(entry) = entry else { continue }; // `file_type` does not follow symbolic links: a link to a file elsewhere is not read. let path = entry.path(); if entry.file_type().is_ok_and(|t| t.is_file()) && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("pat")) { @@ -73,7 +74,7 @@ pub fn scan(folder: &str) -> (Vec, Option) { files.sort(); files.truncate(MAX_FILES); let mut out = Vec::new(); - for path in files { + 'files: for path in files { if std::fs::metadata(&path).map(|m| m.len()).unwrap_or(u64::MAX) > MAX_FILE_BYTES { continue; } @@ -82,7 +83,7 @@ pub fn scan(folder: &str) -> (Vec, Option) { let text = String::from_utf8_lossy(&bytes); for p in parse_pat(&text).items { if out.len() >= MAX_PATTERNS { - break; + break 'files; } out.push(Found { file: path.to_string_lossy().to_string(), name: p.name, description: p.description, lines: p.lines }); } @@ -225,4 +226,23 @@ mod tests { } let _ = std::fs::remove_dir_all(dir); } + + /// The pattern limit holds across files, and a path that is a file is not "missing". + #[test] + fn the_pattern_limit_counts_every_file() { + let dir = std::env::temp_dir().join(format!("cadcraft-many-pat-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for f in ["a", "b", "c"] { + let many: String = (0..2000).map(|i| format!("*{f}{i}, p\n0, 0,0, 0,1\n")).collect(); + std::fs::write(dir.join(format!("{f}.pat")), &many).unwrap(); + } + let (found, _) = super::scan(&dir.to_string_lossy()); + assert_eq!(found.len(), super::MAX_PATTERNS); + assert!(!found.iter().any(|p| p.name.starts_with('C') && p.name[1..].parse::().is_ok_and(|n| n >= 1000))); + let (none, problem) = super::scan(&dir.join("a.pat").to_string_lossy()); + assert!(none.is_empty()); + let problem = problem.unwrap_or_default(); + assert!(!problem.contains("does not exist"), "{problem}"); + let _ = std::fs::remove_dir_all(dir); + } } From 3bcfb17cd12ec3a9c7b2c981d90261076651baeb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 21:23:11 +0200 Subject: [PATCH 10/30] Text formulas: ^ left to right; a replaced AutoCAD field is not written back - ^ groups left to right as in a spreadsheet (=2^3^2 is 64), worked out in a loop. - A text whose AutoCAD field was replaced by plain text no longer writes the field's ACAD_FIELD dictionary and FIELD objects, so reopening the drawing does not bring the field back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/src/dxf_raw.rs | 21 ++++++++ crates/io/tests/it/text_formula_roundtrip.rs | 50 ++++++++++++++++++++ crates/render/src/textformula.rs | 31 ++++++------ 3 files changed, 88 insertions(+), 14 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index fc60843a02..85185ecc66 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -894,6 +894,27 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); } + // A text whose AutoCAD field was replaced (its formula holds no field any more) drops the + // field: its `ACAD_FIELD` dictionary and the fields under it are not written (the extension + // dictionary's entry goes with them), so reopening does not bring the field back. + let fieldless: HashSet = all_entities(d) + .filter(|e| match &e.kind { + EntityKind::Text(t) => !t.formula.as_deref().is_some_and(|f| f.contains("%<\\")), + EntityKind::MText(t) => !t.formula.as_deref().is_some_and(|f| f.contains("%<\\")), + _ => false, + }) + .map(|e| e.handle.hex()) + .collect(); + if !fieldless.is_empty() { + for o in f.objects.iter().filter(|o| is_dictionary(&o.kind) && owners.get(&o.handle.hex()).is_some_and(|w| fieldless.contains(w))) { + let t: Vec = o.tags.iter().map(tag).collect(); + for (k, h) in entries(&t) { + if up(&k) == "ACAD_FIELD" { + alive_memo.insert(norm(&h), false); + } + } + } + } for o in &f.objects { let mut path: Vec = Vec::new(); let mut cur = o.handle.hex(); diff --git a/crates/io/tests/it/text_formula_roundtrip.rs b/crates/io/tests/it/text_formula_roundtrip.rs index c94134afc3..ad07af830b 100644 --- a/crates/io/tests/it/text_formula_roundtrip.rs +++ b/crates/io/tests/it/text_formula_roundtrip.rs @@ -165,3 +165,53 @@ fn a_cleared_formula_is_not_restored_from_old_xdata() { } } } + +/// A text with an AutoCAD field (its extension dictionary's ACAD_FIELD → TEXT → FIELD), as +/// another program writes it: `field` is the field code. +fn with_field(field: &str) -> String { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Text(text("old", None))).unwrap(); + // Group codes without their padding, one group a line. + let dxf = String::from_utf8(cadcraft_io::write(&d, "a.dxf").unwrap()).unwrap().lines().map(str::trim).collect::>().join("\n"); + let at = dxf.find("\n0\nTEXT\n5\n").unwrap() + "\n0\nTEXT\n5\n".len(); + let end = at + dxf[at..].find('\n').unwrap(); + let h = dxf[at..end].trim().to_string(); + let mut out = format!("{}\n102\n{{ACAD_XDICTIONARY\n360\nFFF01\n102\n}}{}", &dxf[..end], &dxf[end..]); + let objects = out.find("\n2\nOBJECTS\n").unwrap(); + let close = objects + out[objects..].find("\n0\nENDSEC").unwrap(); + let objs = format!( + "\n0\nDICTIONARY\n5\nFFF01\n330\n{h}\n100\nAcDbDictionary\n280\n1\n3\nACAD_FIELD\n360\nFFF02\ + \n0\nDICTIONARY\n5\nFFF02\n330\nFFF01\n100\nAcDbDictionary\n280\n1\n3\nTEXT\n360\nFFF03\ + \n0\nFIELD\n5\nFFF03\n330\nFFF02\n100\nAcDbField\n1\nTEXT\n2\n{field}" + ); + out.insert_str(close, &objs); + out +} + +/// A text whose AutoCAD field is replaced by plain text drops the field when saved; one that +/// keeps it writes it back (#2324 review). +#[test] +fn a_replaced_field_is_not_restored_on_reopen() { + let src = with_field("Date: %<\\AcVar Date \\f \"yyyy\">%"); + let read = cadcraft_io::read(src.as_bytes(), "a.dxf").unwrap(); + let t = read.model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some((e.handle, t.clone())) } else { None }).unwrap(); + assert!(t.1.formula.as_deref().is_some_and(|f| f.contains("%<\\AcVar")), "{:?}", t.1.formula); + // Kept: written back. + let again = cadcraft_io::read(&cadcraft_io::write(&read, "a.dxf").unwrap(), "a.dxf").unwrap(); + assert!(again.model.iter().any(|e| matches!(&e.kind, EntityKind::Text(x) if x.formula.is_some()))); + // Replaced: gone for good. + let mut edited = read; + edited + .modify_entity(t.0, |e| { + if let EntityKind::Text(x) = &mut e.kind { + x.value = "plain".into(); + x.formula = None; + } + }) + .unwrap(); + let bytes = cadcraft_io::write(&edited, "a.dxf").unwrap(); + assert!(!String::from_utf8_lossy(&bytes).contains("AcDbField"), "the field objects are not written"); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let t = back.model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!((t.value.as_str(), t.formula.as_deref()), ("plain", None)); +} diff --git a/crates/render/src/textformula.rs b/crates/render/src/textformula.rs index fcb0a071e8..b56fcdb144 100644 --- a/crates/render/src/textformula.rs +++ b/crates/render/src/textformula.rs @@ -567,19 +567,17 @@ impl P<'_> { Ok(a) } fn power(&mut self) -> R { - let a = self.unary()?; - if self.is_op(&["^"]).is_some() { + // Left to right, as in a spreadsheet: =2^3^2 is (2^3)^2 = 64. A loop, so a long chain + // takes no stack. + let mut a = self.unary()?; + while self.is_op(&["^"]).is_some() { self.i += 1; - // Each `^` of a chain nests one level deeper: counted like parentheses. - self.depth += 1; - if self.depth > MAX_DEPTH { - return Err(Err::Syntax); - } - let b = self.power(); - self.depth -= 1; - let b = b?; + let b = self.unary()?; let v = a.num()?.powf(b.num()?); - return if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; + if !v.is_finite() { + return Err(Err::Num); + } + a = Val::Num(v); } Ok(a) } @@ -878,9 +876,14 @@ mod tests { /// review); quoted text in a number format doesn't make it a date format. #[test] fn power_chains_are_bounded_and_quoted_words_are_not_dates() { - let chain = format!("={}2", "2^".repeat(5000)); - assert_eq!(ev(&chain), "#ERROR!"); - assert_eq!(ev("=2^3^2"), "512"); + // Longer than any formula may be: refused. + assert_eq!(ev(&format!("={}2", "2^".repeat(5000))), "#ERROR!"); + // A long chain is no deep nesting: worked out (here too big), no stack used up. + assert_eq!(ev(&format!("={}2", "2^".repeat(900))), "#NUM!"); + assert_eq!(ev(&format!("={}1", "1^".repeat(900))), "1"); + // Left to right, as in a spreadsheet. + assert_eq!(ev("=2^3^2"), "64"); + assert_eq!(ev("=-2^2"), "4"); assert!(!looks_like_date_format("0.0\" days\"")); assert!(!looks_like_date_format("0 \"thick\"")); assert!(looks_like_date_format("dd.mm.yyyy")); From 31e3194666e562c60cf8179a28945659eec440a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 22:17:38 +0200 Subject: [PATCH 11/30] TRIM on a hatch: about linear work for the hover preview The inside tests use edges by horizontal band (the same crossings as point_in_polygon, memory bounded), edge splitting looks only at corners in the edge's x range, and duplicate edges and loop chaining use a point grid, instead of scanning every edge for every candidate. A 20,000-sided hatch trims well within a second. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/trim_hatch.rs | 197 +++++++++++++++++++++++++--- 1 file changed, 181 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/trim_hatch.rs b/crates/engine/src/cmd/trim_hatch.rs index 4d04fac586..090d354429 100644 --- a/crates/engine/src/cmd/trim_hatch.rs +++ b/crates/engine/src/cmd/trim_hatch.rs @@ -25,12 +25,22 @@ fn edges_of(poly: &[Vec2]) -> Vec<(Vec2, Vec2)> { (0..n).filter_map(|i| Some((*poly.get(i)?, *poly.get((i + 1) % n)?))).filter(|(a, b)| a.dist(*b) > 0.0).collect() } -/// Split the edge a→b at the points of `pts` lying on it (within `tol`). +/// Split the edge a→b at the points of `pts` lying on it (within `tol`). `pts` is sorted by x: +/// only those within the edge's x range are looked at. fn split_at(a: Vec2, b: Vec2, pts: &[Vec2], tol: f64, out: &mut Vec<(Vec2, Vec2)>) { let ln = Line::new(a, b); let len = a.dist(b); - let mut ts: Vec = - pts.iter().filter(|p| ln.dist(**p) <= tol).map(|p| ln.param_of(*p)).filter(|t| *t * len > tol && (1.0 - *t) * len > tol).collect(); + let (x0, x1) = (a.x.min(b.x) - tol, a.x.max(b.x) + tol); + let from = pts.partition_point(|p| p.x < x0); + let to = pts.partition_point(|p| p.x <= x1).max(from); + let mut ts: Vec = pts + .get(from..to) + .unwrap_or(&[]) + .iter() + .filter(|p| ln.dist(**p) <= tol) + .map(|p| ln.param_of(*p)) + .filter(|t| *t * len > tol && (1.0 - *t) * len > tol) + .collect(); ts.sort_by(f64::total_cmp); ts.dedup_by(|x, y| (*x - *y).abs() * len <= tol); let mut prev = a; @@ -63,17 +73,126 @@ fn despike(mut poly: Vec, tol: f64) -> Vec { poly } +/// Points by grid cell (`cell` wide), to find the ones near a point without a scan of all. +struct PointGrid { + cell: f64, + cells: std::collections::HashMap<(i64, i64), Vec>, +} + +impl PointGrid { + fn new(cell: f64) -> Self { + PointGrid { cell: if cell.is_finite() && cell > 0.0 { cell } else { 1.0 }, cells: std::collections::HashMap::new() } + } + fn key(&self, p: Vec2) -> (i64, i64) { + // Saturating float-to-int casts: a far or non-finite point lands in an edge cell. + ((p.x / self.cell).floor() as i64, (p.y / self.cell).floor() as i64) + } + fn insert(&mut self, p: Vec2, i: usize) { + let k = self.key(p); + self.cells.entry(k).or_default().push(i); + } + /// The indices stored in the cells around `p` (its own and the eight next to it). + fn near(&self, p: Vec2) -> impl Iterator + '_ { + let (x, y) = self.key(p); + (-1..=1) + .flat_map(move |dx| (-1..=1).map(move |dy| (x.saturating_add(dx), y.saturating_add(dy)))) + .filter_map(|k| self.cells.get(&k)) + .flatten() + .copied() + } +} + +/// Most edge entries over all bands of an [`EdgeRows`]. +const MAX_BAND_ENTRIES: usize = 4_000_000; + +/// Edges by horizontal band, for even-odd inside tests and nearness in about the square root +/// of the edge count each, not a scan of every edge (the hover preview runs these per move). +struct EdgeRows { + edges: Vec<(Vec2, Vec2)>, + rows: Vec>, + y0: f64, + dy: f64, +} + +impl EdgeRows { + fn new(edges: Vec<(Vec2, Vec2)>) -> Self { + let (lo, hi) = + edges.iter().flat_map(|(a, b)| [a.y, b.y]).filter(|y| y.is_finite()).fold((f64::MAX, f64::MIN), |(l, h), y| (l.min(y), h.max(y))); + let mut n = ((edges.len() as f64).sqrt() as usize).clamp(1, 4096); + let (mut y0, mut dy) = if lo < hi { (lo, (hi - lo) / n as f64) } else { (lo.min(0.0), 1.0) }; + // Edges as tall as the area are in every band: past this many entries one band holds + // them all (a plain scan per test, as without bands), so memory stays bounded. + let probe = EdgeRows { edges: Vec::new(), rows: vec![Vec::new(); n], y0, dy }; + let entries: usize = edges.iter().map(|(a, b)| probe.row(a.y.max(b.y)) - probe.row(a.y.min(b.y)) + 1).fold(0, usize::saturating_add); + if entries > MAX_BAND_ENTRIES { + n = 1; + (y0, dy) = (0.0, 1.0); + } + let mut r = EdgeRows { edges: Vec::new(), rows: vec![Vec::new(); n], y0, dy }; + for (i, (a, b)) in edges.iter().enumerate() { + let (r0, r1) = (r.row(a.y.min(b.y)), r.row(a.y.max(b.y))); + for row in r.rows.get_mut(r0..=r1).into_iter().flatten() { + row.push(i); + } + } + r.edges = edges; + r + } + fn row(&self, y: f64) -> usize { + let k = ((y - self.y0) / self.dy).floor(); + if k.is_nan() || k < 0.0 { 0 } else { (k as usize).min(self.rows.len().saturating_sub(1)) } + } + /// Inside by even-odd crossings (as `point_in_polygon` over every loop together). + fn contains(&self, p: Vec2) -> bool { + let mut inside = false; + for &i in self.rows.get(self.row(p.y)).into_iter().flatten() { + // In `point_in_polygon`'s order (from an edge's end back to its start), so points on + // the boundary come out the same. + let Some(&(b, a)) = self.edges.get(i) else { continue }; + if (a.y > p.y) != (b.y > p.y) { + let x = (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x; + if p.x < x { + inside = !inside; + } + } + } + inside + } + /// Whether an edge passes within `d` of `p`. + fn near(&self, p: Vec2, d: f64) -> bool { + let (r0, r1) = (self.row(p.y - d), self.row(p.y + d)); + self.rows.get(r0..=r1).into_iter().flatten().flatten().any(|&i| self.edges.get(i).is_some_and(|(a, b)| Line::new(*a, *b).dist(p) <= d)) + } +} + /// Chain directed edges into closed loops (start of one = end of the last). -fn chain(mut edges: Vec<(Vec2, Vec2)>, tol: f64) -> Vec> { +fn chain(edges: Vec<(Vec2, Vec2)>, tol: f64) -> Vec> { + let mut starts = PointGrid::new(tol); + for (i, (a, _)) in edges.iter().enumerate() { + starts.insert(*a, i); + } + let mut used = vec![false; edges.len()]; let mut loops = Vec::new(); - while let Some((a, b)) = edges.pop() { + for first in (0..edges.len()).rev() { + let (Some(&(a, b)), Some(false)) = (edges.get(first), used.get(first).copied()) else { continue }; + if let Some(u) = used.get_mut(first) { + *u = true; + } let mut pts = vec![a]; let mut end = b; let mut guard = 0usize; while !end.near(a, tol) && guard < MAX_EDGES { guard += 1; - let Some(i) = edges.iter().position(|(p, _)| p.near(end, tol)) else { break }; - let (p, q) = edges.swap_remove(i); + let next = starts + .near(end) + .filter(|&i| !used.get(i).copied().unwrap_or(true)) + .filter(|&i| edges.get(i).is_some_and(|(p, _)| p.near(end, tol))) + .min(); + let Some(i) = next else { break }; + if let Some(u) = used.get_mut(i) { + *u = true; + } + let Some(&(p, q)) = edges.get(i) else { break }; pts.push(p); end = q; } @@ -108,7 +227,8 @@ pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Opti l.pop(); } } - let in_hatch = |p: Vec2| loops.iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1; + let hatch_rows = EdgeRows::new(loops.iter().flat_map(|l| edges_of(l)).collect()); + let in_hatch = |p: Vec2| hatch_rows.contains(p); // A pick on the hatch's edge (the hatch is picked along its boundary too) trims the part // just inside it. let pick = if in_hatch(pick) { @@ -154,19 +274,22 @@ pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Opti .map(|l| despike(l, snap)) .filter(|l| l.len() >= 3) .collect(); - let Some(outer) = face.first().cloned() else { return Err(no_cut()) }; - let in_face = |p: Vec2| point_in_polygon(&outer, p) && !face.iter().skip(1).any(|i| point_in_polygon(i, p)); + if face.is_empty() { + return Err(no_cut()); + } + // Inside the face: its outer loop and not an island (even-odd over its loops, the islands + // lying inside the outer loop and apart). + let face_rows = EdgeRows::new(face.iter().flat_map(|l| edges_of(l)).collect()); + let in_face = |p: Vec2| face_rows.contains(p); // A face made of the hatch's own boundary only: no cutting edge crosses this area. - let on_hatch = |a: Vec2, z: Vec2| { - let m = (a + z) * 0.5; - loops.iter().any(|l| edges_of(l).iter().any(|(p, q)| Line::new(*p, *q).dist(m) <= snap * 10.0)) - }; + let on_hatch = |a: Vec2, z: Vec2| hatch_rows.near((a + z) * 0.5, snap * 10.0); if face.iter().all(|f| edges_of(f).iter().all(|(a, z)| on_hatch(*a, *z))) { return Err(no_cut()); } // Every candidate edge: the hatch's loops split where the face's corners touch them, and the // face's own edges. - let corners: Vec = face.iter().flatten().copied().collect(); + let mut corners: Vec = face.iter().flatten().copied().filter(|p| p.is_finite()).collect(); + corners.sort_by(|p, q| p.x.total_cmp(&q.x)); let mut cand: Vec<(Vec2, Vec2)> = Vec::new(); for l in &loops { for (a, z) in edges_of(l) { @@ -181,6 +304,7 @@ pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Opti let off = size * 1e-6; let left_over = |p: Vec2| in_hatch(p) && !in_face(p); let mut kept: Vec<(Vec2, Vec2)> = Vec::new(); + let mut kept_at = PointGrid::new(snap); for (a, z) in cand { let d = (z - a).normalized(); let m = (a + z) * 0.5; @@ -191,9 +315,10 @@ pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Opti } let e = if l { (a, z) } else { (z, a) }; // The same piece of boundary twice (a loop edge that is also a face edge). - if kept.iter().any(|(p, q)| p.near(e.0, snap) && q.near(e.1, snap)) { + if kept_at.near(e.0).any(|i| kept.get(i).is_some_and(|(p, q)| p.near(e.0, snap) && q.near(e.1, snap))) { continue; } + kept_at.insert(e.0, kept.len()); kept.push(e); } let outlines = chain(kept, snap * 10.0); @@ -315,6 +440,46 @@ mod tests { let _ = trim_hatch(&h, &[], Vec2::ZERO); } + /// A hatch with a many-sided boundary trims in about linear time (the hover preview runs + /// this on every move; #2329 review). + #[test] + fn a_detailed_hatch_trims_quickly() { + let n = 20_000; + let c = Vec2::new(5.0, 5.0); + let vertices: Vec = + (0..n).map(|i| PolyVertex::new(c + Vec2::from_angle(std::f64::consts::TAU * f64::from(i) / f64::from(n)) * 5.0)).collect(); + let h = hatch(vec![HatchLoop { vertices, outer: true, sources: Vec::new() }]); + let cut = [Segment::Line(Line::new(Vec2::new(7.0, -5.0), Vec2::new(7.0, 15.0)))]; + let t = std::time::Instant::now(); + let (left, _) = trim_hatch(&h, &cut, Vec2::new(9.0, 5.0)).unwrap(); + let took = t.elapsed(); + let a = area(&left.unwrap()); + // The circle (78.54) less the cap right of x = 7 (19.82). + assert!((a - 58.72).abs() < 1.0, "{a}"); + assert!(took.as_secs_f64() < 1.0, "took {took:?}"); + } + + /// The banded inside test agrees with `point_in_polygon` (two loops, one inside the + /// other, points on band edges and vertices included), with and without bands. + #[test] + fn banded_inside_test_matches_the_plain_one() { + let star: Vec = (0..40).map(|i| Vec2::from_angle(f64::from(i) * 0.157) * if i % 2 == 0 { 10.0 } else { 4.0 }).collect(); + let inner: Vec = (0..12).map(|i| Vec2::from_angle(f64::from(i) * 0.5236) * 2.0).collect(); + let edges: Vec<(Vec2, Vec2)> = edges_of(&star).into_iter().chain(edges_of(&inner)).collect(); + let rows = EdgeRows::new(edges); + assert!(rows.rows.len() > 1); + for i in -60..=60 { + for j in -60..=60 { + let p = Vec2::new(f64::from(i) * 0.19, f64::from(j) * 0.19); + let plain = point_in_polygon(&star, p) != point_in_polygon(&inner, p); + assert_eq!(rows.contains(p), plain, "{p:?}"); + } + } + for v in star.iter().chain(&inner) { + assert_eq!(rows.contains(*v), point_in_polygon(&star, *v) != point_in_polygon(&inner, *v), "{v:?}"); + } + } + #[test] fn walls_along_the_hatch_boundary_do_not_stop_the_trim() { // The hatch fills a room whose walls run along its boundary and past its corners; a From 428eb13f8250b6a0e05c8f06d4d4316842bf9db4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 22:20:01 +0200 Subject: [PATCH 12/30] TRIM on a hatch: a test angle clippy reads as a constant Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/trim_hatch.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/trim_hatch.rs b/crates/engine/src/cmd/trim_hatch.rs index 090d354429..bda46c0509 100644 --- a/crates/engine/src/cmd/trim_hatch.rs +++ b/crates/engine/src/cmd/trim_hatch.rs @@ -464,7 +464,7 @@ mod tests { #[test] fn banded_inside_test_matches_the_plain_one() { let star: Vec = (0..40).map(|i| Vec2::from_angle(f64::from(i) * 0.157) * if i % 2 == 0 { 10.0 } else { 4.0 }).collect(); - let inner: Vec = (0..12).map(|i| Vec2::from_angle(f64::from(i) * 0.5236) * 2.0).collect(); + let inner: Vec = (0..12).map(|i| Vec2::from_angle(f64::from(i) * 0.5) * 2.0).collect(); let edges: Vec<(Vec2, Vec2)> = edges_of(&star).into_iter().chain(edges_of(&inner)).collect(); let rows = EdgeRows::new(edges); assert!(rows.rows.len() > 1); From 6616657e90b9794c124dc0fbc8bd78dbc298df7d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 23:57:07 +0200 Subject: [PATCH 13/30] Custom patterns: the folder isn't read on every keystroke While the folder path is being typed the last listing stays; the folder is read once the field is left (or Reload is pressed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/ui-egui/src/custom_patterns.rs | 31 ++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/custom_patterns.rs b/crates/ui-egui/src/custom_patterns.rs index 48677864f6..9edc68b963 100644 --- a/crates/ui-egui/src/custom_patterns.rs +++ b/crates/ui-egui/src/custom_patterns.rs @@ -92,13 +92,16 @@ pub fn scan(folder: &str) -> (Vec, Option) { (out, problem) } -/// The folder's patterns, read again when the folder or the reload count changed. +/// The folder's patterns, read again when the folder or the reload count changed; while +/// `typing` the folder, the last listing stays (a folder isn't read on every keystroke). /// Shared, not copied: the tab asks for it every frame and a folder may hold thousands. -fn listing(folder: &str) -> (std::rc::Rc>, Option) { +fn listing(folder: &str, typing: bool) -> (std::rc::Rc>, Option) { let generation = GENERATION.with(|g| *g.borrow()); LISTING.with(|cell| { let mut l = cell.borrow_mut(); - if l.folder != folder || l.generation != generation { + let stale = l.folder != folder || l.generation != generation; + // The first listing, or a reload, is read even while typing. + if stale && (!typing || l.generation == u64::MAX || l.folder == folder) { let (patterns, problem) = scan(folder); *l = Listing { folder: folder.to_string(), generation, patterns: std::rc::Rc::new(patterns), problem }; } @@ -139,10 +142,11 @@ pub enum TabAction { /// `pattern` and `file`. pub fn tab_ui(ui: &mut egui::Ui, folder: &mut String, pattern: &mut String, file: &mut Option, can_browse: bool) -> TabAction { let mut action = TabAction::None; + let mut typing = false; ui.label(crate::tl!("Folder with hatch pattern files (.pat):")); ui.horizontal(|ui| { let w = ui.available_width() - if can_browse { 150.0 } else { 70.0 }; - ui.add(egui::TextEdit::singleline(folder).desired_width(w.max(120.0)).hint_text(crate::tl!("Folder path"))); + typing = ui.add(egui::TextEdit::singleline(folder).desired_width(w.max(120.0)).hint_text(crate::tl!("Folder path"))).has_focus(); if can_browse && ui.button(crate::tl!("Browse...")).clicked() { action = TabAction::Browse; } @@ -150,7 +154,7 @@ pub fn tab_ui(ui: &mut egui::Ui, folder: &mut String, pattern: &mut String, file reload(); } }); - let (found, problem) = listing(folder); + let (found, problem) = listing(folder, typing); if let Some(p) = &problem { ui.colored_label(Tokens::get().text_dim, p); } @@ -227,6 +231,23 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// While the folder is being typed it isn't read on every keystroke; once typing stops + /// it is. + #[test] + fn a_folder_being_typed_is_read_once_typing_stops() { + let dir = std::env::temp_dir().join(format!("cadcraft-typing-pat-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.pat"), "*ONE, one\n0, 0,0, 0,1\n").unwrap(); + let full = dir.to_string_lossy().to_string(); + let (first, _) = super::listing("", false); + assert!(first.is_empty()); + let (typing, _) = super::listing(&full, true); + assert!(typing.is_empty(), "the last listing stays while typing"); + let (done, _) = super::listing(&full, false); + assert_eq!(done.len(), 1); + let _ = std::fs::remove_dir_all(dir); + } + /// The pattern limit holds across files, and a path that is a file is not "missing". #[test] fn the_pattern_limit_counts_every_file() { From ec32ad2f0a760a7ab77a75c23e20f6b7e841dfff Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:20:10 +0200 Subject: [PATCH 14/30] Keep DXF finishing within upstream's complexity limit The replaced-field lookup moves into its own function. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/src/dxf_raw.rs | 47 ++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index acf6e54608..151f9f3266 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -927,27 +927,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); } - // A text whose AutoCAD field was replaced (its formula holds no field any more) drops the - // field: its `ACAD_FIELD` dictionary and the fields under it are not written (the extension - // dictionary's entry goes with them), so reopening does not bring the field back. - let fieldless: HashSet = all_entities(d) - .filter(|e| match &e.kind { - EntityKind::Text(t) => !t.formula.as_deref().is_some_and(|f| f.contains("%<\\")), - EntityKind::MText(t) => !t.formula.as_deref().is_some_and(|f| f.contains("%<\\")), - _ => false, - }) - .map(|e| e.handle.hex()) - .collect(); - if !fieldless.is_empty() { - for o in f.objects.iter().filter(|o| is_dictionary(&o.kind) && owners.get(&o.handle.hex()).is_some_and(|w| fieldless.contains(w))) { - let t: Vec = o.tags.iter().map(tag).collect(); - for (k, h) in entries(&t) { - if up(&k) == "ACAD_FIELD" { - alive_memo.insert(norm(&h), false); - } - } - } - } + // A text whose AutoCAD field was replaced drops the field (see `replaced_fields`). + alive_memo.extend(replaced_fields(f, d, &owners).into_iter().map(|h| (h, false))); for o in &f.objects { let mut path: Vec = Vec::new(); let mut cur = o.handle.hex(); @@ -1037,6 +1018,30 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { *tags = out; } +/// The `ACAD_FIELD` dictionaries of texts whose AutoCAD field was replaced (their formula holds +/// no field any more): not written, nor the fields under them (the extension dictionary's entry +/// goes with them), so reopening does not bring the field back. `owners`: object → owner. +fn replaced_fields(f: &Foreign, d: &Drawing, owners: &HashMap) -> Vec { + let has_field = |formula: &Option| formula.as_deref().is_some_and(|f| f.contains("%<\\")); + let fieldless: HashSet = all_entities(d) + .filter(|e| match &e.kind { + EntityKind::Text(t) => !has_field(&t.formula), + EntityKind::MText(t) => !has_field(&t.formula), + _ => false, + }) + .map(|e| e.handle.hex()) + .collect(); + let mut out = Vec::new(); + if fieldless.is_empty() { + return out; + } + for o in f.objects.iter().filter(|o| is_dictionary(&o.kind) && owners.get(&o.handle.hex()).is_some_and(|w| fieldless.contains(w))) { + let t: Vec = o.tags.iter().map(tag).collect(); + out.extend(entries(&t).into_iter().filter(|(k, _)| up(k) == "ACAD_FIELD").map(|(_, h)| norm(&h))); + } + out +} + /// Where the entities of types CADCraft doesn't model go: each before the next written entity of /// its space or block (else at the end of it), as `(section, record)` lists by the index of the /// record they precede. Owners come from the written block records. From 2fc041b97494e7ee948407667b3db1fe8d077cfe Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:21:41 +0200 Subject: [PATCH 15/30] CLI perf drawing: the text formula field Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- apps/cadcraft-cli/src/perf.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/cadcraft-cli/src/perf.rs b/apps/cadcraft-cli/src/perf.rs index e52b6107b0..4c11f46d70 100644 --- a/apps/cadcraft-cli/src/perf.rs +++ b/apps/cadcraft-cli/src/perf.rs @@ -56,6 +56,7 @@ fn synthetic(n: usize, side: f64) -> Result EntityKind::Text(d::Text { + formula: None, insert: v3(x, y), align_pt: None, height: s * 0.2, From aa8c500fd065602039df1c4e2e5d16de9d8d66d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:49:34 +0200 Subject: [PATCH 16/30] fmt Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/src/dxf_write/sections.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 5f226df097..ac09800db6 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -171,7 +171,15 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap w.f(146, 0.0); } w.s(0, "ENDTAB"); - let apps = ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP, dxf_ext::HATCH_BACKGROUND_APP, dxf_ext::FORMULA_APP]; + let apps = [ + "ACAD", + dxf_ext::APP, + "AcadAnnotative", + dxf_ext::LAYER_TRANSPARENCY_APP, + dxf_ext::LAYER_DESCRIPTION_APP, + dxf_ext::HATCH_BACKGROUND_APP, + dxf_ext::FORMULA_APP, + ]; let th = table_head(w, "APPID", apps.len()); for app in apps { record_head(w, "APPID", &th, "AcDbRegAppTableRecord"); From 98139c35a860d241be32e525abe9f0d1f6476bf4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 09:57:53 +0200 Subject: [PATCH 17/30] Text formulas: the formula field in upstream 0.15's new objects and round-trip checks Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/doc/src/extents.rs | 1 + crates/doc/src/tests.rs | 1 + crates/io/tests/it/roundtrip/cases.rs | 1 + crates/io/tests/it/roundtrip/cases/geometry.rs | 1 + crates/io/tests/it/roundtrip/compare.rs | 6 ++++-- crates/io/tests/it/roundtrip/dxf/conformance.rs | 1 + crates/io/tests/it/roundtrip/dxf/geometry_groups.rs | 1 + crates/render/tests/it/annotative_orientation.rs | 1 + 8 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index dc2063520f..f7da9f2321 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -345,6 +345,7 @@ mod tests { fn mtext(contents: &str, width: f64) -> crate::MText { crate::MText { + formula: None, insert: Vec3::new(10.0, 10.0, 0.0), height: 2.5, width, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 3e5b5be5b7..fb27b4a639 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -391,6 +391,7 @@ fn plain_attrib(tag: &str) -> Attrib { Attrib { tag: tag.into(), text: Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 1.0, diff --git a/crates/io/tests/it/roundtrip/cases.rs b/crates/io/tests/it/roundtrip/cases.rs index a6031ec8f6..835ba82287 100644 --- a/crates/io/tests/it/roundtrip/cases.rs +++ b/crates/io/tests/it/roundtrip/cases.rs @@ -28,6 +28,7 @@ pub(super) fn drawing() -> Drawing { pub(super) fn text() -> Text { Text { + formula: None, insert: Vec3::new(2.5, -3.75, 4.125), align_pt: None, height: 2.25, diff --git a/crates/io/tests/it/roundtrip/cases/geometry.rs b/crates/io/tests/it/roundtrip/cases/geometry.rs index 35a2cc9dc1..554dedafd9 100644 --- a/crates/io/tests/it/roundtrip/cases/geometry.rs +++ b/crates/io/tests/it/roundtrip/cases/geometry.rs @@ -123,6 +123,7 @@ pub(crate) fn faces() -> Vec { pub(crate) fn mtext() -> MText { MText { + formula: None, insert: Vec3::new(1.25, -2.5, 3.75), height: 2.25, width: 12.5, diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index d4bd1541a6..29f135b066 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -217,7 +217,8 @@ fn common(expected: &Common, actual: &Common, context: &str) { } fn text(expected: &Text, actual: &Text, context: &str) { - let Text { insert, align_pt, height, value, rotation, width_factor, oblique, style, halign, valign } = expected; + let Text { formula, insert, align_pt, height, value, rotation, width_factor, oblique, style, halign, valign } = expected; + equal(formula, &actual.formula, context, "formula"); equal(insert, &actual.insert, context, "insert"); equal(align_pt, &actual.align_pt, context, "align_pt"); equal(height, &actual.height, context, "height"); @@ -231,7 +232,8 @@ fn text(expected: &Text, actual: &Text, context: &str) { } fn mtext(expected: &MText, actual: &MText, context: &str) { - let MText { insert, height, width, attach, rotation, style, contents, line_spacing, line_spacing_exact, columns } = expected; + let MText { formula, insert, height, width, attach, rotation, style, contents, line_spacing, line_spacing_exact, columns } = expected; + equal(formula, &actual.formula, context, "mtext.formula"); equal(insert, &actual.insert, context, "mtext.insert"); equal(height, &actual.height, context, "mtext.height"); equal(width, &actual.width, context, "mtext.width"); diff --git a/crates/io/tests/it/roundtrip/dxf/conformance.rs b/crates/io/tests/it/roundtrip/dxf/conformance.rs index 3f036be2c4..7459735715 100644 --- a/crates/io/tests/it/roundtrip/dxf/conformance.rs +++ b/crates/io/tests/it/roundtrip/dxf/conformance.rs @@ -30,6 +30,7 @@ pub(super) fn model() -> Drawing { &Space::Model, Common::default(), EntityKind::Text(Text { + formula: None, insert: Vec3::new(-3.25, 4.5, 1.75), align_pt: None, height: 2.5, diff --git a/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs index b447638ebb..f43f182450 100644 --- a/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs +++ b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs @@ -64,6 +64,7 @@ fn fixtures() -> Vec { Fixture { wire_type: "MTEXT", kind: EntityKind::MText(MText { + formula: None, insert: Vec3::new(1.25, -2.5, 3.75), height: 2.25, width: 12.5, diff --git a/crates/render/tests/it/annotative_orientation.rs b/crates/render/tests/it/annotative_orientation.rs index ee28b0624b..57010e6bc2 100644 --- a/crates/render/tests/it/annotative_orientation.rs +++ b/crates/render/tests/it/annotative_orientation.rs @@ -25,6 +25,7 @@ fn bounds(rotation: f64, match_orientation: Option<&str>) -> Bounds2 { ]; } let text = Text { + formula: None, insert: Vec3::new(10.0, 5.0, 0.0), align_pt: None, height: 2.5, From 90c9d0648667d34b37f33dc380ffa108bf3b1c1d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 19:50:41 +0200 Subject: [PATCH 18/30] Text formulas: an AutoCAD field the reader declines is kept on save FredApps (#2318): replaced_fields dropped the ACAD_FIELD objects of every text without a field formula, but the reader leaves the formula empty when it declines a field (over 16,384 characters, nested deeper than 8, a child missing), so such a field was lost on save. A field is now dropped only when it resolves to a formula, as the reader would have made of it, and the text no longer holds one. Reading a formula back is also capped (64 KiB): a longer one is not read and the text keeps its value. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/src/dxf_ext.rs | 32 +++++++++++++++++++- crates/io/src/dxf_fields.rs | 14 +++++++++ crates/io/src/dxf_raw.rs | 13 +++++++- crates/io/tests/it/text_formula_roundtrip.rs | 22 ++++++++++++++ 4 files changed, 79 insertions(+), 2 deletions(-) diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 3581b1a68a..a9771297b6 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -26,10 +26,22 @@ pub(crate) const FORMULA_APP: &str = "CADCRAFTFORMULA"; /// A text's formula from its `CADCRAFTFORMULA` extended data. pub(crate) fn formula(tags: &[Tag]) -> Option { let x = xdata(tags, FORMULA_APP); - let s: String = x.iter().filter(|t| t.code == 1000).map(|t| t.str()).collect(); + let mut s = String::new(); + for t in x.iter().filter(|t| t.code == 1000) { + s.push_str(&t.str()); + // A formula longer than any CADCraft writes is not read (the text keeps its value): the + // file alone would bound it otherwise (#2318 review). + if s.len() > MAX_FORMULA_BYTES { + return None; + } + } (!s.is_empty()).then_some(s) } +/// Longest formula read back from a file, in bytes: room for the longest field template the +/// reader resolves (16,384 characters of up to 4 bytes). +const MAX_FORMULA_BYTES: usize = 64 * 1024; + /// A formula as 1000 strings of at most 250 bytes (whole characters). pub(crate) fn formula_chunks(f: &str) -> Vec { // An xdata string holds at most 255 bytes: Hebrew, Cyrillic or Chinese letters take 2 to 4 @@ -940,3 +952,21 @@ mod tests { assert!(is_standard_arrow("_dot")); } } + +#[cfg(test)] +mod formula_cap_tests { + use super::{FORMULA_APP, MAX_FORMULA_BYTES, formula}; + use cadcraft_dxf::Tag; + + /// A formula is read back whole up to the cap; a file's longer one is not read at all. + #[test] + fn an_overlong_formula_is_not_read() { + let tags = |n: usize| { + let mut t = vec![Tag::s(0, "TEXT"), Tag::s(1001, FORMULA_APP)]; + t.extend((0..n).map(|_| Tag::s(1000, "x".repeat(250)))); + t + }; + assert_eq!(formula(&tags(4)).map(|f| f.len()), Some(1000)); + assert_eq!(formula(&tags(MAX_FORMULA_BYTES / 250 + 2)), None); + } +} diff --git a/crates/io/src/dxf_fields.rs b/crates/io/src/dxf_fields.rs index e340b3252c..8ccf05fbd4 100644 --- a/crates/io/src/dxf_fields.rs +++ b/crates/io/src/dxf_fields.rs @@ -82,6 +82,20 @@ fn expand(objects: &HashMap>, h: &str, depth: usize, seen: &mut Some(s) } +/// Whether the `ACAD_FIELD` dictionary `dict` holds a field the reader turns into a formula +/// ([`resolve`] does that only for a field within [`MAX_LEN`] and [`MAX_DEPTH`] whose children are +/// all there). `objects`: the file's dictionaries and fields by handle, upper-case as written. +/// A field the reader declined is kept as it is on save, whatever the text now holds. +pub(crate) fn resolves(objects: &HashMap>, dict: &str) -> bool { + let found = (|| code(objects, &entry(objects.get(dict)?, "TEXT")?, 0))(); + found.is_some_and(|c| c.contains("%<\\")) +} + +/// A record's handle as [`resolves`] keys it. +pub(crate) fn object_handle(tags: &[Tag]) -> Option { + handle_of(tags) +} + /// Give the texts with AutoCAD fields their templates as formulas. pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { let mut objects: HashMap> = HashMap::new(); diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 8d93093500..d863c126aa 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1033,9 +1033,20 @@ fn replaced_fields(f: &Foreign, d: &Drawing, owners: &HashMap) - if fieldless.is_empty() { return out; } + // Only a field the reader made a formula of can have been replaced: one it declined (too long, + // too deep, a child missing) never reached the text, so it stays as it was read (#2318 review). + let mut objects: HashMap> = HashMap::new(); + for o in f.objects.iter().filter(|o| is_dictionary(&o.kind) || o.kind == "FIELD") { + // Keyed by the handle as the file wrote it, as the field entries refer to it. + let t: Vec = o.tags.iter().map(tag).collect(); + let h = crate::dxf_fields::object_handle(&t).unwrap_or_else(|| o.handle.hex()); + objects.insert(h, t); + } for o in f.objects.iter().filter(|o| is_dictionary(&o.kind) && owners.get(&o.handle.hex()).is_some_and(|w| fieldless.contains(w))) { let t: Vec = o.tags.iter().map(tag).collect(); - out.extend(entries(&t).into_iter().filter(|(k, _)| up(k) == "ACAD_FIELD").map(|(_, h)| norm(&h))); + out.extend( + entries(&t).into_iter().filter(|(k, h)| up(k) == "ACAD_FIELD" && crate::dxf_fields::resolves(&objects, &up(h))).map(|(_, h)| norm(&h)), + ); } out } diff --git a/crates/io/tests/it/text_formula_roundtrip.rs b/crates/io/tests/it/text_formula_roundtrip.rs index ad07af830b..24810b755b 100644 --- a/crates/io/tests/it/text_formula_roundtrip.rs +++ b/crates/io/tests/it/text_formula_roundtrip.rs @@ -215,3 +215,25 @@ fn a_replaced_field_is_not_restored_on_reopen() { let t = back.model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); assert_eq!((t.value.as_str(), t.formula.as_deref()), ("plain", None)); } + +/// A field the reader cannot make a formula of (too long, nested too deep, a child missing) +/// never reached the text, so saving keeps it as it was read (#2318 review: it was dropped with +/// its ACAD_FIELD objects, leaving only the cached value). +#[test] +fn a_field_the_reader_declines_is_kept_on_save() { + // Too long: the code goes on in 3 groups past 16,384 characters. + let long = format!("%<\\AcVar Date>% {}", format!("\n3\n{}", "x".repeat(2_000)).repeat(10)); + // A child the code names is not in the file. + let orphan = "Sum: %<\\_FldIdx 0>%\n360\nFFF99"; + for field in [long.as_str(), orphan] { + let src = with_field(field); + let read = cadcraft_io::read(src.as_bytes(), "a.dxf").unwrap(); + assert!(read.model.iter().all(|e| !matches!(&e.kind, EntityKind::Text(t) if t.formula.is_some())), "declined: no formula"); + let out = String::from_utf8_lossy(&cadcraft_io::write(&read, "a.dxf").unwrap()).into_owned(); + assert!(out.contains("AcDbField") && out.contains("ACAD_FIELD"), "the field is written back"); + // And it stays through another round. + let again = cadcraft_io::read(out.as_bytes(), "a.dxf").unwrap(); + let out2 = String::from_utf8_lossy(&cadcraft_io::write(&again, "a.dxf").unwrap()).into_owned(); + assert!(out2.contains("AcDbField")); + } +} From fded7c0c25d85a9a815c630c1d236e0aedab5ece Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 19:54:14 +0200 Subject: [PATCH 19/30] Hatch: a numeric background outside 0..=256 is refused FredApps (#2323): background_param took any i16 and Color::from_aci turns anything outside 0..=255 into ByLayer, so background 1000 or -5 was stored as a ByLayer background instead of being refused. It now takes 0 (ByBlock) to 256 (ByLayer), as parse_color does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/hatch.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 0adade84f1..2e321add7e 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -502,7 +502,9 @@ pub(crate) fn background_param(p: &Value) -> Option Some(None), Value::String(t) if t.trim().is_empty() || t.trim().eq_ignore_ascii_case("none") || t.trim() == "." => Some(None), Value::String(t) => cadcraft_color::Color::parse(t.trim()).map(Some), - v => v.as_i64().and_then(|i| i16::try_from(i).ok()).map(|i| Some(cadcraft_color::Color::from_aci(i))), + // An index colour, 0 (ByBlock) to 256 (ByLayer), as `parse_color` takes it: any other + // number is refused rather than stored as ByLayer (#2323 review). + v => v.as_i64().filter(|i| (0..=256).contains(i)).and_then(|i| i16::try_from(i).ok()).map(|i| Some(cadcraft_color::Color::from_aci(i))), } } @@ -1076,13 +1078,15 @@ mod tests { fn a_bad_background_is_refused() { let mut s = Session::new(); s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); - for bad in [json!("blu"), json!(true), json!({})] { + for bad in [json!("blu"), json!(true), json!({}), json!(1000), json!(-5), json!(257)] { assert!(s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "ANSI31", "background": bad })).is_err(), "{bad}"); } s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap(); let (h, _) = only_hatch(&s); assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": "blu" })).is_err()); assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": "none" })).is_ok()); + assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": 1000 })).is_err()); + assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": 5 })).is_ok(), "an index colour is taken"); } /// A block whose lines are drawn with a dashed linetype: its outline still bounds a hatch, and From ffa731023c32e7e2d11ce9e9eaba8c6d35bad2e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 19:50:13 +0200 Subject: [PATCH 20/30] Text formulas: Chinese labels for Text Formulas and Update Fields The full-translation test main added (#2510) needs a Chinese label for every menu item. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/ui-egui/src/i18n/zh.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 21c86d1fe7..db7529f7b6 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1381,3 +1381,5 @@ Save Layout as Template 将布局另存为样板 Set Dynamic Property 设置动态特性 Units 单位 + Text Formulas 文字公式 + Update Fields 更新字段 From eb8735644795e4878eb30731f695521f7eca073f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 19:52:17 +0200 Subject: [PATCH 21/30] Fit upstream 0.15.1: the new fields in its added objects and tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/annotate/leader.rs | 2 ++ crates/engine/src/cmd/blocks/attdef.rs | 1 + crates/engine/tests/insert_file_field.rs | 1 + crates/io/tests/it/text_carets_roundtrip.rs | 1 + 4 files changed, 5 insertions(+) diff --git a/crates/engine/src/cmd/annotate/leader.rs b/crates/engine/src/cmd/annotate/leader.rs index 1c5ce72767..f93707cf9e 100644 --- a/crates/engine/src/cmd/annotate/leader.rs +++ b/crates/engine/src/cmd/annotate/leader.rs @@ -136,6 +136,7 @@ impl Interactive for LeaderM { }; let text = picked.and_then(|h| s.doc().ok()?.entity(h).cloned()).and_then(|e| match &e.kind { EntityKind::Text(t) => Some(MText { + formula: None, insert: t.insert, height: t.height, width: 0.0, @@ -298,6 +299,7 @@ fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Ann (false, false) => (6, 0.0), }; Some(s.add_entity(EntityKind::MText(MText { + formula: None, insert: v3(end + Vec2::new(dir * z.gap, lift)), height: z.text, width: 0.0, diff --git a/crates/engine/src/cmd/blocks/attdef.rs b/crates/engine/src/cmd/blocks/attdef.rs index 0803cfe95a..8d8857369a 100644 --- a/crates/engine/src/cmd/blocks/attdef.rs +++ b/crates/engine/src/cmd/blocks/attdef.rs @@ -106,6 +106,7 @@ impl AttdefM { s.add_entity(EntityKind::AttDef(Attrib { tag: self.tag.to_uppercase(), text: Text { + formula: None, insert: v3(self.at), align_pt: if left { None } else { Some(v3(self.at)) }, height: self.height, diff --git a/crates/engine/tests/insert_file_field.rs b/crates/engine/tests/insert_file_field.rs index 1365f88b5a..158f3a9bc7 100644 --- a/crates/engine/tests/insert_file_field.rs +++ b/crates/engine/tests/insert_file_field.rs @@ -31,6 +31,7 @@ fn object(handle: u64, kind: &str, tags: Vec) -> ForeignObject { fn read(bytes: &[u8], _name: &str) -> Result { let mut d = Drawing::new_imperial(); let text = Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 2.0, diff --git a/crates/io/tests/it/text_carets_roundtrip.rs b/crates/io/tests/it/text_carets_roundtrip.rs index 1c30dd1a37..7284e08af5 100644 --- a/crates/io/tests/it/text_carets_roundtrip.rs +++ b/crates/io/tests/it/text_carets_roundtrip.rs @@ -7,6 +7,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn text(value: &str) -> Text { Text { + formula: None, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 2.5, From 60709f68c1ae29a10565ab4d3a3fa18afbec03e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 21:05:17 +0200 Subject: [PATCH 22/30] Text formulas: an AutoCAD field's text is saved as read while the field is unchanged ATARYS-LAB (#2318): a date field saved on an earlier day became plain text in AutoCAD after a CADCraft save. CADCraft works the field out for today when it opens the drawing, but the field object still caches the old value, and AutoCAD drops a field whose text does not match its cache. The reader now keeps the text each field showed beside its formula (ForeignExtra::field_text), and the writer writes that text back while the text still holds the same field formula; AutoCAD works the field out again itself. A text whose field was replaced or changed is written as it is now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/doc/src/foreign.rs | 12 ++++++- crates/io/src/dxf_fields.rs | 21 +++++++++++ crates/io/src/dxf_write/entity.rs | 16 +++++++-- crates/io/tests/it/text_formula_roundtrip.rs | 37 ++++++++++++++++++++ 4 files changed, 83 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index d732df2613..81278aba65 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -42,11 +42,21 @@ pub struct ForeignExtra { pub color_book: Option<(String, String)>, /// Other unmodelled property groups (material 347, shadow mode 284). pub props: Vec, + /// A TEXT or MTEXT with an AutoCAD field: the formula the field was read as and the text the + /// file showed. While the formula is unchanged the text is written back as read, so it + /// matches the value cached in the field and AutoCAD keeps the field (it works it out again + /// itself); CADCraft shows the field worked out for today meanwhile. + pub field_text: Option<(String, String)>, } impl ForeignExtra { pub fn is_empty(&self) -> bool { - self.xdict.is_none() && self.reactors.is_empty() && self.xdata.is_empty() && self.color_book.is_none() && self.props.is_empty() + self.xdict.is_none() + && self.reactors.is_empty() + && self.xdata.is_empty() + && self.color_book.is_none() + && self.props.is_empty() + && self.field_text.is_none() } } diff --git a/crates/io/src/dxf_fields.rs b/crates/io/src/dxf_fields.rs index 8ccf05fbd4..6bb65a432a 100644 --- a/crates/io/src/dxf_fields.rs +++ b/crates/io/src/dxf_fields.rs @@ -133,6 +133,27 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { if formulas.is_empty() { return; } + // The text each field showed in the file, kept beside its formula (see `ForeignExtra::field_text`). + let shown: Vec<(Handle, String, String)> = d + .model + .iter() + .chain(d.layouts.iter().flat_map(|l| l.entities.iter())) + .chain(d.blocks.values().flat_map(|b| b.entities.iter())) + .filter_map(|e| { + let f = formulas.get(&e.handle)?; + match &e.kind { + EntityKind::Text(t) => Some((e.handle, f.clone(), t.value.clone())), + EntityKind::MText(t) => Some((e.handle, f.clone(), t.contents.clone())), + _ => None, + } + }) + .collect(); + if !shown.is_empty() { + let foreign = std::sync::Arc::make_mut(&mut d.foreign); + for (h, f, v) in shown { + foreign.entities.entry(h).or_default().field_text = Some((f, v)); + } + } let set = |store: &mut EntityStore| { let hs: Vec = store.iter().filter(|e| formulas.contains_key(&e.handle)).map(|e| e.handle).collect(); for h in hs { diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index d323aaeb60..949bf6b427 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -278,13 +278,24 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo } } +/// The text an AutoCAD field's TEXT or MTEXT is written with while its field is unchanged: as +/// the file showed it, matching the value the field caches. A text whose shown value differs +/// from that cache loses its field in AutoCAD (#2318 review: a date field read on another day). +fn field_text_as_read<'a>(d: &'a Drawing, e: &Entity, formula: Option<&str>) -> Option<&'a str> { + let (f, v) = d.foreign.entities.get(&e.handle)?.field_text.as_ref()?; + (Some(f.as_str()) == formula).then_some(v.as_str()) +} + fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { match &e.kind { EntityKind::Text(t) => { w.s(0, "TEXT"); common(w, e, owner, paper, "AcDbText"); thickness(w, e); - text_tags(w, d, t, None, None); + match field_text_as_read(d, e, t.formula.as_deref()) { + Some(v) => text_tags(w, d, &cadcraft_doc::Text { value: v.to_string(), ..t.clone() }, None, None), + None => text_tags(w, d, t, None, None), + } formula_xdata(w, t.formula.as_deref()); } // Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS. @@ -321,7 +332,8 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo // Drawing direction: 5, by style. w.i(72, 5); // Long contents go in 250-char 3-chunks, the remainder in 1. - let chars: Vec = crate::dxf_read::mtext_dxf::encode_contents(&t.contents).chars().collect(); + let contents = field_text_as_read(d, e, t.formula.as_deref()).unwrap_or(&t.contents); + let chars: Vec = crate::dxf_read::mtext_dxf::encode_contents(contents).chars().collect(); let chunks: Vec = chars.chunks(250).map(|c| c.iter().collect()).collect(); let n = chunks.len(); for (i, c) in chunks.iter().enumerate() { diff --git a/crates/io/tests/it/text_formula_roundtrip.rs b/crates/io/tests/it/text_formula_roundtrip.rs index 24810b755b..f28d04047b 100644 --- a/crates/io/tests/it/text_formula_roundtrip.rs +++ b/crates/io/tests/it/text_formula_roundtrip.rs @@ -237,3 +237,40 @@ fn a_field_the_reader_declines_is_kept_on_save() { assert!(out2.contains("AcDbField")); } } + +/// A text with an AutoCAD date field, worked out for another day than it was saved on, is +/// written back with the text the file showed while its field is unchanged: AutoCAD drops a +/// field whose text differs from the value cached in it (#2318 review, a date field saved on an +/// earlier day). Once the text no longer holds that field, its own text is written. +#[test] +fn a_field_text_is_written_as_read_while_the_field_is_unchanged() { + let field = "Date: %<\\AcVar Date \\f \"yyyy\">%"; + let read = cadcraft_io::read(with_field(field).as_bytes(), "a.dxf").unwrap(); + let (h, t) = read.model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some((e.handle, t.clone())) } else { None }).unwrap(); + assert_eq!(t.value, "old"); + let value_written = |d: &Drawing| { + let back = cadcraft_io::read(&cadcraft_io::write(d, "a.dxf").unwrap(), "a.dxf").unwrap(); + back.model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.value.clone()) } else { None }).unwrap() + }; + // Worked out for today (as opening the drawing does): the file still gets the text it showed. + let mut today = read.clone(); + today + .modify_entity(h, |e| { + if let EntityKind::Text(x) = &mut e.kind { + x.value = "Date: 2026".into(); + } + }) + .unwrap(); + assert_eq!(value_written(&today), "old"); + // Another formula: the text as it is now. + let mut edited = read; + edited + .modify_entity(h, |e| { + if let EntityKind::Text(x) = &mut e.kind { + x.value = "3".into(); + x.formula = Some("=1+2".into()); + } + }) + .unwrap(); + assert_eq!(value_written(&edited), "3"); +} From 140936dce7ab563ccd77e635649ed46bf9a20869 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 20:42:13 +0200 Subject: [PATCH 23/30] EXTEND: pass the edges on (clippy needless_borrow after #2656) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/modify/trim.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index b359f33593..bf19095c22 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -420,7 +420,7 @@ pub(crate) fn extend_result(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) let none = || EngineError::Other("Object does not intersect an edge.".into()); if let Some((ga, _)) = cadcraft_geom::bulge_to_arc(prev, end, bulge) { // An arc end segment runs on round its circle, as an arc does. - let (np, b) = extend_arc_segment(&ga, end, 4.0 * bulge.atan(), &cut).ok_or_else(none)?; + let (np, b) = extend_arc_segment(&ga, end, 4.0 * bulge.atan(), cut).ok_or_else(none)?; if let Some(v) = vs.get_mut(i_end) { v.p = np; } From 3bf07c1bd2874aab6260d491ce90be3bd875234c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 20:45:48 +0200 Subject: [PATCH 24/30] Fit main: the new fields in its added tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/tests/it/mtext_caret_spaces.rs | 1 + crates/render/src/linetype_text.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/crates/io/tests/it/mtext_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs index 8bb1ed071d..86ebd3c6dd 100644 --- a/crates/io/tests/it/mtext_caret_spaces.rs +++ b/crates/io/tests/it/mtext_caret_spaces.rs @@ -31,6 +31,7 @@ fn drawing() -> Result<(Drawing, Vec<(Handle, String)>), Box Date: Wed, 4 Nov 2026 21:01:25 +0200 Subject: [PATCH 25/30] Text formulas: a block reference's attribute formulas are worked out (UPDATEFIELD, opening); a typed value replaces the formula FredApps on #2318: has_formula and apply skipped Insert.attribs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/blocks/attedit.rs | 4 ++ crates/engine/src/textformula.rs | 21 +++++++++++ crates/engine/tests/it/text_formulas.rs | 49 +++++++++++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/crates/engine/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index be59474c59..35b4e19a1e 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -125,12 +125,16 @@ fn all_in_space(s: &Session) -> Result> { /// Change attribute `k` of block reference `h`; returns whether its value changed. fn edit(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&str) -> Option) -> Result { let mut changed = false; + let env = crate::textformula::env(s); s.doc_mut()?.modify_entity(h, |e| { if let EntityKind::Insert(ins) = &mut e.kind && let Some(a) = ins.attribs.get_mut(k) && let Some(v) = f(&a.text.value).filter(|v| *v != a.text.value) { set_value(&mut a.text, v); + // A typed value replaces the attribute's formula (or field); a typed formula is kept + // and shows its result. + crate::textformula::apply_text(&mut a.text, &env, true); changed = true; } })?; diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs index 58ae6c6b19..fad3629ae3 100644 --- a/crates/engine/src/textformula.rs +++ b/crates/engine/src/textformula.rs @@ -40,9 +40,18 @@ pub fn measured(d: &Drawing, dm: &cadcraft_doc::Dimension) -> Option { /// value just typed: typing over an AutoCAD field turns it into plain text, typing a value that /// is not a formula drops the formula. Text, attribute definitions, multiline text, /// multileader text and dimension text (whose `<>` is its measurement, `env.measured`). +/// A block reference's attributes are worked out too (each as one-line text; a multiline +/// attribute's value replaces its contents when it is saved). pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { // Multiline text keeps a result's `\`, `{` and `}` as letters, not formatting codes. let (value, formula, mtext): (&mut String, &mut Option, bool) = match kind { + EntityKind::Insert(i) => { + // The reference's attributes were not typed here: their formulas are only worked out. + for a in &mut i.attribs { + apply_text(&mut a.text, env, false); + } + return; + } EntityKind::Text(t) => (&mut t.value, &mut t.formula, false), EntityKind::AttDef(a) => (&mut a.text.value, &mut a.text.formula, false), EntityKind::MText(t) => (&mut t.contents, &mut t.formula, true), @@ -53,6 +62,17 @@ pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { EntityKind::Dimension(d) => (&mut d.text, &mut d.marks.formula, false), _ => return, }; + work(value, formula, mtext, env, edited); +} + +/// [`apply`] for one line of text: a block reference's attribute, whose value was just typed +/// when `edited` (ATTEDIT, EATTEDIT). +pub fn apply_text(t: &mut cadcraft_doc::Text, env: &Env, edited: bool) { + work(&mut t.value, &mut t.formula, false, env, edited); +} + +/// [`apply`] on a text's value and formula. +fn work(value: &mut String, formula: &mut Option, mtext: bool, env: &Env, edited: bool) { if edited { // Multiline text is read without its formatting codes; one-line text and dimension text // as typed (their braces and backslashes are letters). @@ -91,6 +111,7 @@ fn has_formula(k: &EntityKind) -> bool { EntityKind::MText(t) => t.formula.is_some(), EntityKind::MLeader(m) => m.text.as_ref().is_some_and(|t| t.formula.is_some()), EntityKind::Dimension(d) => d.marks.formula.is_some(), + EntityKind::Insert(i) => i.attribs.iter().any(|a| a.text.formula.is_some()), _ => false, } } diff --git a/crates/engine/tests/it/text_formulas.rs b/crates/engine/tests/it/text_formulas.rs index 974afe1d3d..b74cba779a 100644 --- a/crates/engine/tests/it/text_formulas.rs +++ b/crates/engine/tests/it/text_formulas.rs @@ -199,3 +199,52 @@ fn one_line_text_formulas_keep_braces() { .collect(); assert_eq!(got, [("4".to_string(), Some("=LEN(\"a{b}\")".to_string())), ("{A}\\X".to_string(), Some("=UPPER(\"{a}\\x\")".to_string()))]); } + +/// FredApps on #2318: a block reference's attribute that holds a formula (or a field) is worked +/// out by UPDATEFIELD and when the drawing is opened, as other text is; a value typed over it +/// replaces the formula. +#[test] +fn a_block_references_attribute_formulas_are_worked_out() { + let mut s = Session::new(); + s.execute("attdef", &json!({"tag": "T", "default": "one", "at": [0, 1]})).unwrap(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let hs: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name": "B", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap(); + let r = s.execute("insert", &json!({"name": "B", "at": [100, 0], "attribs": {"T": "old"}})).unwrap(); + let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + let attrib = |s: &Session| { + let EntityKind::Insert(i) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") }; + let t = &i.attribs.iter().find(|a| a.tag == "T").unwrap().text; + (t.value.clone(), t.formula.clone()) + }; + // As read from a file: the formula, with a stale value. + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.attribs.iter_mut().for_each(|a| a.text.formula = Some("=2+3".into())); + } + }) + .unwrap(); + assert_eq!(s.execute("updatefield", &json!({})).unwrap()["updated"], 1); + assert_eq!(attrib(&s), ("5".to_string(), Some("=2+3".to_string()))); + + // Opening the drawing works it out too. + let mut d = s.doc().unwrap().clone(); + d.modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.attribs.iter_mut().for_each(|a| a.text.value = "stale".into()); + } + }) + .unwrap(); + let env = cadcraft_engine::textformula::env(&s); + assert_eq!(cadcraft_engine::textformula::refresh(&mut d, &env), 1); + let EntityKind::Insert(i) = &d.entity(h).unwrap().kind else { panic!("not an insert") }; + assert_eq!(i.attribs.first().map(|a| a.text.value.as_str()), Some("5")); + + // A value typed over it replaces the formula; UPDATEFIELD then leaves it alone. + s.execute("-attedit", &json!({"tag": "T", "find": "5", "replace": "typed"})).unwrap(); + assert_eq!(attrib(&s), ("typed".to_string(), None)); + s.execute("updatefield", &json!({})).unwrap(); + assert_eq!(attrib(&s).0, "typed"); +} From 583682679e82ede25c82ea023fd74dbf83de0832 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 21:20:09 +0200 Subject: [PATCH 26/30] HATCH: a block reference's closed outline bounds a hatch picked by Select objects FredApps on #2323: closed_loop and island_curve did not take a block reference. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/hatch.rs | 6 ++++-- crates/engine/tests/it/hatch_assoc.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 30dfc364de..bc0fee07da 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -143,11 +143,13 @@ fn closed_loop(d: &Drawing, e: &Entity) -> Option> { /// Open curves that can make up an island together (a square drawn as four LINEs, two ARCs /// forming a circle, the inner lines of multiline walls around a room). Closed objects are -/// islands on their own (see `closed_loop`). +/// islands on their own (see `closed_loop`). A block reference counts by the lines it draws: a +/// closed outline inside a block bounds a hatch as the same outline drawn on its own does. fn island_curve(d: &Drawing, e: &Entity) -> bool { matches!( e.kind, - EntityKind::Line(_) + EntityKind::Insert(_) + | EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Ellipse(_) | EntityKind::LwPolyline(_) diff --git a/crates/engine/tests/it/hatch_assoc.rs b/crates/engine/tests/it/hatch_assoc.rs index ac73c27ed4..680cc7c156 100644 --- a/crates/engine/tests/it/hatch_assoc.rs +++ b/crates/engine/tests/it/hatch_assoc.rs @@ -194,3 +194,19 @@ fn interactive_stretch_at_the_command_line_refills() { assert!(hh.associative); assert!(close(area(&hh), 150.0), "area {}", area(&hh)); } + +/// FredApps on #2323: HATCH's Select objects on a block reference whose block holds a closed +/// outline hatches the outline, as picking inside it does. +#[test] +fn a_block_reference_with_a_closed_outline_bounds_a_hatch() { + let mut s = Session::new(); + let r = s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 5] })).unwrap(); + let hs = vec![r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()]; + s.execute("block", &json!({ "name": "FRAME", "base": [0, 0], "handles": hs, "keep": "delete" })).unwrap(); + let ins = s.execute("insert", &json!({ "name": "FRAME", "at": [100, 0] })).unwrap(); + let ins = ins["handle"].as_str().unwrap().to_string(); + let h = Handle::parse_hex(&handle(&s.execute("hatch", &json!({ "handles": [ins] })).unwrap())).unwrap(); + let EntityKind::Hatch(hatch) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not a hatch") }; + let b = Bounds2::from_points(hatch.loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p))); + assert!((b.min.x - 100.0).abs() < 1e-6 && (b.max.x - 110.0).abs() < 1e-6 && (b.max.y - 5.0).abs() < 1e-6, "{b:?}"); +} From 1951a6cc0d4e24e2935807d8357f41e6da0f84b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:02:59 +0200 Subject: [PATCH 27/30] TRIM: a hatch's glow is kept while the cursor stays in the area it was worked out for With its boundary erased, the cursor finds the hatch everywhere inside it, and the hatch was traced against every object around it again on each move, which stalled the cursor in big drawings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/trim_hatch.rs | 8 +++ crates/engine/src/cmd/trimextend.rs | 59 +++++++++++++++++-- crates/engine/tests/it/trim_extend_options.rs | 34 +++++++++++ 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/trim_hatch.rs b/crates/engine/src/cmd/trim_hatch.rs index bda46c0509..c6cd820013 100644 --- a/crates/engine/src/cmd/trim_hatch.rs +++ b/crates/engine/src/cmd/trim_hatch.rs @@ -206,6 +206,13 @@ fn chain(edges: Vec<(Vec2, Vec2)>, tol: f64) -> Vec> { /// Trim the hatch at `pick` against the cutting edges `cut`: the hatch that is left (`None`: none /// of its area is) and the outline of the part taken away (its outer loop, then its islands). pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Option, Vec>)> { + trim_hatch_at(h, cut, pick, &mut Vec::new()) +} + +/// [`trim_hatch`], also giving the area around `pick` that the cutting edges bound (`face`), +/// whether or not a trim there takes anything away: a pick anywhere inside it trims the same. +/// Left empty when no such area is found. +pub(crate) fn trim_hatch_at(h: &Hatch, cut: &[Segment], pick: Vec2, face_out: &mut Vec>) -> Result<(Option, Vec>)> { // The exact extents, arcs included: a circle kept as two half-circle arcs is as tall as it is // wide, not the flat sliver its chords make. let bounds = Bounds2::from_points( @@ -277,6 +284,7 @@ pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Opti if face.is_empty() { return Err(no_cut()); } + face_out.clone_from(&face); // Inside the face: its outer loop and not an island (even-odd over its loops, the islands // lying inside the outer loop and apart). let face_rows = EdgeRows::new(face.iter().flat_map(|l| edges_of(l)).collect()); diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 3e9c7dc989..1ab468a33d 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -249,6 +249,18 @@ type EdgeCache = (usize, Space, bool, Arc>); /// The last glow worked out: the drawing (by address), the cursor and the result. type GlowCache = (usize, (u64, u64), Option); +/// The last hatch glow worked out: the drawing (by address), the hatch, Quick mode and implied +/// edges, the area the cutting edges bound around the cursor (outline, then islands) and the +/// glow. A cursor moving within that area glows the same, without the hatch traced again. +struct HatchGlowCache { + doc: usize, + hatch: Handle, + quick: bool, + implied: bool, + face: Vec>, + glow: Option, +} + pub(crate) struct TrimM { extend: bool, /// Cutting/boundary edges; `None`: all objects. @@ -258,6 +270,7 @@ pub(crate) struct TrimM { undo: Vec>, edge_cache: Mutex>, glow_cache: Mutex>, + hatch_glow_cache: Mutex>, } /// Samples along an object when finding the part of it a trim takes away or an extend adds. @@ -341,7 +354,15 @@ fn uncovered(orig: &EntityKind, others: &[EntityKind]) -> Vec { impl TrimM { pub(crate) fn new(extend: bool) -> Self { - TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new(), edge_cache: Mutex::new(None), glow_cache: Mutex::new(None) } + TrimM { + extend, + edges: None, + stage: Stage::Pick, + undo: Vec::new(), + edge_cache: Mutex::new(None), + glow_cache: Mutex::new(None), + hatch_glow_cache: Mutex::new(None), + } } /// The cutting (boundary) edges with their objects, from the cache while the drawing is the /// same. @@ -378,14 +399,41 @@ impl TrimM { let kinds = uncovered(&new, std::slice::from_ref(&e.kind)); return (!kinds.is_empty()).then_some(Glow { kinds, removing: false }); } + // A hatch: the same as last time while the cursor stays in the area it was worked out + // for (tracing a big hatch among many objects on every move stalls the cursor). + let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize; + let hatch = match &d.entity(h)?.kind { + EntityKind::Hatch(hatch) => Some(hatch), + _ => None, + }; + if hatch.is_some() + && let Ok(cache) = self.hatch_glow_cache.lock() + && let Some(hc) = cache.as_ref() + && (hc.doc, hc.hatch, hc.quick, hc.implied) == (doc, h, quick, implied) + && hc.face.iter().filter(|l| cadcraft_geom::point_in_polygon(l, c)).count() % 2 == 1 + { + return hc.glow.clone(); + } // A trim only meets the edges around the object. let cut = trim_edges(s, Edges { only: self.edges.as_deref(), implied }, h).ok()?; // A hatch's trim is worked out once, for the part it takes away (`trim_result` would // work it out again only to drop that part). - let result = match &d.entity(h)?.kind { - EntityKind::Hatch(hatch) => super::trim_hatch::trim_hatch(hatch, &cut, c).map(|(_, face)| hatch_glow(hatch, face)), - _ => trim_result(s, h, c, &cut).map(|(e, pieces)| uncovered(&e.kind, &pieces)), + let mut face = Vec::new(); + let result = match hatch { + Some(hatch) => super::trim_hatch::trim_hatch_at(hatch, &cut, c, &mut face).map(|(_, face)| hatch_glow(hatch, face)), + None => trim_result(s, h, c, &cut).map(|(e, pieces)| uncovered(&e.kind, &pieces)), }; + let glow = Self::glow_of(result, quick, d, h); + if !face.is_empty() + && let Ok(mut cache) = self.hatch_glow_cache.lock() + { + *cache = Some(HatchGlowCache { doc, hatch: h, quick, implied, face, glow: glow.clone() }); + } + glow + } + /// The glow of a trim's result: what it takes away, or all of the object when a Quick-mode + /// trim of an object no edge crosses erases it. + fn glow_of(result: Result>, quick: bool, d: &Drawing, h: Handle) -> Option { let kinds = match result { Ok(kinds) => kinds, // A Quick-mode trim of an object no edge crosses erases all of it. @@ -554,6 +602,9 @@ impl Interactive for TrimM { if let Ok(c) = self.glow_cache.get_mut() { *c = None; } + if let Ok(c) = self.hatch_glow_cache.get_mut() { + *c = None; + } let quick = quick_mode(s); let implied = edge_mode(s); let extending = self.extend; diff --git a/crates/engine/tests/it/trim_extend_options.rs b/crates/engine/tests/it/trim_extend_options.rs index a0ee4e366a..48b33a0387 100644 --- a/crates/engine/tests/it/trim_extend_options.rs +++ b/crates/engine/tests/it/trim_extend_options.rs @@ -346,3 +346,37 @@ fn lines_inside_a_block_cut_a_hatch() { assert_eq!(left.len(), 1, "trimmed, not erased"); assert!(left[0].loops.iter().flat_map(|l| l.vertices.iter()).all(|v| v.p.x >= 4.0 - 1e-6)); } + +/// TRIM's glow over a big hatch among many objects (its boundary erased, so the cursor finds the +/// hatch everywhere inside it) is worked out once for the area under the cursor, not again on +/// every move within it: tracing the hatch on each move stalled the cursor. +#[test] +fn a_hatch_glow_is_kept_while_the_cursor_stays_in_its_area() { + let mut s = Session::new(); + let mut edges = Vec::new(); + for (a, b) in [((0, 0), (40000, 0)), ((40000, 0), (40000, 24000)), ((40000, 24000), (0, 24000)), ((0, 24000), (0, 0))] { + let r = s.execute("line", &json!({"points": [[a.0, a.1], [b.0, b.1]]})).unwrap(); + edges.push(r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()); + } + s.execute("hatch", &json!({"points": [[20000, 12000]], "pattern": "SOLID"})).unwrap(); + s.execute("erase", &json!({"handles": edges})).unwrap(); + // Furniture in the right part of the room, a wall line across it. + for i in 0..400 { + let (x, y) = (17500.0 + f64::from(i % 20) * 1100.0, 1000.0 + f64::from(i / 20) * 1100.0); + s.execute("circle", &json!({"center": [x, y], "radius": 300})).unwrap(); + s.execute("line", &json!({"points": [[x - 500.0, y - 500.0], [x + 500.0, y + 400.0]]})).unwrap(); + } + s.execute("line", &json!({"points": [[16000, -100], [16000, 30000]]})).unwrap(); + s.cmdline("trim").unwrap(); + let at = |i: u32| cadcraft_engine::geom::Vec2::new(4000.0 + f64::from(i) * 50.0, 12000.0); + let t = std::time::Instant::now(); + let first = s.glow(at(0)); + let once = t.elapsed(); + assert!(first.as_ref().is_some_and(|(_, removing)| *removing), "the left part glows"); + let t = std::time::Instant::now(); + for i in 1..=40 { + assert_eq!(s.glow(at(i)), first, "the same part glows at {:?}", at(i)); + } + let moves = t.elapsed(); + assert!(moves < once * 4, "40 moves took {moves:?}, one trace {once:?}"); +} From f22ff801888067e8846663bdf285db6b0ad0b977 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:48:09 +0200 Subject: [PATCH 28/30] Fit main: the new fields in its added code and tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/io/tests/it/text_formula_roundtrip.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/io/tests/it/text_formula_roundtrip.rs b/crates/io/tests/it/text_formula_roundtrip.rs index f28d04047b..d680fd864b 100644 --- a/crates/io/tests/it/text_formula_roundtrip.rs +++ b/crates/io/tests/it/text_formula_roundtrip.rs @@ -95,6 +95,7 @@ fn attribute_and_multileader_formulas_roundtrip() { d.add(&Space::Model, Common::default(), EntityKind::AttDef(def.clone())).unwrap(); d.blocks.insert("B".into(), cadcraft_doc::Block::new("B").into()); let ins = cadcraft_doc::Insert { + clip: Default::default(), block: "B".into(), insert: Vec3::new(5.0, 0.0, 0.0), scale: Vec3::new(1.0, 1.0, 1.0), From 63848a76c3419a42e0c4d030564a6e1d04eac8e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:54:27 +0200 Subject: [PATCH 29/30] EXTEND: a click shows the extension, a second click extends (no work while the cursor moves) --- crates/engine/src/cmd/trimextend.rs | 47 ++++++++++++++++++- crates/engine/src/lib.rs | 5 ++ crates/engine/tests/it/trim_extend_options.rs | 29 +++++++++++- crates/ui-egui/src/canvas.rs | 4 ++ crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/zh.tsv | 1 + 6 files changed, 84 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 0b50f061f2..02d7bbd8d6 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -241,6 +241,9 @@ enum Stage { Edge, /// "Select objects to erase or ": the objects picked so far. Erase(Vec), + /// EXTEND clicked an object: its extension shows (`TrimM::shown`) until a second click on it + /// extends it. Working the extension out on every cursor move lagged. + Confirm(Handle, Vec2), } /// The cutting (boundary) edges of one drawing and space, kept while the cursor moves: the @@ -271,6 +274,8 @@ pub(crate) struct TrimM { edge_cache: Mutex>, glow_cache: Mutex>, hatch_glow_cache: Mutex>, + /// The extension EXTEND shows while it waits for the second click ([`Stage::Confirm`]). + shown: Option, } /// Samples along an object when finding the part of it a trim takes away or an extend adds. @@ -362,6 +367,7 @@ impl TrimM { edge_cache: Mutex::new(None), glow_cache: Mutex::new(None), hatch_glow_cache: Mutex::new(None), + shown: None, } } /// The cutting (boundary) edges with their objects, from the cache while the drawing is the @@ -568,6 +574,7 @@ impl Interactive for TrimM { } Stage::Edges(_) => Prompt::new("Select objects or", Accept::SELECT).default("select all"), Stage::Erase(_) => Prompt::new("Select objects to erase or", Accept::SELECT).default("exit"), + Stage::Confirm(..) => Prompt::new("Click the object again to extend it, or pick another", Accept::POINT).kw(&["Undo"]), Stage::Fence(pts) => match pts.last() { None => Prompt::new("Specify first fence point", Accept::POINT), Some(l) => Prompt::new("Specify next fence point", Accept::POINT).kw(&["Undo"]).base(*l), @@ -610,6 +617,31 @@ impl Interactive for TrimM { let extending = self.extend; match self.stage.clone() { Stage::Mode | Stage::Project | Stage::Edge => self.option(s, i), + Stage::Confirm(h, at) => { + self.shown = None; + self.stage = Stage::Pick; + let Input::Point(p) = i else { + // Enter, Undo and the rest as at the first prompt. + return self.input(s, i); + }; + let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; + let space = s.space(); + match s.pick_object(&space, p, ap)? { + // The second click on the object: extend it as shown. + Some(again) if again == h => { + let r = self.step(s, |m, s| apply(s, h, at, extending, m.edges(quick, implied), quick).map(|_| ())); + if let Err(e) = r { + s.echo(e.to_string()); + } + self.show_edges(s); + Ok(Step::Continue) + } + // Another object: show its extension instead. + Some(_) => self.input(s, Input::Point(p)), + // Empty space: the extension is dropped. + None => Ok(Step::Continue), + } + } Stage::Edges(mut picked) => { match i { Input::Pick(hs) => { @@ -722,6 +754,15 @@ impl Interactive for TrimM { self.stage = Stage::Line(p); return Ok(Step::Continue); }; + // EXTEND from a click: show the extension first, extend on the second click. + if extending + && s.clicked + && let Some(glow) = self.work_out_glow(s, p) + { + self.shown = Some(glow); + self.stage = Stage::Confirm(h, p); + return Ok(Step::Continue); + } let r = self.step(s, |m, s| apply(s, h, p, extending, m.edges(quick, implied), quick).map(|_| ())); if let Err(e) = r { s.echo(e.to_string()); @@ -763,7 +804,11 @@ impl Interactive for TrimM { } } fn glow(&self, s: &Session, c: Vec2) -> Option { - if self.stage != Stage::Pick { + if let Stage::Confirm(..) = self.stage { + return self.shown.clone(); + } + // EXTEND shows its extension on a click, not under the cursor. + if self.stage != Stage::Pick || self.extend { return None; } let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd20d84b3b..dcdaa38a49 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -94,6 +94,10 @@ pub struct Session { /// it resumes when that command ends. One level, as in AutoCAD. pub suspended: Option, pub log: Vec, + /// The point being input came from a click in the drawing (the window sets it around the + /// click), not from typed text, a script or LISP: EXTEND shows its result on a first click + /// and extends on a second. + pub clicked: bool, pub last_command: Option, /// LASTPOINT. pub last_point: Vec2, @@ -191,6 +195,7 @@ impl Session { running: None, in_script: false, suspended: None, + clicked: false, log: Vec::new(), last_command: None, last_point: Vec2::ZERO, diff --git a/crates/engine/tests/it/trim_extend_options.rs b/crates/engine/tests/it/trim_extend_options.rs index 48b33a0387..f52e160cbd 100644 --- a/crates/engine/tests/it/trim_extend_options.rs +++ b/crates/engine/tests/it/trim_extend_options.rs @@ -275,14 +275,39 @@ fn trim_glows_the_part_a_pick_takes_away() { assert_eq!(lines(&s).len(), 4); } +/// EXTEND shows nothing under the cursor: a click shows the part it adds, a second click on the +/// object extends it. Typed points (scripts, LISP) extend at once. #[test] -fn extend_glows_the_part_a_pick_adds() { +fn extend_shows_the_part_a_click_adds_and_extends_on_a_second_click() { + use cadcraft_engine::geom::Vec2; + use cadcraft_engine::prompt::Input; let mut s = session(&["0,0 5,0", "10,-5 10,5"]); s.cmdline("EXTEND").unwrap(); - let (pts, removing) = glow_points(&s, (4.0, 0.0)).expect("a glow over the line"); + assert!(glow_points(&s, (4.0, 0.0)).is_none(), "no work while the cursor moves"); + let click = |s: &mut Session, x: f64, y: f64| { + s.clicked = true; + s.input(Input::Point(Vec2::new(x, y))).unwrap(); + s.clicked = false; + }; + click(&mut s, 4.0, 0.0); + // Shown wherever the cursor is, the drawing unchanged. + let (pts, removing) = glow_points(&s, (3.0, 30.0)).expect("the extension shows"); assert!(!removing); let (lo, hi) = pts.iter().flatten().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); assert!((lo - 5.0).abs() < 1e-2 && (hi - 10.0).abs() < 1e-3, "{lo} {hi}"); + assert!(lines(&s).contains(&((0.0, 0.0), (5.0, 0.0)))); + // A click in empty space drops it; a click and a second click extend. + click(&mut s, 3.0, 30.0); + assert!(glow_points(&s, (3.0, 30.0)).is_none()); + click(&mut s, 4.0, 0.0); + click(&mut s, 2.0, 0.0); + assert!(glow_points(&s, (3.0, 30.0)).is_none()); + assert!(lines(&s).contains(&((0.0, 0.0), (10.0, 0.0))), "{:?}", lines(&s)); + s.cmdline("").unwrap(); + // A typed point extends at once. + let mut s = session(&["0,0 5,0", "10,-5 10,5"]); + s.script("EXTEND 4,0\n\n").unwrap(); + assert!(lines(&s).contains(&((0.0, 0.0), (10.0, 0.0))), "{:?}", lines(&s)); } #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 850fa4b548..3aa5d66ead 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -768,10 +768,12 @@ fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickCo if let Some((_, earlier)) = releases.split_last() { for pos in earlier.iter().filter(|p| context.rect.contains(**p)) { let w = effective_point(app, context.xf.to_world(*pos), &context.xf, ui.ctx()); + app.session.clicked = true; let result = match app.canvas.snap { Some(hit) => app.session.input_snapped(hit), None => app.session.input(Input::Point(w)), }; + app.session.clicked = false; if let Err(e) = result { app.session.echo(e.to_string()); } @@ -915,10 +917,12 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.cmd.buffer.clear(); } // Preserve a snap's viewport origin for DIST, and its deferred curve where needed. + app.session.clicked = true; let result = match app.canvas.snap { Some(hit) => app.session.input_snapped(hit), None => app.session.input(Input::Point(p)), }; + app.session.clicked = false; if let Err(e) = result { app.session.echo(e.to_string()); } diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a34105023d..b786d74a79 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1030,3 +1030,4 @@ Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text The drawing changed. Close the window and open it again. Чертёж изменился. Закройте окно и откройте его снова. + Click the object again to extend it, or pick another Щёлкните объект ещё раз, чтобы удлинить его, или выберите другой diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index b1ba668ec4..6ce21277ea 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1478,3 +1478,4 @@ menu View 视图 Ctrl+Enter to apply Ctrl+Enter 应用 Edit Text 编辑文字 The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。 + Click the object again to extend it, or pick another 再次单击该对象以延伸,或选择另一个对象 From 64a2d34b9a7a5dab49cb864edeb1cf6314759b87 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 14:07:41 +0200 Subject: [PATCH 30/30] Hatch background: its APPID is written again after the merge --- crates/io/src/dxf_write/sections.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 93d082239a..952ca144b0 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -182,7 +182,15 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap *t = Tag::s(345, h); } } - let apps = ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP, dxf_ext::FORMULA_APP]; + let apps = [ + "ACAD", + dxf_ext::APP, + "AcadAnnotative", + dxf_ext::LAYER_TRANSPARENCY_APP, + dxf_ext::LAYER_DESCRIPTION_APP, + dxf_ext::HATCH_BACKGROUND_APP, + dxf_ext::FORMULA_APP, + ]; let th = table_head(w, "APPID", apps.len()); for app in apps { record_head(w, "APPID", &th, "AcDbRegAppTableRecord");