diff --git a/Cargo.lock b/Cargo.lock index ff182c4170..9e15ef8f77 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -818,6 +818,7 @@ dependencies = [ "cadcraft-fonts", "cadcraft-geom", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)", + "jiff", "lyon_tessellation", "rayon", "serde_json", @@ -2897,6 +2898,58 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" + +[[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/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, diff --git a/crates/constraints/src/tests.rs b/crates/constraints/src/tests.rs index eadc7a3c2e..c6426ed7d6 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 dc4635c7ab..0bca5e639d 100644 --- a/crates/doc/src/entity/dim.rs +++ b/crates/doc/src/entity/dim.rs @@ -90,6 +90,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 75857eb303..569b84ff50 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 9f29c07b68..d5dae698e6 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -599,6 +599,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, @@ -618,6 +619,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, @@ -684,6 +686,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/foreign.rs b/crates/doc/src/foreign.rs index 539982cb7e..16f3c512fc 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/doc/src/tables/tablebreak.rs b/crates/doc/src/tables/tablebreak.rs index 48137f1168..8366887f6f 100644 --- a/crates/doc/src/tables/tablebreak.rs +++ b/crates/doc/src/tables/tablebreak.rs @@ -162,6 +162,25 @@ impl Table { b } + /// The top-left corner, width and height of cell (`row`, `col`) — over its merged span — in + /// the part that holds the row. + pub fn cell_rect(&self, row: usize, col: usize) -> Option<(Vec2, f64, f64)> { + if col >= self.col_widths.len() || row >= self.row_heights.len() { + return None; + } + let (rs, cs) = + self.cells.get(row).and_then(|r| r.get(col)).and_then(|c| c.merged).map_or((1, 1), |(a, b)| (a.max(1) as usize, b.max(1) as usize)); + let x: f64 = self.col_widths.iter().take(col).map(|w| size(*w)).sum(); + let w: f64 = self.col_widths.iter().skip(col).take(cs).map(|w| size(*w)).sum(); + for part in self.parts() { + let Some(at) = part.rows.iter().position(|r| *r == row) else { continue }; + let y: f64 = part.rows.iter().take(at).map(|r| size(self.row_heights.get(*r).copied().unwrap_or(0.0))).sum(); + let h: f64 = part.rows.iter().skip(at).take(rs).map(|r| size(self.row_heights.get(*r).copied().unwrap_or(0.0))).sum(); + return Some((part.origin + Vec2::new(x, -y), w, h)); + } + None + } + /// The cell (row, col) under `p`, in any part. pub fn cell_at_point(&self, p: Vec2) -> Option<(usize, usize)> { for part in self.parts() { @@ -216,6 +235,16 @@ mod tests { } } + #[test] + fn cell_rect_covers_the_merged_span_and_hostile_indices_are_none() { + let mut t = table(3); + assert_eq!(t.cell_rect(1, 1), Some((Vec2::new(2.0, -1.0), 3.0, 1.0))); + t.cells[0][0].merged = Some((1, 2)); + assert_eq!(t.cell_rect(0, 0), Some((Vec2::ZERO, 5.0, 1.0))); + assert_eq!(t.cell_rect(9, 0), None); + assert_eq!(t.cell_rect(0, usize::MAX), None); + } + #[test] fn unbroken_is_one_part() { let t = table(5); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index f94893a54b..0de58620e0 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -212,6 +212,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, @@ -433,6 +434,7 @@ fn plain_attrib(tag: &str) -> Attrib { Attrib { tag: tag.into(), text: Text { + formula: None, insert: Vec3::ZERO, align_pt: None, height: 1.0, @@ -573,6 +575,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, @@ -598,6 +601,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, @@ -613,6 +617,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/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/annotate/mleader.rs b/crates/engine/src/cmd/annotate/mleader.rs index 9b4e74128b..e23854c9c6 100644 --- a/crates/engine/src/cmd/annotate/mleader.rs +++ b/crates/engine/src/cmd/annotate/mleader.rs @@ -21,6 +21,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, @@ -96,6 +97,8 @@ pub(super) struct MLeaderM { block: bool, block_name: String, block_center: bool, + /// The in-place editor's box while the text is asked for. + editor: Option, } impl MLeaderM { @@ -118,8 +121,21 @@ impl MLeaderM { block: o.block && s.doc().is_ok_and(|d| d.block(&s.last_used.mleader_block).is_some()), block_name: s.last_used.mleader_block.clone(), block_center: o.block_center, + editor: None, } } + /// Where the text goes while it is asked for: next to the landing, as the multileader will + /// place it. + fn refresh_editor(&mut self, s: &Session) { + self.editor = if self.wants_text() && self.opt.is_none() { + mleader_kind(s, &self.leader(None), "X", self.landing).and_then(|k| match k { + EntityKind::MLeader(m) => m.text.map(|t| MText { contents: String::new(), ..t }), + _ => None, + }) + } else { + None + }; + } /// Keep the order and Options for the next MLEADER. fn remember(&self, s: &mut Session) { s.last_used.mleader = MLeaderOptions { @@ -319,6 +335,30 @@ impl Interactive for MLeaderM { } } fn input(&mut self, s: &mut Session, i: Input) -> Result { + let step = self.answer(s, i); + self.refresh_editor(s); + step + } + fn editing_mtext(&self) -> Option { + self.editor.clone() + } + fn preview(&self, s: &Session, c: Vec2) -> Vec { + if self.opt.is_some() || self.wants_text() || self.leader_done || self.pts.is_empty() { + return Vec::new(); + } + let text = self.text.as_deref().unwrap_or(""); + let next = self.constrained(c); + let shape = mleader_kind(s, &self.leader(Some(next)), text, self.landing) + .and_then(|k| crate::cmd::mleader_content::apply(s, k, &self.content_spec()).ok()); + // The segment being placed, drawn as well in case the multileader preview hides it. + let mut out = vec![EntityKind::Line(cadcraft_doc::Line { a: v3(*self.pts.last().unwrap_or(&next)), b: v3(next) })]; + out.extend(shape); + out + } +} + +impl MLeaderM { + fn answer(&mut self, s: &mut Session, i: Input) -> Result { if let Some(o) = self.opt { self.opt = self.option(s, o, i); self.remember(s); @@ -353,14 +393,4 @@ impl Interactive for MLeaderM { } if self.leader_done && !self.wants_text() { self.finish(s) } else { Ok(Step::Continue) } } - fn preview(&self, s: &Session, c: Vec2) -> Vec { - if self.opt.is_some() || self.wants_text() || self.leader_done || self.pts.is_empty() { - return Vec::new(); - } - let text = self.text.as_deref().unwrap_or(""); - mleader_kind(s, &self.leader(Some(self.constrained(c))), text, self.landing) - .and_then(|k| crate::cmd::mleader_content::apply(s, k, &self.content_spec()).ok()) - .into_iter() - .collect() - } } diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 4a0ba3ae68..b8944391e4 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -511,6 +511,7 @@ fn attdef_kind( EntityKind::AttDef(Attrib { tag: tag.to_ascii_uppercase(), text: Text { + formula: None, insert: v3(at), align_pt: if left { None } else { Some(v3(at)) }, height, diff --git a/crates/engine/src/cmd/blocks/attdef.rs b/crates/engine/src/cmd/blocks/attdef.rs index 542afabfc9..1372c17eb6 100644 --- a/crates/engine/src/cmd/blocks/attdef.rs +++ b/crates/engine/src/cmd/blocks/attdef.rs @@ -107,6 +107,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/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index e86826265a..834364798a 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -126,12 +126,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/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 24007bc918..8c2d1d14ed 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -40,6 +40,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, @@ -82,6 +83,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, @@ -106,6 +108,11 @@ pub(super) struct TextM { /// Run by a LISP routine (`command`): one line of text ends the command, as AutoLISP's /// `command` runs TEXT; typed and in scripts each line asks for the next. single_line: bool, + /// The in-place editor's box for the line being typed (once point, height and angle are known). + editor: Option, + /// TEXTSIZE when the command started: the default height and the size of the frame shown + /// before the height is given. + size: f64, } impl TextM { @@ -118,8 +125,42 @@ impl TextM { asking_justify: false, line: 0, single_line: s.lisp_running(), + editor: None, + size: s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2), } } + /// Where line `line` starts: one line spacing (5/3 of the height) below the one before. + fn line_at(a: Vec2, h: f64, r: f64, line: usize) -> Vec2 { + a + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0 * line as f64) + } + /// The editor's box once the start point, height and angle are known. + fn refresh_editor(&mut self, s: &Session) { + self.editor = match (self.at, self.height, self.rotation, self.asking_justify) { + (Some(a), Some(h), Some(r), false) => match make_text(s, Self::line_at(a, h, r, self.line), "", h, r, self.justify) { + EntityKind::Text(t) => Some(crate::cmd::modify2::line_box(&t)), + _ => None, + }, + _ => None, + }; + } + /// The outline of a line of text `h` high at `a`, turned by `r`, placed by the justification: + /// what the text will cover before it is typed (four characters wide). + fn frame(&self, a: Vec2, h: f64, r: f64) -> EntityKind { + let w = h * 3.2; + let x0 = match self.justify.0 { + HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0, + HAlign::Center | HAlign::Middle => -w / 2.0, + HAlign::Right => -w, + }; + let y0 = match (self.justify.0, self.justify.1) { + (HAlign::Middle, _) | (_, VAlign::Middle) => -h / 2.0, + (_, VAlign::Top) => -h, + (_, VAlign::Bottom) => -h / 3.0, + _ => 0.0, + }; + let corners = [Vec2::new(x0, y0), Vec2::new(x0 + w, y0), Vec2::new(x0 + w, y0 + h), Vec2::new(x0, y0 + h)]; + lwpoly(corners.iter().map(|q| PolyVertex::new(a + q.rotate(r))).collect(), true) + } } impl Interactive for TextM { @@ -148,6 +189,29 @@ impl Interactive for TextM { Ok(Step::Continue) } fn input(&mut self, s: &mut Session, i: Input) -> Result { + let step = self.answer(s, i); + self.refresh_editor(s); + step + } + fn text_editor(&self) -> Option { + let mtext = self.editor.clone()?; + Some(crate::TextEditor { mtext, kind: crate::EditorKind::Line, key: format!("new-text:{}", self.line) }) + } + fn preview(&self, _s: &Session, c: Vec2) -> Vec { + if self.asking_justify { + return Vec::new(); + } + match (self.at, self.height, self.rotation) { + (None, _, _) => vec![self.frame(c, self.size, 0.0)], + (Some(a), None, _) => vec![self.frame(a, a.dist(c).max(1e-9), 0.0)], + (Some(a), Some(h), None) if a.dist(c) > 1e-12 => vec![self.frame(a, h, a.angle_to(c))], + _ => Vec::new(), + } + } +} + +impl TextM { + fn answer(&mut self, s: &mut Session, i: Input) -> Result { if self.asking_justify { let code = match &i { Input::Keyword(k) | Input::Text(k) => k.clone(), @@ -173,8 +237,10 @@ impl Interactive for TextM { (Some(_), Some(_), None, Input::Text(t)) => { self.rotation = Some(s.angle_settings().direction(&t).ok_or_else(|| crate::EngineError::Other("Requires an angle.".into()))?) } + // An empty line (the editor finished with nothing typed) ends the command. + (Some(_), Some(_), Some(_), Input::Text(t)) if t.is_empty() => return Ok(Step::Done), (Some(a), Some(h), Some(r), Input::Text(t)) => { - let at = a + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0 * self.line as f64); + let at = Self::line_at(a, h, r, self.line); let k = make_text(s, at, &t, h, r, self.justify); s.add_entity(k)?; self.line += 1; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index f9ede3b546..0301132b0f 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -372,7 +372,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 21051fffc4..04b36a2a12 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -95,6 +95,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, @@ -167,6 +168,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 d4b5b35cbf..aeaa03be28 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -80,11 +80,19 @@ 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, loaded drawing name)"), CommandSpec::new("textedit", "Edit Text...", run_textedit) .menu(&["Modify", "Object", "Edit Text..."]) .alias(&["ed", "ddedit"]) - .params("{handle, text} (text, mtext, attribute definitions, dimension text override)") + .params("{handle, text} (text, mtext, attribute definitions, dimension text override, multileader text)") .interactive(|_| Ok(Box::new(TextEditM::default()))), + // Double-clicking text, a dimension or a multileader: TEXTEDIT for that one object, in the + // in-place editor. + CommandSpec::new("textedit.object", "Edit Text", run_textedit) + .params("same as textedit") + .interactive(|_| Ok(Box::new(TextEditM::single()))), ] } @@ -154,7 +162,8 @@ 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}; +pub(crate) use textedit::line_box; +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/tests.rs b/crates/engine/src/cmd/modify2/tests.rs index 5f65026a96..85a6c7cc70 100644 --- a/crates/engine/src/cmd/modify2/tests.rs +++ b/crates/engine/src/cmd/modify2/tests.rs @@ -2,7 +2,7 @@ use cadcraft_doc::{EntityKind, Handle, Space}; use cadcraft_geom::{Arc, Polyline, Vec2}; use serde_json::{Value, json}; -use crate::Session; +use crate::{Input, Session}; fn last(s: &Session) -> EntityKind { s.doc().unwrap().model.last().unwrap().kind.clone() @@ -763,6 +763,85 @@ fn offset_polyline_arc_bulge_follows_joined_endpoints() { assert!((arc.radius - 4.0).abs() < 1e-6, "radius {}", arc.radius); } +/// Start `cmd` and pick the object at `at`: what the in-place editor gets. +fn pick_for_editor(s: &mut Session, cmd: &str, at: Vec2) -> crate::TextEditor { + s.start(cmd).unwrap(); + s.input(Input::Point(at)).unwrap(); + s.text_editor().unwrap_or_else(|| panic!("no editor: {}", s.prompt_text())) +} + +#[test] +fn double_click_editing_describes_each_kind_and_applies_the_text() { + use crate::EditorKind; + let mut s = Session::new(); + // Multiline text: the editor starts from its contents, with formatting codes. + let m = h(&s.execute("mtext", &json!({"at": [0, 0], "text": "{\\fArial|b1;Bold}\\Pline"})).unwrap()); + let e = pick_for_editor(&mut s, "textedit.object", Vec2::new(0.05, -0.05)); + assert_eq!(e.kind, EditorKind::MText); + assert_eq!(e.key, m); + assert!(e.mtext.contents.contains("Bold"), "{}", e.mtext.contents); + s.input(Input::Text("new\\Ptext".into())).unwrap(); + assert!(s.running.is_none(), "one object only"); + assert!(matches!(kind(&s, &m), EntityKind::MText(x) if x.contents == "new\\Ptext")); + + // One line of text: plain, no formatting. + let t = h(&s.execute("text", &json!({"at": [20, 0], "text": "single"})).unwrap()); + let e = pick_for_editor(&mut s, "textedit.object", Vec2::new(20.05, 0.05)); + assert_eq!((e.kind, e.mtext.contents.as_str()), (EditorKind::Line, "single")); + s.input(Input::Text("changed".into())).unwrap(); + assert!(matches!(kind(&s, &t), EntityKind::Text(x) if x.value == "changed")); + + // A dimension: `<>` is the measured value, which the editor is told. + let d = h(&s.execute("dimlinear", &json!({"p1": [0, 10], "p2": [8, 10], "at": [4, 12]})).unwrap()); + let EntityKind::Dimension(dm) = kind(&s, &d) else { panic!() }; + let at = cadcraft_render::dimension_in(s.doc().unwrap(), &dm).text_pos; + let e = pick_for_editor(&mut s, "textedit.object", at); + let EditorKind::Dimension { measured } = &e.kind else { panic!("{:?}", e.kind) }; + assert!(measured.contains('8'), "{measured}"); + assert_eq!(e.mtext.contents, "<>"); + s.input(Input::Text("L=<> mm".into())).unwrap(); + assert!(matches!(kind(&s, &d), EntityKind::Dimension(x) if x.text == "L=<> mm")); + + // A multileader's text. + let ml = h(&s.execute("mleader", &json!({"points": [[40, 0], [44, 4]], "text": "note"})).unwrap()); + let EntityKind::MLeader(mm) = kind(&s, &ml) else { panic!() }; + let at = mm.text.as_ref().unwrap().insert.xy(); + s.start("textedit.object").unwrap(); + s.input(Input::Point(at + Vec2::new(0.05, -0.05))).unwrap(); + let e = s.text_editor().expect("the multileader's text"); + assert_eq!(e.kind, EditorKind::MText); + s.input(Input::Text("new note".into())).unwrap(); + assert!(matches!(kind(&s, &ml), EntityKind::MLeader(x) if x.text.as_ref().is_some_and(|t| t.contents == "new note"))); +} + +#[test] +fn table_cells_are_edited_in_place_and_tab_moves_on() { + use crate::EditorKind; + let mut s = Session::new(); + let t = h(&s.execute("table", &json!({"at": [0, 0], "rows": 2, "cols": 2, "colWidth": 3, "rowHeight": 1})).unwrap()); + let EntityKind::Table(tb) = kind(&s, &t) else { panic!() }; + let (corner, w, hgt) = tb.cell_rect(tb.row_heights.len() - 1, 0).unwrap(); + let e = pick_for_editor(&mut s, "tabledit.cell", corner + Vec2::new(w / 2.0, -hgt / 2.0)); + assert!(matches!(&e.kind, EditorKind::TableCell { name } if name.starts_with('A')), "{:?}", e.kind); + assert!(e.mtext.width > 0.0 && e.mtext.width < w); + let first = e.key.clone(); + s.input(Input::Text("left".into())).unwrap(); + s.input(Input::Keyword("Next".into())).unwrap(); + let e2 = s.text_editor().unwrap(); + assert_ne!(e2.key, first); + s.input(Input::Text("right".into())).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none()); + let EntityKind::Table(tb) = kind(&s, &t) else { panic!() }; + let last = tb.cells.last().unwrap(); + assert_eq!((last[0].text.as_str(), last[1].text.as_str()), ("left", "right")); + // Up from the first row ends, as Tab past the last cell does. + s.start("tabledit.cell").unwrap(); + s.input(Input::Point(tb.cell_rect(0, 0).map(|(c, w, h)| c + Vec2::new(w / 2.0, -h / 2.0)).unwrap())).unwrap(); + s.input(Input::Keyword("Up".into())).unwrap(); + assert!(s.running.is_none()); +} + #[test] fn offset_elliptical_arc_follows_picked_side() { let max_x = |side: Value| { diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index 081737a7b7..7610aee681 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -11,18 +11,142 @@ fn text_of(k: &EntityKind) -> Option { EntityKind::Text(t) => Some(t.value.clone()), EntityKind::AttDef(a) => Some(a.text.value.clone()), EntityKind::MText(t) => Some(t.contents.replace("\\P", "\n")), - // A multileader's text (one with a block instead has none, #1081). - EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.contents.replace("\\P", "\n")), EntityKind::Dimension(d) => Some(if d.text.is_empty() { "<>".into() } else { d.text.clone() }), + EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.contents.replace("\\P", "\n")), + _ => None, + } +} + +/// A box for the in-place editor showing one line of text where `t` sits. +pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText { + use cadcraft_doc::{HAlign, VAlign}; + let col = match t.halign { + HAlign::Left => 0u8, + HAlign::Right => 2, + _ => 1, + }; + let row = match t.valign { + VAlign::Top => 0u8, + VAlign::Middle => 1, + _ if t.halign == HAlign::Middle => 1, + _ => 2, + }; + let left_baseline = t.halign == HAlign::Left && t.valign == VAlign::Baseline; + let at = if left_baseline { t.insert } else { t.align_pt.unwrap_or(t.insert) }; + cadcraft_doc::MText { + formula: None, + insert: at, + height: t.height, + width: 0.0, + attach: row * 3 + col + 1, + rotation: t.rotation, + style: t.style.clone(), + contents: t.value.clone(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + } +} + +/// What the in-place editor edits for object `h`: an MTEXT or multileader text as multiline +/// text, a TEXT or attribute definition as one line, a dimension's text with `<>` for its value. +pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { + use crate::{EditorKind, TextEditor}; + let d = s.doc().ok()?; + let key = h.hex(); + match &d.entity(h)?.kind { + // A text with a formula is edited as its formula. + EntityKind::MText(t) => { + let mut m = t.clone(); + // The formula as multiline text: its `\`, `{` and `}` are letters, not codes. + if let Some(f) = t.formula.as_ref().filter(|f| crate::textformula::is_formula(f)) { + m.contents = cadcraft_doc::mtext_literal(f); + } + Some(TextEditor { mtext: m, kind: EditorKind::MText, key }) + } + EntityKind::MLeader(m) => m.text.clone().map(|mut mtext| { + if let Some(f) = mtext.formula.as_ref().filter(|f| crate::textformula::is_formula(f)) { + mtext.contents = cadcraft_doc::mtext_literal(f); + } + TextEditor { mtext, kind: EditorKind::MText, key } + }), + EntityKind::Text(t) => { + let mut b = line_box(t); + if let Some(f) = t.formula.as_ref().filter(|f| crate::textformula::is_formula(f)) { + b.contents.clone_from(f); + } + Some(TextEditor { mtext: b, kind: EditorKind::Line, key }) + } + EntityKind::AttDef(a) => { + let mut b = line_box(&a.text); + if let Some(f) = a.text.formula.as_ref().filter(|f| crate::textformula::is_formula(f)) { + b.contents.clone_from(f); + } + Some(TextEditor { mtext: b, kind: EditorKind::Line, key }) + } + EntityKind::Dimension(dm) => { + let g = cadcraft_render::dimension_in(d, dm); + let measured = cadcraft_render::dimension_in( + d, + &cadcraft_doc::Dimension { + text: String::new(), + block: None, + marks: cadcraft_doc::DimMarks { formula: None, ..dm.marks.clone() }, + ..dm.clone() + }, + ) + .value; + let mtext = cadcraft_doc::MText { + formula: None, + insert: g.text_pos.to3(0.0), + height: if g.text_height > 0.0 && g.text_height.is_finite() { g.text_height } else { 0.18 }, + width: 0.0, + attach: 5, + rotation: g.text_angle, + style: d.dim_style(&dm.style).map(|st| st.text_style.clone()).unwrap_or_else(|| dm.style.clone()), + // The editor holds multiline text: a formula's `\`, `{` and `}` go in as letters. + contents: match dm.marks.formula.clone().filter(|f| crate::textformula::is_formula(f)) { + Some(f) => cadcraft_doc::mtext_literal(&f), + None if dm.text.is_empty() => "<>".into(), + None => dm.text.clone(), + }, + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key }) + } _ => None, } } -pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { +/// Set the text of object `h`. `from_editor`: `text` comes from the in-place editor, which +/// writes a dimension's text as multiline text (a formula's braces and backslashes escaped); +/// otherwise a dimension's text is taken as typed. +pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str, from_editor: bool) -> Result<()> { if curves::is_locked(s, h) { return Err(other("The object is on a locked layer.")); } let mut k = curves::entity(s, h)?.kind; + // The text as the editor showed it (a formula, else the value): unchanged, it keeps its + // formula or AutoCAD field. + let f = |x: &Option| x.clone().filter(|f| crate::textformula::is_formula(f)); + let shown = match &k { + EntityKind::Text(t) => f(&t.formula).unwrap_or_else(|| t.value.clone()), + EntityKind::AttDef(a) => f(&a.text.formula).unwrap_or_else(|| a.text.value.clone()), + EntityKind::MText(t) => f(&t.formula).map(|f| cadcraft_doc::mtext_literal(&f)).unwrap_or_else(|| t.contents.clone()), + EntityKind::MLeader(m) => { + m.text.as_ref().map(|t| f(&t.formula).map(|f| cadcraft_doc::mtext_literal(&f)).unwrap_or_else(|| t.contents.clone())).unwrap_or_default() + } + EntityKind::Dimension(d) if from_editor => f(&d.marks.formula).map(|f| cadcraft_doc::mtext_literal(&f)).unwrap_or_else(|| d.text.clone()), + EntityKind::Dimension(d) => f(&d.marks.formula).unwrap_or_else(|| d.text.clone()), + _ => String::new(), + }; + // Multiline text comes back from the editor rewritten (its codes in the editor's own form): + // compared in that form, an edit that changed nothing keeps the formula. + let canonical = |x: &str| crate::mtext_edit::Formatted::from_contents(x).to_contents(); + let multiline = matches!(k, EntityKind::MText(_) | EntityKind::MLeader(_)) || (from_editor && matches!(k, EntityKind::Dimension(_))); + let unchanged = shown == text || shown == text.replace('\n', "\\P") || (multiline && canonical(&shown) == canonical(&text.replace('\n', "\\P"))); match &mut k { EntityKind::Text(t) => t.value = text.to_string(), EntityKind::AttDef(a) => a.text.value = text.to_string(), @@ -33,35 +157,67 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { } } EntityKind::Dimension(d) => { + // A formula from the editor is read without its codes (its escaped braces and + // backslashes are letters again); other text stays multiline text, as an override is. + let plain = cadcraft_fonts::plain_mtext(text); + let text = if from_editor && crate::textformula::is_formula(&plain) { plain.trim() } else { text }; d.text = if text == "<>" { String::new() } else { text.to_string() }; d.block = None; } + EntityKind::MLeader(m) => match &mut m.text { + Some(t) => t.contents = text.replace('\n', "\\P"), + None => return Err(other("This multileader has no text.")), + }, _ => return Err(other("Select a text, mtext, multileader, 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 { + // 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")); + 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"))?; if text.len() > 1_000_000 { return Err(bad("textedit", "text is too long")); } - set_text(s, h, text)?; + set_text(s, h, text, false)?; Ok(json!({ "handle": h.hex() })) } #[derive(Default)] pub(super) struct TextEditM { h: Option<(Handle, String)>, + /// What the in-place editor shows for the picked object. + editor: Option, /// Edits made in this run, newest last: each object as it was before (the Undo option). edits: Vec<(Handle, EntityKind)>, /// Single mode: end after one edit (the Mode option; Multiple by default). single: bool, /// Asking for the edit mode. mode: bool, - /// The MTEXT being edited, for the in-place editor (#842). - mtext: Option, +} + +impl TextEditM { + /// TEXTEDIT for one object (a double-click): done after it. + pub(super) fn single() -> Self { + Self { single: true, ..Self::default() } + } } impl Interactive for TextEditM { @@ -70,7 +226,7 @@ impl Interactive for TextEditM { } /// An MTEXT asking for its new text opens in the in-place editor with its contents. fn editing_mtext(&self) -> Option { - self.h.as_ref().and(self.mtext.clone()) + self.h.as_ref().and(self.editor.as_ref().filter(|e| matches!(e.kind, crate::EditorKind::MText)).map(|e| e.mtext.clone())) } fn prompt(&self, _s: &Session) -> Prompt { if self.mode { @@ -100,18 +256,13 @@ impl Interactive for TextEditM { if curves::is_locked(s, h) { return Err(other("The object is on a locked layer.")); } - let kind = curves::entity(s, h)?.kind; - let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?; - self.mtext = match kind { - EntityKind::MText(m) => Some(m), - // A multileader's text opens in the same editor (#1081). - EntityKind::MLeader(m) => m.text, - _ => None, - }; + let old = text_of(&curves::entity(s, h)?.kind) + .ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?; + self.editor = editor_for(s, h); // The editor would drop part of a text this long, and saving would lose it: the // command line asks for it instead. - if self.mtext.as_ref().is_some_and(|m| !crate::mtext_edit::Formatted::fits(&m.contents)) { - self.mtext = None; + if self.editor.as_ref().is_some_and(|e| !crate::mtext_edit::Formatted::fits(&e.mtext.contents)) { + self.editor = None; s.echo("This text is too long for the editor; enter the new text at the command line."); } self.h = Some((h, old)); @@ -120,15 +271,15 @@ impl Interactive for TextEditM { (Some((h, _)), Input::Text(t) | Input::Keyword(t)) => { let h = *h; let before = curves::entity(s, h)?.kind; - set_text(s, h, &t)?; + set_text(s, h, &t, true)?; self.edits.push((h, before)); self.h = None; - self.mtext = None; + self.editor = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (Some(_), Input::Enter) => { self.h = None; - self.mtext = None; + self.editor = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (None, Input::Enter) => Ok(Step::Done), @@ -146,4 +297,7 @@ impl Interactive for TextEditM { _ => Ok(Step::Continue), } } + fn text_editor(&self) -> Option { + if self.mode || self.h.is_none() { None } else { self.editor.clone() } + } } 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/set.rs b/crates/engine/src/cmd/props/set.rs index c67a4a8346..ee5780e108 100644 --- a/crates/engine/src/cmd/props/set.rs +++ b/crates/engine/src/cmd/props/set.rs @@ -305,6 +305,9 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { .transpose()?; let lineweight = p.get("lineweight").map(|v| crate::cmd::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); // Every check reads the drawing first: a refused call leaves no empty undo step. let d = s.doc()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). @@ -335,6 +338,16 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { return Ok(left_out.result(0, &[])); } let prep = Prepared::new(d, p, &hs); + // A dimension's measurement, which `<>` in a new formula stands for. + let dim_envs: HashMap = hs + .iter() + .filter_map(|h| match d.entity(*h).map(|e| &e.kind) { + Some(EntityKind::Dimension(dm)) => { + Some((*h, crate::textformula::Env { measured: crate::textformula::measured(d, dm), ..formula_env.clone() })) + } + _ => None, + }) + .collect(); let anno_scale = d.current_anno_scale(); let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale }; // A failed call changes nothing (a command's error doesn't undo what it did), so the drawing @@ -373,6 +386,14 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result { EntityKind::Hatch(ha) => hatch(ha, &c, &mut used), _ => {} } + let new_text = match &e.kind { + EntityKind::Text(_) | EntityKind::MText(_) => str_param(p, "text").is_some(), + EntityKind::Dimension(_) => str_param(p, "textOverride").is_some(), + _ => false, + }; + if new_text { + crate::textformula::apply(&mut e.kind, dim_envs.get(&h).unwrap_or(&formula_env), true); + } })?; } let ignored: Vec<&str> = p diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 8f7e8f1dd3..8a8bc0e405 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -229,10 +229,12 @@ fn cell_at(p: &Value, t: &Table) -> std::result::Result<(usize, usize), String> fn run_set(s: &mut Session, p: &Value) -> Result { let text = str_param(p, "text").unwrap_or("").to_string(); - // A formula: the `formula` parameter, or text starting with "=". + // A formula: the `formula` parameter, or text starting with "=" once its formatting codes + // are left out (the in-place editor sends `{\fArial|b1;=1+1}` for a formula typed in bold). + let plain = cadcraft_fonts::plain_mtext(&text); let formula = match str_param(p, "formula") { Some(f) => Some(f.trim().to_string()), - None => text.trim().starts_with('=').then(|| text.trim().to_string()), + None => plain.trim().starts_with('=').then(|| plain.trim().to_string()), }; if let Some(f) = &formula { let f = if f.starts_with('=') { f.clone() } else { format!("={f}") }; diff --git a/crates/engine/src/cmd/table/cells.rs b/crates/engine/src/cmd/table/cells.rs index f7c6950366..f0b04c176f 100644 --- a/crates/engine/src/cmd/table/cells.rs +++ b/crates/engine/src/cmd/table/cells.rs @@ -29,6 +29,10 @@ pub fn specs() -> Vec { CommandSpec::new("tabledit", "Edit Table Cell", run_tabledit) .params("{handle?, at: [x,y] | row+col, text (=… for a formula)}") .interactive(|_| Ok(Box::new(TableEditM::default()))), + // Double-clicking a table cell: the in-place editor, which moves between cells. + CommandSpec::new("tabledit.cell", "Edit Table Cells", run_tabledit) + .params("same as tabledit") + .interactive(|_| Ok(Box::new(TableEditM { stay: true, ..TableEditM::default() }))), CommandSpec::new("tableexport", "Export Table", run_export) .params("{handle, path? (.csv), separator?: \",\" | \"\\t\"} → {csv, rows, cols, path?}") .interactive(|_| Ok(Box::new(ExportM::default()))), @@ -426,10 +430,102 @@ fn run_tabledit(s: &mut Session, p: &Value) -> Result { super::run_set(s, &q) } -/// TABLEDIT at the command line: pick a cell, type its text (or `=formula`). +/// TABLEDIT at the command line: pick a cell, type its text (or `=formula`). In the in-place +/// editor (`stay`), the text keeps the cell open: `Next`, `Previous`, `Up` and `Down` move to +/// another cell and Enter ends. #[derive(Default)] struct TableEditM { cell: Option<(Handle, usize, usize)>, + stay: bool, + /// The in-place editor's box for the current cell (`stay` only). + editor: Option, +} + +impl TableEditM { + fn open(&mut self, s: &Session, cell: (Handle, usize, usize)) { + self.cell = Some(cell); + self.editor = if self.stay { cell_editor(s, cell.0, cell.1, cell.2) } else { None }; + } +} + +/// The cell's text to edit: its formula, or its text. +fn cell_source(t: &Table, r: usize, c: usize) -> String { + t.cells.get(r).and_then(|row| row.get(c)).map(|c| c.formula.clone().unwrap_or_else(|| c.text.clone())).unwrap_or_default() +} + +/// The cell `dir` of (r, c) that is not covered by a merge: Next and Previous run along the rows +/// and wrap; Up and Down stay in the column. `None` at the table's edge. +fn neighbour(t: &Table, r: usize, c: usize, dir: &str) -> Option<(usize, usize)> { + let rows = t.row_heights.len().min(t.cells.len()).min(MAX_ROWS); + let cols = t.col_widths.len().min(MAX_COLS); + if rows == 0 || cols == 0 { + return None; + } + let covered = cadcraft_render::table_covered(t); + let free = |r: usize, c: usize| !covered.get(r).and_then(|v| v.get(c)).copied().unwrap_or(false); + let (mut r, mut c) = (r.min(rows - 1), c.min(cols - 1)); + for _ in 0..rows.saturating_mul(cols) { + match dir { + "Next" => { + c += 1; + if c >= cols { + c = 0; + r += 1; + } + if r >= rows { + return None; + } + } + "Previous" => { + if c == 0 { + if r == 0 { + return None; + } + r -= 1; + c = cols - 1; + } else { + c -= 1; + } + } + "Up" => r = r.checked_sub(1)?, + "Down" => { + r += 1; + if r >= rows { + return None; + } + } + _ => return None, + } + if free(r, c) { + return Some((r, c)); + } + } + None +} + +/// The in-place editor's box for cell (r, c) of table `h`. +fn cell_editor(s: &Session, h: Handle, r: usize, c: usize) -> Option { + let d = s.doc().ok()?; + let EntityKind::Table(t) = &d.entity(h)?.kind else { return None }; + let (corner, w, _) = t.cell_rect(r, c)?; + let height = t.cells.get(r).and_then(|row| row.get(c)).and_then(|c| c.text_height).unwrap_or(t.text_height); + let height = if height.is_finite() && height > 0.0 { height } else { 0.18 }; + let margin = d.table_styles.iter().find(|st| st.name.eq_ignore_ascii_case(&t.style)).map_or(0.06, |st| st.margin); + let margin = if margin.is_finite() && margin >= 0.0 { margin.min(w * 0.25) } else { 0.0 }; + let mtext = cadcraft_doc::MText { + formula: None, + insert: (corner + Vec2::new(margin, -margin)).to3(t.insert.z), + height, + width: (w - 2.0 * margin).max(height), + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: cell_source(t, r, c), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + Some(crate::TextEditor { mtext, kind: crate::EditorKind::TableCell { name: cell_name(r, c) }, key: format!("{}:{r}:{c}", h.hex()) }) } impl Interactive for TableEditM { @@ -457,13 +553,38 @@ impl Interactive for TableEditM { (_, Input::Cancel) => Ok(Step::Cancel), (None, Input::Point(p)) => { match cell_under(s, p) { - Some(c) => self.cell = Some(c), + Some(c) => self.open(s, c), None => s.echo("No table cell there."), } Ok(Step::Continue) } (None, Input::Enter) => Ok(Step::Cancel), (Some(_), Input::Enter) => Ok(Step::Done), + (Some((h, r, c)), Input::Keyword(k)) if self.stay && matches!(k.as_str(), "Next" | "Previous" | "Up" | "Down") => { + let (h, r, c) = (*h, *r, *c); + let next = s + .doc() + .ok() + .and_then(|d| d.entity(h)) + .and_then(|e| if let EntityKind::Table(t) = &e.kind { neighbour(t, r, c, &k) } else { None }); + match next { + Some((r, c)) => { + self.open(s, (h, r, c)); + Ok(Step::Continue) + } + // Past the table's edge: done, as the last cell's Tab is in AutoCAD. + None => Ok(Step::Done), + } + } + (Some((h, r, c)), Input::Text(t)) if self.stay => { + let q = json!({ "handle": h.hex(), "row": r, "col": c, "text": t }); + let cell = (*h, *r, *c); + if let Err(e) = super::run_set(s, &q) { + s.echo(e.to_string()); + } + self.open(s, cell); + Ok(Step::Continue) + } (Some((h, r, c)), Input::Text(t) | Input::Keyword(t)) => { let q = json!({ "handle": h.hex(), "row": r, "col": c, "text": t }); match super::run_set(s, &q) { @@ -477,6 +598,9 @@ impl Interactive for TableEditM { _ => Ok(Step::Continue), } } + fn text_editor(&self) -> Option { + self.cell.and(self.editor.clone()) + } } // ---------------------------------------------------------------- TABLEEXPORT 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 fb024f08ee..097c15771e 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,8 @@ fn single(t: &Text) -> MText { _ => 2, }; MText { + // 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/file_access/commands.rs b/crates/engine/src/file_access/commands.rs index b9134243e0..6d146a561c 100644 --- a/crates/engine/src/file_access/commands.rs +++ b/crates/engine/src/file_access/commands.rs @@ -311,6 +311,9 @@ pub const NO_FILES: &[&str] = &[ "flatten", "arraypath", "textedit", + "textedit.object", + "tabledit.cell", + "updatefield", "group", "ungroup", "groupedit", 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/guard.rs b/crates/engine/src/guard.rs index e779609587..f243bc99be 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -119,6 +119,15 @@ impl Interactive for Guarded { None }) } + fn text_editor(&self) -> Option { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.text_editor())).unwrap_or_else(|_| { + self.broken.set(Some("panic in prompt")); + None + }) + } } #[cfg(test)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5fd19de470..8c807c232a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,6 +20,7 @@ pub mod cmd; pub mod doc_path; pub mod file_access; mod finite; +pub mod formula; pub mod grip_dims; pub mod grips; mod guard; @@ -37,6 +38,7 @@ pub mod settings_dir; pub mod snap; pub mod spatial; pub mod sysvars; +pub mod textformula; pub mod ucs; pub mod undoctl; pub mod units; @@ -54,7 +56,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, DisplayOnly, Drag, Input, Interactive, Picker, Prompt, Step}; +pub use prompt::{Accept, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor}; mod doc_state; mod error; @@ -310,6 +312,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/prompt.rs b/crates/engine/src/prompt.rs index ed9a77147e..6b0b79423e 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -328,6 +328,11 @@ pub trait Interactive: Send { fn display_only(&self, _s: &Session) -> Option { None } + /// The text the in-place editor edits: where, how, its current contents and what kind of + /// object holds it. By default the new multiline text of [`Interactive::editing_mtext`]. + fn text_editor(&self) -> Option { + self.editing_mtext().map(|mtext| TextEditor { mtext, kind: EditorKind::NewMText, key: String::new() }) + } } /// See [`Interactive::display_only`]: the only things drawn in the current view while a command @@ -341,6 +346,34 @@ pub struct DisplayOnly { pub extra: Vec, } +/// What the in-place text editor edits ([`Interactive::text_editor`]). The editor answers the +/// command's text prompt with the new contents (`Input::Text`), then `Input::Enter`; a table cell +/// may answer a move keyword instead of Enter (`Next`, `Previous`, `Up`, `Down`). +#[derive(Clone, Debug, PartialEq)] +pub struct TextEditor { + /// Where the box sits (insertion point, attachment, rotation), its width (0: grows with the + /// text), text height and style; `contents` is the text to start from, in MTEXT codes. + pub mtext: cadcraft_doc::MText, + pub kind: EditorKind, + /// Which object (and cell) is being edited: a new key means a new text to load. + pub key: String, +} + +/// The kind of text the in-place editor edits. +#[derive(Clone, Debug, PartialEq)] +pub enum EditorKind { + /// Multiline text being created (MTEXT). + NewMText, + /// Existing multiline text: an MTEXT, a multileader's text. + MText, + /// One line of plain text (TEXT, attribute definition): no formatting, Enter finishes. + Line, + /// A dimension's text: `<>` stands for the measured value, shown as `measured`. + Dimension { measured: String }, + /// A table cell (`name` such as `B3`); Tab, Shift+Tab and the arrows move between cells. + TableCell { name: String }, +} + /// See [`Interactive::drag`]. #[derive(Clone, Debug)] pub struct Drag { diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 4e615a4f2e..427d961603 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -38,6 +38,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, @@ -214,7 +215,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 68a5e532b4..294ed1087b 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -89,6 +89,24 @@ 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. + // 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 { + 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 && lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() { diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index e6af826017..ad15386a4a 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -4,6 +4,7 @@ use super::{ Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value, Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars, }; +use crate::TextEditor; impl Session { // ---------------- interactive commands ---------------- @@ -536,6 +537,11 @@ impl Session { self.running.as_ref().and_then(|r| r.machine.editing_mtext()) } + /// The text the running command edits in place ([`Interactive::text_editor`]). + pub fn text_editor(&self) -> Option { + self.running.as_ref().and_then(|r| r.machine.text_editor()) + } + pub fn current_prompt(&self) -> Option { if let Some(p) = self.lisp_prompt() { return Some(p); diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 10888f5cf1..9acade4d0e 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -342,6 +342,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..fad3629ae3 --- /dev/null +++ b/crates/engine/src/textformula.rs @@ -0,0 +1,175 @@ +//! 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): 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(), + block: None, + marks: cadcraft_doc::DimMarks { formula: None, ..dm.marks.clone() }, + ..dm.clone() + }; + 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 +/// 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`). +/// 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), + 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, + }; + 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). + let plain = if mtext { cadcraft_fonts::plain_mtext(value) } else { value.clone() }; + 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) + { + // 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 { + 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(), + EntityKind::Insert(i) => i.attribs.iter().any(|a| a.text.formula.is_some()), + _ => false, + } +} + +/// 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 { + 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| { + 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; + } + }; + 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 f3d046b7c2..2191c11135 100644 --- a/crates/engine/tests/audit.rs +++ b/crates/engine/tests/audit.rs @@ -58,6 +58,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/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/engine/tests/it/attedit_prompts.rs b/crates/engine/tests/it/attedit_prompts.rs index 7a7d47304f..2e323d5777 100644 --- a/crates/engine/tests/it/attedit_prompts.rs +++ b/crates/engine/tests/it/attedit_prompts.rs @@ -227,6 +227,7 @@ fn dash_attedit_edits_a_multiline_attributes_text() { rotation: 0.0, style: "Standard".into(), contents: "abc".into(), + formula: None, line_spacing: 1.0, line_spacing_exact: false, columns: None, 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 0c08b4bc06..3fc33da77e 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -60,6 +60,7 @@ mod extend_polyline_end_choice; mod fillet_chamfer; mod fix_holds_grips; mod followups_626; +mod formula_input; mod greek_keyboard; mod grip_dim_input; mod grip_options; @@ -172,6 +173,8 @@ mod table_formulas; mod table_styles; mod temp_tracking; mod text_commands; +mod text_editor_on_create; +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/table_formulas.rs b/crates/engine/tests/it/table_formulas.rs index 91b7ca6b6c..e4797ea8d2 100644 --- a/crates/engine/tests/it/table_formulas.rs +++ b/crates/engine/tests/it/table_formulas.rs @@ -187,3 +187,22 @@ fn hostile_formulas_never_panic() { } assert_eq!(text(&s, &h2, n - 1, 0), n.to_string()); } + +/// FredApps on #2320: the in-place editor sends a cell's text with its formatting codes; a +/// formula typed with formatting (bold, another font) is still a formula, also when Tab moves on +/// to the next cell. +#[test] +fn a_formatted_formula_stays_a_formula() { + let (mut s, h) = session(); + set(&mut s, &h, 3, 0, "{\\fArial|b1;=Sum(A1:A3)}"); + assert_eq!(table(&s, &h).cells[3][0].formula.as_deref(), Some("=Sum(A1:A3)")); + assert_eq!(text(&s, &h, 3, 0), "6"); + + // The editor: the text, then Tab (Next) to the next cell. + s.cmdline("tabledit").unwrap(); + s.cmdline("4,-3.5").unwrap(); + s.input(cadcraft_engine::Input::Text("{\\fArial|b1;=A1*10}".into())).unwrap(); + s.input(cadcraft_engine::Input::Keyword("Next".into())).unwrap(); + assert_eq!(table(&s, &h).cells[3][1].formula.as_deref(), Some("=A1*10")); + assert_eq!(text(&s, &h, 3, 1), "10"); +} diff --git a/crates/engine/tests/it/text_editor_on_create.rs b/crates/engine/tests/it/text_editor_on_create.rs new file mode 100644 index 0000000000..accc4d3414 --- /dev/null +++ b/crates/engine/tests/it/text_editor_on_create.rs @@ -0,0 +1,59 @@ +//! TEXT and MLEADER hand their text to the in-place editor once it is asked for, and show the +//! text's frame / the leader segment while points are picked. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{EditorKind, Input, Session}; + +fn texts(s: &Session) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Text(t) => Some(t.value.clone()), + _ => None, + }) + .collect() +} + +#[test] +fn text_opens_a_line_editor_for_each_line_and_an_empty_line_ends_it() { + let mut s = Session::new(); + s.start("text").unwrap(); + // Before the start point: the frame of a line of text follows the cursor. + assert!(!s.preview(Vec2::new(1.0, 1.0)).is_empty()); + assert!(s.text_editor().is_none()); + s.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap(); + assert!(!s.preview(Vec2::new(0.0, 2.0)).is_empty(), "the frame grows with the height"); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + let ed = s.text_editor().expect("the editor opens at the text prompt"); + assert_eq!(ed.kind, EditorKind::Line); + let first_key = ed.key.clone(); + s.input(Input::Text("first".into())).unwrap(); + let ed = s.text_editor().expect("the next line gets an editor"); + assert_ne!(ed.key, first_key); + assert!(ed.mtext.insert.y < 0.0, "the next line is below the first"); + s.input(Input::Text("second".into())).unwrap(); + s.input(Input::Text(String::new())).unwrap(); + assert!(s.running.is_none()); + assert_eq!(texts(&s), ["first", "second"]); +} + +#[test] +fn mleader_opens_the_editor_after_its_leader_and_previews_the_segment() { + let mut s = Session::new(); + s.start("mleader").unwrap(); + s.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap(); + assert!(!s.preview(Vec2::new(5.0, 5.0)).is_empty(), "the segment to the cursor shows"); + assert!(s.editing_mtext().is_none()); + s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap(); + let m = s.editing_mtext().expect("the editor opens at the landing"); + assert!(m.insert.x > 5.0 && m.contents.is_empty()); + s.input(Input::Text("NOTE".into())).unwrap(); + assert!(s.running.is_none()); + let found = + s.doc().unwrap().model.iter().any(|e| matches!(&e.kind, EntityKind::MLeader(m) if m.text.as_ref().is_some_and(|t| t.contents == "NOTE"))); + assert!(found); +} diff --git a/crates/engine/tests/it/text_formulas.rs b/crates/engine/tests/it/text_formulas.rs new file mode 100644 index 0000000000..cd0f58c950 --- /dev/null +++ b/crates/engine/tests/it/text_formulas.rs @@ -0,0 +1,356 @@ +//! 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"); +} + +/// 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()))]); +} + +/// The in-place editor shows what was typed: an attribute definition's formula, a multiline +/// formula with its braces as letters, and a dimension's own measurement for `<>` (#2320 review). +#[test] +fn the_editor_shows_formulas_as_typed() { + use cadcraft_engine::geom::Vec2; + use cadcraft_engine::{EditorKind, Input}; + let open = |s: &mut Session, at: Vec2| { + s.start("textedit").unwrap(); + // Single or Multiple may be asked first; a point picks the object. + s.input(Input::Point(at)).unwrap(); + s.text_editor().expect("the editor opens") + }; + let mut s = Session::new(); + s.execute("attdef", &json!({ "tag": "T", "default": "=1+1", "at": [0, 0], "height": 1.0 })).unwrap(); + let ed = open(&mut s, Vec2::new(0.3, 0.4)); + assert_eq!((ed.kind, ed.mtext.contents.as_str()), (EditorKind::Line, "=1+1")); + // Accepted unchanged, the formula stays. + s.input(Input::Text("=1+1".into())).unwrap(); + let a = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.text.clone()) } else { None }).unwrap(); + assert_eq!(a.formula.as_deref(), Some("=1+1")); + s.cancel(); + + let mut s = Session::new(); + s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "=UPPER(\"\\{a\\}\")" })).unwrap(); + let ed = open(&mut s, Vec2::new(0.5, 9.6)); + assert_eq!(ed.mtext.contents, "=UPPER(\"\\{a\\}\")", "braces written as letters"); + s.input(Input::Text(ed.mtext.contents.clone())).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!((mt.formula.as_deref(), cadcraft_fonts::plain_mtext(&mt.contents).as_str()), (Some("=UPPER(\"{a}\")"), "{A}")); + s.cancel(); + + 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 at = { + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + cadcraft_render::dimension_in(d, dm).text_pos + }; + let ed = open(&mut s, at); + match ed.kind { + EditorKind::Dimension { measured } => assert_eq!(measured, "1250.0000"), + k => panic!("{k:?}"), + } +} + +/// Multiline text sent back by the editor in its own form of the codes, unchanged otherwise, +/// keeps its formula (#2326 review). +#[test] +fn an_unchanged_multiline_formula_in_the_editors_form_is_kept() { + let mut s = Session::new(); + let r = s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "=UPPER(\"\\{a\\}\")&\"\\\\x\"" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let before = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); + assert!(before.formula.is_some()); + let shown = cadcraft_doc::mtext_literal(before.formula.as_deref().unwrap()); + let sent = cadcraft_engine::mtext_edit::Formatted::from_contents(&shown).to_contents(); + s.execute("textedit", &json!({ "handle": m, "text": sent })).unwrap(); + let after = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MText(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!(after.formula, before.formula); +} + +/// A dimension formula with braces and a backslash goes through the in-place editor as +/// multiline text and comes back unchanged when accepted as it is (#2320 review: the braces +/// were read as formatting, so `=UPPER("{a}")` became `=UPPER("a")`). A changed formula from the +/// editor is read without its codes too. +#[test] +fn a_dimension_formula_keeps_its_braces_through_the_editor() { + use cadcraft_engine::Input; + 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(); + let formula = r#"=UPPER("{a}")&"\x""#; + s.execute("textedit", &json!({ "handle": h, "text": formula })).unwrap(); + let dim = |s: &Session| { + let d = s.doc().unwrap(); + match &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind { + EntityKind::Dimension(dm) => dm.clone(), + _ => panic!(), + } + }; + assert_eq!(dim(&s).marks.formula.as_deref(), Some(formula), "the JSON form takes the formula as typed"); + let at = cadcraft_render::dimension_in(s.doc().unwrap(), &dim(&s)).text_pos; + let open = |s: &mut Session| { + s.start("textedit").unwrap(); + s.input(Input::Point(at)).unwrap(); + s.text_editor().expect("the editor opens") + }; + let ed = open(&mut s); + assert_eq!(ed.mtext.contents, cadcraft_doc::mtext_literal(formula), "braces and backslash as letters"); + // What the editor sends back for unchanged contents. + let sent = cadcraft_engine::mtext_edit::Formatted::from_contents(&ed.mtext.contents).to_contents(); + s.input(Input::Text(sent)).unwrap(); + assert_eq!(dim(&s).marks.formula.as_deref(), Some(formula), "unchanged, the formula stays"); + s.cancel(); + // An edited formula from the editor: its escaped braces are letters again. + let ed = open(&mut s); + let edited = cadcraft_doc::mtext_literal(r#"=LOWER("{B}")"#); + let sent = cadcraft_engine::mtext_edit::Formatted::from_contents(&edited).to_contents(); + assert_eq!(ed.kind, cadcraft_engine::EditorKind::Dimension { measured: "1250.0000".into() }); + s.input(Input::Text(sent)).unwrap(); + assert_eq!(dim(&s).marks.formula.as_deref(), Some(r#"=LOWER("{B}")"#)); + assert_eq!(dim(&s).text, "{b}", "the result, braces as letters"); +} + +/// 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"); +} diff --git a/crates/engine/tests/usage.rs b/crates/engine/tests/usage.rs index e70d9d6387..a713725df6 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/fonts/src/complex.rs b/crates/fonts/src/complex.rs index fd85b2b164..1bbe9c1a0c 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -83,7 +83,10 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 let scale_x = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; let shear = oblique.tan().clamp(-10.0, 10.0); let stroke_scale = normalized_height / stroke::CAP; - let characters: Vec = chars.iter().map(|character| character.0).collect(); + // A sign the font lacks (the diameter sign of `%%c`) is drawn by a stand-in it has; the + // directions come from the text as typed (the stand-in Ø is a letter, the sign is not). + let typed: Vec = chars.iter().map(|character| character.0).collect(); + let characters: Vec = typed.iter().map(|character| ttf::sign_for(primary, *character)).collect(); let flags = |index: usize| chars.get(index).map_or((false, false), |character| (character.1, character.2)); let mut shaped = Shaped::default(); let mut points_left = ttf::MAX_SHAPED_POINTS; @@ -91,7 +94,7 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 let mut pen_x = 0.0; // Whether the rightmost glyph so far is a stroke-font glyph. let mut stroke_last = false; - for (run, rtl) in bidi::visual_runs(&characters, base_rtl) { + for (run, rtl) in bidi::visual_runs(&typed, base_rtl) { let mut pieces = itemize(&characters, run, primary); if rtl { pieces.reverse(); diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index c33799368b..9001e9b835 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -19,6 +19,7 @@ pub mod bidi; mod complex; mod linebreak; mod mtext; +mod sfnt_name; pub mod shx; mod stroke; pub mod subset; diff --git a/crates/fonts/src/sfnt_name.rs b/crates/fonts/src/sfnt_name.rs new file mode 100644 index 0000000000..e539c75f68 --- /dev/null +++ b/crates/fonts/src/sfnt_name.rs @@ -0,0 +1,161 @@ +//! A font file's family name, read from its `name` table alone: the table directory and the +//! table, not the whole file. Font lists name every installed font this way; reading each whole +//! file (system font folders hold hundreds of megabytes) only to list it was too slow. +//! +//! The layout is OpenType's (`sfnt` header, table records, `name` table records), for single +//! fonts and collections (the first font of a `ttcf`). + +/// Most tables a font directory may list. +const MAX_TABLES: usize = 512; +/// Most bytes of a `name` table read. +const MAX_NAME_TABLE: usize = 1 << 20; +/// Longest family name kept, in characters. +const MAX_CHARS: usize = 80; + +/// Name ids: the typographic family (16) when it is set, else the family (1). +const TYPOGRAPHIC_FAMILY: u16 = 16; +const FAMILY: u16 = 1; + +fn u16_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(u16::from_be_bytes([*s.first()?, *s.get(1)?])) +} + +fn u32_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_be_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?])) +} + +/// The family name of the font whose bytes `read(offset, len)` gives (fewer bytes at the end of +/// the file are fine; `None` when the range can't be read at all). +pub(crate) fn family(read: &mut dyn FnMut(u64, usize) -> Option>) -> Option { + let head = read(0, 16)?; + let font = if head.get(..4) == Some(b"ttcf") { u64::from(u32_at(&head, 12)?) } else { 0 }; + let sfnt = read(font, 12)?; + let tables = usize::from(u16_at(&sfnt, 4)?).min(MAX_TABLES); + let dir = read(font.checked_add(12)?, tables.checked_mul(16)?)?; + let (offset, length) = (0..tables).find_map(|i| { + let r = i.checked_mul(16)?; + (dir.get(r..r.checked_add(4)?)? == b"name").then(|| Some((u32_at(&dir, r + 8)?, u32_at(&dir, r + 12)?)))? + })?; + let table = read(u64::from(offset), usize::try_from(length).ok()?.min(MAX_NAME_TABLE))?; + family_in(&table) +} + +/// The family name in a `name` table. +pub(crate) fn family_in(t: &[u8]) -> Option { + let count = usize::from(u16_at(t, 2)?); + let strings = usize::from(u16_at(t, 4)?); + // (score, text): Windows Unicode in US English first, then any Windows Unicode, then + // Unicode, then Macintosh Roman. + let mut best: Option<(u8, u16, String)> = None; + for i in 0..count.min(4096) { + let r = i.checked_mul(12)?.checked_add(6)?; + let (platform, encoding, language, id) = (u16_at(t, r)?, u16_at(t, r + 2)?, u16_at(t, r + 4)?, u16_at(t, r + 6)?); + if id != FAMILY && id != TYPOGRAPHIC_FAMILY { + continue; + } + let (len, off) = (usize::from(u16_at(t, r + 8)?), usize::from(u16_at(t, r + 10)?)); + let start = strings.checked_add(off)?; + let Some(raw) = t.get(start..start.checked_add(len)?) else { continue }; + let (score, text) = match platform { + 3 if encoding == 1 || encoding == 10 => (if language == 0x409 { 4 } else { 3 }, utf16(raw)), + 0 => (2, utf16(raw)), + 1 if encoding == 0 => (1, raw.iter().map(|b| char::from(*b)).collect()), + _ => continue, + }; + let text: String = text.chars().filter(|c| !c.is_control()).take(MAX_CHARS).collect(); + let text = text.trim().to_string(); + if text.is_empty() { + continue; + } + // The typographic family wins over the family at the same score. + let rank = (score, u16::from(id == TYPOGRAPHIC_FAMILY)); + if best.as_ref().is_none_or(|(s, i, _)| rank > (*s, u16::from(*i == TYPOGRAPHIC_FAMILY))) { + best = Some((score, id, text)); + } + } + best.map(|(_, _, t)| t) +} + +fn utf16(raw: &[u8]) -> String { + let units: Vec = raw.chunks_exact(2).filter_map(|c| Some(u16::from_be_bytes([*c.first()?, *c.get(1)?]))).collect(); + char::decode_utf16(units).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)).collect() +} + +/// [`family`] of a font in memory. +pub(crate) fn family_of_bytes(bytes: &[u8]) -> Option { + family(&mut |off, len| { + let start = usize::try_from(off).ok()?; + let end = start.checked_add(len)?.min(bytes.len()); + bytes.get(start..end).map(<[u8]>::to_vec) + }) +} + +/// [`family`] of a font file, reading only its directory and `name` table. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn family_of_file(path: &std::path::Path) -> Option { + use std::io::{Read, Seek, SeekFrom}; + let mut f = std::fs::File::open(path).ok()?; + family(&mut |off, len| { + f.seek(SeekFrom::Start(off)).ok()?; + let mut buf = Vec::new(); + (&mut f).take(u64::try_from(len).ok()?).read_to_end(&mut buf).ok()?; + Some(buf) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A one-table font whose `name` table holds `records` (platform, encoding, language, id, + /// text). + fn font(records: &[(u16, u16, u16, u16, &str)]) -> Vec { + let mut strings: Vec = Vec::new(); + let mut recs: Vec = Vec::new(); + for (p, e, l, id, text) in records { + let bytes: Vec = if *p == 1 { text.bytes().collect() } else { text.encode_utf16().flat_map(u16::to_be_bytes).collect() }; + for v in [*p, *e, *l, *id, bytes.len() as u16, strings.len() as u16] { + recs.extend(v.to_be_bytes()); + } + strings.extend(bytes); + } + let mut name = Vec::new(); + for v in [0u16, records.len() as u16, (6 + recs.len()) as u16] { + name.extend(v.to_be_bytes()); + } + name.extend(recs); + name.extend(strings); + let mut f = Vec::new(); + f.extend(0x0001_0000u32.to_be_bytes()); + f.extend(1u16.to_be_bytes()); + f.extend([0u8; 6]); + f.extend(*b"name"); + f.extend(0u32.to_be_bytes()); + f.extend(28u32.to_be_bytes()); + f.extend((name.len() as u32).to_be_bytes()); + f.extend(name); + f + } + + #[test] + fn the_family_comes_from_the_name_table() { + let f = font(&[(1, 0, 0, 1, "Mac Name"), (3, 1, 0x409, 1, "Arial"), (3, 1, 0x40C, 1, "Arial FR"), (3, 1, 0x409, 4, "Arial Regular")]); + assert_eq!(family_of_bytes(&f).as_deref(), Some("Arial")); + // The typographic family wins. + let f = font(&[(3, 1, 0x409, 1, "Segoe UI Light"), (3, 1, 0x409, 16, "Segoe UI")]); + assert_eq!(family_of_bytes(&f).as_deref(), Some("Segoe UI")); + // A Macintosh-only name still names it. + assert_eq!(family_of_bytes(&font(&[(1, 0, 0, 1, "Old")])).as_deref(), Some("Old")); + } + + #[test] + fn broken_fonts_have_no_family() { + assert_eq!(family_of_bytes(&[]), None); + assert_eq!(family_of_bytes(b"ttcf\0\0\0\0\0\0\0\x01\xff\xff\xff\xff"), None); + let mut f = font(&[(3, 1, 0x409, 1, "Arial")]); + f.truncate(40); + assert_eq!(family_of_bytes(&f), None); + } +} diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 363eb4cfcb..925971ba02 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -266,6 +266,9 @@ struct Db { /// Names read from user font files for lists and family searches, by stem. Reading them /// does not keep the file's bytes, so it does not use up `MAX_LOADED_BYTES`. face_names: HashMap>, + /// Family names of installed fonts for lists, by stem, read from the files' `name` tables + /// alone ([`crate::sfnt_name`]). + listed: HashMap>, } /// The names inside one font file. @@ -476,6 +479,7 @@ pub fn rescan() { g.loaded_bytes = 0; g.user.clear(); g.face_names.clear(); + g.listed.clear(); drop(g); GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); // SHX files in the same folders: the SHX font table looks there too. @@ -545,6 +549,8 @@ pub struct FontFile { pub fn installed() -> Vec { /// Fonts whose family name is read for the list. const MAX_NAMED: usize = 200; + /// Other fonts whose family name is read for the list (from the name table only). + const MAX_LISTED: usize = 5000; let mut g = lock(); let mut list: Vec<(String, String, bool)> = g .paths @@ -559,11 +565,15 @@ pub fn installed() -> Vec { .collect(); list.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase()))); let mut named = 0usize; + let mut listed = 0usize; list.into_iter() .map(|(stem, name, user)| { let family = if user && named < MAX_NAMED { named += 1; g.face_names(&stem).and_then(|n| n.family.clone()) + } else if listed < MAX_LISTED { + listed += 1; + g.listed_family(&stem) } else { None }; @@ -622,6 +632,22 @@ impl Db { })) } + /// The family name of an installed font for lists, read once from its name table alone. + fn listed_family(&mut self, stem: &str) -> Option { + if let Some(f) = self.listed.get(stem) { + return f.clone(); + } + let family = match self.paths.get(stem)? { + #[cfg(not(target_arch = "wasm32"))] + Source::File(path) => crate::sfnt_name::family_of_file(path), + #[cfg(target_arch = "wasm32")] + Source::File(_) => None, + Source::Static(bytes) => crate::sfnt_name::family_of_bytes(bytes), + }; + self.listed.insert(stem.to_string(), family.clone()); + family + } + /// The names inside the font file with this stem, read once (the bytes are dropped after). fn face_names(&mut self, stem: &str) -> Option> { if let Some(n) = self.face_names.get(stem) { @@ -1146,13 +1172,42 @@ pub(crate) fn fallback_glyph(c: char) -> Option> { /// The glyph of `c` in `face`, or from a fallback font when `face` lacks it. fn glyph_or_fallback(face: &Face, c: char) -> Arc { - let g = glyph(face, c); + let g = glyph(face, sign_for(Some(face), c)); if g.mapped || c.is_whitespace() { return g; } fallback_glyph(c).unwrap_or(g) } +/// Characters that stand in for a sign a font lacks, best first: the diameter sign of `%%c` +/// (U+2300) is missing from many fonts (Arial among them), which have the empty-set sign +/// (U+2205) or at least the letter Ø that it looks like. +fn sign_substitutes(c: char) -> &'static [char] { + match c { + '\u{2300}' => &['\u{2205}', '\u{00D8}'], + '\u{2205}' => &['\u{2300}', '\u{00D8}'], + _ => &[], + } +} + +/// The character that draws `c` in `face` (`None`: the stroke font, which has the signs): `c` +/// when the face has it, else a stand-in the face has ([`sign_substitutes`]), so the sign keeps +/// the text's font, else `c` when a fallback font has it, else a stand-in a fallback font has. +pub(crate) fn sign_for(face: Option<&Face>, c: char) -> char { + let subs = sign_substitutes(c); + let Some(face) = face else { return c }; + if subs.is_empty() || face.has_glyph(c) { + return c; + } + if let Some(s) = subs.iter().find(|s| face.has_glyph(**s)) { + return *s; + } + if fallback_for(c).is_some() { + return c; + } + subs.iter().copied().find(|s| fallback_for(*s).is_some()).unwrap_or(c) +} + /// The [`crate::TextGlyph`] of a glyph placed like [`place_glyph`] does (its outline index is /// set when it is added). `None` for the missing-glyph shape. pub(crate) fn text_glyph(g: &GlyphOutline, c: char, x: f64, h: f64, wf: f64, shear: f64) -> Option { @@ -1495,4 +1550,26 @@ mod scan_tests { #[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_env = "ohos"))))] assert!(dirs.iter().any(|d| d == std::path::Path::new("/usr/share/fonts")), "{dirs:?}"); } + + /// A font without the diameter sign of `%%c` draws a stand-in it has (the empty-set sign or + /// Ø), not its missing-glyph box (#2330 review: Arial). + #[test] + fn a_font_without_the_diameter_sign_draws_a_stand_in() { + // Any installed font that lacks U+2300 and has Ø; none on this machine: nothing to show. + let Some(face) = ["arial", "liberationsans", "dejavusans", "freesans", "carlito"] + .iter() + .filter_map(|n| find(n)) + .find(|f| !f.has_glyph('\u{2300}') && f.has_glyph('\u{00D8}')) + else { + return; + }; + let c = sign_for(Some(&face), '\u{2300}'); + assert_ne!(c, '\u{2300}'); + assert!(face.has_glyph(c), "the stand-in is the text's own font's"); + assert!(glyph_or_fallback(&face, '\u{2300}').mapped); + // A sign the font has, and any other character, are left alone. + assert_eq!(sign_for(Some(&face), '\u{00B0}'), '\u{00B0}'); + assert_eq!(sign_for(Some(&face), 'a'), 'a'); + assert_eq!(sign_for(None, '\u{2300}'), '\u{2300}'); + } } diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 710634dc66..73d7aee7d8 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -20,6 +20,57 @@ 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 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 + // 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() { + 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. @@ -986,3 +1037,21 @@ mod tests { assert!(!is_named_frame(&unit, Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0), Vec3::new(-1.0, 0.0, 0.0))); } } + +#[cfg(test)] +mod formula_cap_tests { + use super::{FORMULA_APP, MAX_FORMULA_BYTES, formula}; + use craft_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 new file mode 100644 index 0000000000..4680d14e8a --- /dev/null +++ b/crates/io/src/dxf_fields.rs @@ -0,0 +1,239 @@ +//! 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 craft_dxf::{SectionRef, 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) +} + +/// 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: &[SectionRef<'_>], 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; + } + // 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 { + 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 craft_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 c644eb558e..ff0e076886 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_raw.rs b/crates/io/src/dxf_raw.rs index 49f74e472c..04acd810bb 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -44,7 +44,7 @@ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_LAYERSTATES", "ACA /// 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; @@ -1011,6 +1011,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap = own.iter().filter_map(|(h, o)| Some((h.clone(), o.clone()?))).collect(); + let replaced = replaced_fields(f, d, &owners); let alive_memo = settle(&hard, |kept: &HashMap| { // Keep established live paths available to descendants during this pass as well. let mut alive_memo: HashMap = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect(); @@ -1019,6 +1022,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap = Vec::new(); let mut cur = o.handle.hex(); @@ -1123,6 +1127,41 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &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; + } + // 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, h)| up(k) == "ACAD_FIELD" && crate::dxf_fields::resolves(&objects, &up(h))).map(|(_, h)| norm(&h)), + ); + } + out +} + /// Kept extension dictionaries of written records: those that go on a record without its own, /// and those whose entries join the one the writer gave a table (the LAYER table's, holding the /// layer states) as kept dictionary → the written one. diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 88f6940d26..ebd816b550 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -176,6 +176,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize) d.layers.insert(0, Layer::default()); } crate::dxf_raw::read(&secs, &mut d); + crate::dxf_fields::resolve(&secs, &mut d); crate::dxf_clip::read(&mut d); if rx.curves.cut > 0 { // Echoed on open, returned by OPEN and listed by the CLI, so a coarse boundary is never silent. diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 1801a125d4..2bc80655d6 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -495,6 +495,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), @@ -520,6 +521,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()); } @@ -619,6 +623,8 @@ pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer 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 df73b878c3..60924536d2 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -74,6 +74,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), // An MTEXT's width is one column's: with columns, the column width (48, or 44 of the @@ -119,6 +120,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 { @@ -167,6 +169,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/blocks.rs b/crates/io/src/dxf_write/blocks.rs index 2de1400cf8..b15ecaf7d0 100644 --- a/crates/io/src/dxf_write/blocks.rs +++ b/crates/io/src/dxf_write/blocks.rs @@ -116,6 +116,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, @@ -170,6 +171,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 ac823dbfec..26b25cddcd 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::{ @@ -278,13 +278,25 @@ 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. EntityKind::Region(r) => { @@ -308,6 +320,7 @@ fn write_text_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"); @@ -319,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() { @@ -336,6 +350,7 @@ fn write_text_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, cx.target >= Version::R2018 && !cx.legacy_columns)); + formula_xdata(w, t.formula.as_deref()); } _ => {} } @@ -381,6 +396,7 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b 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"); @@ -476,6 +492,7 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper } } dim_xdata(w, dm, cx); + formula_xdata(w, dm.marks.formula.as_deref()); } } @@ -561,6 +578,7 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap 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/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 3a4b1a5271..93d082239a 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -182,7 +182,7 @@ 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]; + let apps = ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP, dxf_ext::FORMULA_APP]; let th = table_head(w, "APPID", apps.len()); for app in apps { record_head(w, "APPID", &th, "AcDbRegAppTableRecord"); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index d08d01d933..fe90220314 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -8,6 +8,7 @@ mod dxf_raw; /// XCLIP boundaries as SPATIAL_FILTER objects. mod dxf_clip; mod dxf_ext; +mod dxf_fields; mod dxf_image; mod dxf_layer_states; mod dxf_mleader; diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 01617da3b5..ce52d2f280 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, @@ -260,6 +262,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, @@ -1966,6 +1969,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, @@ -1990,6 +1994,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, @@ -2232,6 +2237,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, @@ -2266,6 +2272,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 c5e408d79d..57498f0056 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, @@ -208,6 +209,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 52cd6e762c..35152f66a1 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 6e71e4b7e0..e56c25d882 100644 --- a/crates/io/tests/it/attrib_modes.rs +++ b/crates/io/tests/it/attrib_modes.rs @@ -9,6 +9,7 @@ use cadcraft_io::{SaveOptions, Version, read_dxf, write_dxf, write_with}; 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 3b750fa7a8..aa17fc3b2b 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 10aaa07a5b..df43b1033c 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 149cbd5510..79f20fdacd 100644 --- a/crates/io/tests/it/entity_props_roundtrip.rs +++ b/crates/io/tests/it/entity_props_roundtrip.rs @@ -72,6 +72,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 10e355cd34..8e88cc057d 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 86a771a43b..2b576ede47 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -80,6 +80,7 @@ mod svg_tiny_extents; mod table_cellstyle_roundtrip; mod tables_objects_roundtrip; mod text_carets_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 f55da8925c..a2a016ebbe 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, @@ -79,6 +80,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_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs index 88c901245d..e23f8b2dde 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) -> 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/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 e263f47f82..4a2a2aadeb 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 0f8d4a29dd..583427c954 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 19e15beaaa..c6cff5c461 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/io/tests/it/text_carets_roundtrip.rs b/crates/io/tests/it/text_carets_roundtrip.rs index 3e8532855f..49249f2b88 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, 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..d680fd864b --- /dev/null +++ b/crates/io/tests/it/text_formula_roundtrip.rs @@ -0,0 +1,277 @@ +//! 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(); + // The xdata application is registered (AutoCAD refuses xdata of an unknown application). + let text = String::from_utf8_lossy(&bytes); + assert!(text.contains("APPID") && text.matches("CADCRAFTFORMULA").count() >= 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")))); + 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 { + clip: Default::default(), + 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)), + _ => {} + } + } +} + +/// 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)); +} + +/// 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")); + } +} + +/// 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"); +} diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index a0f96dd67d..8b3fed67de 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, @@ -369,6 +370,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 44d5b48da8..ad9c171e6a 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -20,6 +20,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 73b8932bb4..7ef7306f72 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -54,6 +54,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. diff --git a/crates/render/src/dim/linear.rs b/crates/render/src/dim/linear.rs index 3dc7401865..aab5c6be8e 100644 --- a/crates/render/src/dim/linear.rs +++ b/crates/render/src/dim/linear.rs @@ -1,4 +1,4 @@ -use super::text::linear_text; +use super::text::{linear_formula_value, linear_text}; use super::{DimConfig, DimGeometry, DimKind, LineRole, Vec2, ext_line, readable}; struct LinearDimState { @@ -55,6 +55,7 @@ fn prepare_linear(config: &DimConfig<'_>, g: &mut DimGeometry, text_mid: Vec2) - }; let (f1, f2) = (foot(p1), foot(p2)); let raw_measurement = (p2 - p1).dot(direction).abs(); + g.formula_value = Some(linear_formula_value(raw_measurement, st)); g.mtext = linear_text(raw_measurement, d, st, ""); g.measurement = raw_measurement; let measurement = f1.dist(f2); diff --git a/crates/render/src/dim/text.rs b/crates/render/src/dim/text.rs index 91e6b568c5..062396e2dd 100644 --- a/crates/render/src/dim/text.rs +++ b/crates/render/src/dim/text.rs @@ -49,7 +49,38 @@ 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(linear_formula_value(meas, st))), 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 } +} + +/// 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. @@ -78,8 +109,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/dim/variants.rs b/crates/render/src/dim/variants.rs index 8c35986c5a..ff8f2485bd 100644 --- a/crates/render/src/dim/variants.rs +++ b/crates/render/src/dim/variants.rs @@ -1,4 +1,4 @@ -use super::text::{apply_override, inspected, linear_text}; +use super::text::{angular_formula_value, apply_override, inspected, linear_formula_value, linear_text}; use super::{Arrowhead, DimConfig, DimGeometry, DimKind, Vec2, ext_line, readable}; use crate::units::format_angle_with_separator; use cadcraft_geom::{Arc, ccw_sweep}; @@ -22,6 +22,7 @@ pub(super) fn draw_jogged_radius(config: &DimConfig<'_>, g: &mut DimGeometry, te 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() { @@ -73,6 +74,7 @@ pub(super) fn draw_radius_or_diameter(config: &DimConfig<'_>, g: &mut DimGeometr 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); @@ -180,7 +182,8 @@ pub(super) fn draw_angular(config: &DimConfig<'_>, g: &mut DimGeometry, text_ang 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.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); @@ -224,6 +227,7 @@ pub(super) fn draw_ordinate(config: &DimConfig<'_>, g: &mut DimGeometry, text_an 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); @@ -257,6 +261,7 @@ pub(super) fn draw_arc_length(config: &DimConfig<'_>, g: &mut DimGeometry, text_ 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/lib.rs b/crates/render/src/lib.rs index 1adaaddd59..214a0f8157 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; @@ -34,6 +35,7 @@ pub use dim::{ArrowGeom, Arrowhead, DimGeometry, DimText, LineRole, arrowhead, d pub use fill::triangulate_evenodd; pub use hatch::{fill_loops as hatch_fill_loops, pattern_swatch}; pub use paper::{PAPER_SIZES, PaperSize, Sheet, paper_size, sheet}; +pub use text::triangulate_placed as triangulate_glyph; pub use tolerance::{gdt_points, tolerance_in}; /// A resolved colour: its RGB, whether it is colour 7, and its index colour (0 = a true diff --git a/crates/render/src/linetype_text.rs b/crates/render/src/linetype_text.rs index ddf8b4f84f..9927c31500 100644 --- a/crates/render/src/linetype_text.rs +++ b/crates/render/src/linetype_text.rs @@ -317,6 +317,7 @@ mod tests { let mut d = Drawing::new_imperial(); d.text_styles.push(cadcraft_doc::TextStyle { name: "SHX".into(), font: "cadcraft-render-text.shx".into(), ..Default::default() }); let t = cadcraft_doc::Text { + formula: None, insert: cadcraft_geom::Vec3::new(0.0, 0.0, 0.0), align_pt: None, height: 3.0, diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index afd68209e0..2701cf7fef 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, @@ -256,6 +257,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, @@ -330,6 +332,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, @@ -768,6 +771,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, @@ -865,6 +869,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/text.rs b/crates/render/src/text.rs index 8e692facd2..0226af6f35 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -196,7 +196,7 @@ fn triangulate(contours: &[Vec]) -> Vec { /// [`triangulate`] for a glyph outline already placed in drawing coordinates (complex-script /// runs carry no [`TextGlyph`]): tessellated relative to its first point so f32 keeps the /// precision. Outlines past the limits [`mesh`] applies keep the slab filler. -pub(super) fn triangulate_placed(contours: &[Vec]) -> Vec { +pub fn triangulate_placed(contours: &[Vec]) -> Vec { let Some(&origin) = contours.iter().flatten().next() else { return Vec::new() }; let points = contours.iter().map(Vec::len).try_fold(0usize, usize::checked_add); let out_of_range = |p: &Vec2| { diff --git a/crates/render/src/textformula.rs b/crates/render/src/textformula.rs new file mode 100644 index 0000000000..b56fcdb144 --- /dev/null +++ b/crates/render/src/textformula.rs @@ -0,0 +1,975 @@ +//! 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, Default, PartialEq)] +pub struct Env { + /// 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, +} + +/// 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); + Some((i32::from(z.year()), clamp(z.month()), clamp(z.day()), clamp(z.hour()), clamp(z.minute()), clamp(z.second()))) + } + #[cfg(target_arch = "wasm32")] + { + None + } +} + +/// 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(), + // 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(), + }); + } + 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, + /// A value not known here (no clock, no file or sheet name): not an error to show. + Unknown, +} + +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!", + Err::Unknown => "#N/A", + }) + } +} + +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 { + // 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 ---------- + +#[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 { + // 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; + let b = self.unary()?; + let v = a.num()?.powf(b.num()?); + if !v.is_finite() { + return Err(Err::Num); + } + a = Val::Num(v); + } + 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 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()), + "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.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 { + 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" => known(&env.file), + "SHEET" => known(&env.sheet), + _ => 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 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. 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, + } +} + +/// 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: 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() { + // 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")); + 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() { + 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_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, 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 46028a576a..f4e3b356d0 100644 --- a/crates/render/tests/it/dim_text_fill.rs +++ b/crates/render/tests/it/dim_text_fill.rs @@ -139,6 +139,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, @@ -171,6 +172,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, @@ -201,6 +203,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, @@ -231,6 +234,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 b0361c21f6..8466e29121 100644 --- a/crates/render/tests/it/render_props.rs +++ b/crates/render/tests/it/render_props.rs @@ -101,6 +101,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/bidi_edit.rs b/crates/ui-egui/src/bidi_edit.rs new file mode 100644 index 0000000000..b57a7d17c7 --- /dev/null +++ b/crates/ui-egui/src/bidi_edit.rs @@ -0,0 +1,773 @@ +//! The text box of the text editors: text in the drawing's fonts, laid out as the drawing lays it +//! out, with left-to-right and right-to-left scripts mixed on one line the way word processors +//! do it (the Unicode Bidirectional Algorithm, each paragraph's direction from its first strong +//! character). +//! +//! The text is kept in logical order (the order it is typed and stored). Each line is shown in +//! display order; the caret sits after the character before it (at its right edge in +//! left-to-right text, its left edge in right-to-left text); Left and Right move the caret one +//! place left or right on screen, whatever the direction of the text under it; a selection +//! covers a range of the logical text and lights up every character in it, wherever it is shown. + +use egui::{Color32, Event, Key, Pos2, Rect, Sense, Stroke, pos2, vec2}; + +use crate::editor_glyphs::{self, EditorFont}; + +/// Most undo steps kept. +const MAX_UNDO: usize = 100; + +/// How a character looks. +#[derive(Clone, Debug, PartialEq)] +pub struct Look { + pub font: EditorFont, + pub italic: bool, + pub bold: bool, + pub underline: bool, + /// Size in points (the cap height is [`editor_glyphs::CAP`] of it). + pub size: f32, + pub color: Color32, +} + +/// The caret and selection (character indices into the text), kept between frames. +#[derive(Clone, Debug, Default)] +pub struct EditState { + pub cursor: usize, + pub anchor: usize, + /// Horizontal scroll of a one-line box. + scroll_x: f32, + /// For Up and Down: the x the caret aims at. + preferred_x: Option, + undo: Vec<(String, usize)>, + redo: Vec<(String, usize)>, + /// The input method's composition (pre-edit) text: shown at the caret while composing, not + /// part of the text until it is committed. + pub preedit: String, +} + +impl EditState { + pub fn at(i: usize) -> Self { + EditState { cursor: i, anchor: i, ..Default::default() } + } + /// Everything selected, the caret at the end. + pub fn all(len: usize) -> Self { + EditState { cursor: len, anchor: 0, ..Default::default() } + } + /// The selection, low to high. + pub fn range(&self) -> (usize, usize) { + (self.cursor.min(self.anchor), self.cursor.max(self.anchor)) + } +} + +/// What a frame of the box did. +pub struct Output { + pub response: egui::Response, + pub changed: bool, + /// The caret's bottom on screen (where a completion list goes). + pub caret: Pos2, +} + +/// A character placed on a line. +#[derive(Clone, Copy, Debug)] +struct Cell { + /// Index in the text. + idx: usize, + /// Left edge and width (box coordinates). + x: f32, + w: f32, + rtl: bool, +} + +#[derive(Clone, Debug)] +struct Line { + /// Logical range of the line's characters (a paragraph's `\n` is not in it). + start: usize, + end: usize, + top: f32, + height: f32, + baseline: f32, + /// The paragraph runs right to left. + rtl: bool, + /// The characters in display order, left to right. + cells: Vec, +} + +struct Layout { + lines: Vec, + width: f32, + height: f32, +} + +/// Characters laid out in lines: wrapped at spaces to `wrap` (one line: no wrapping), each line +/// put in display order. +fn layout(chars: &[char], look: &dyn Fn(usize) -> Look, wrap: Option, default_size: f32) -> Layout { + let adv: Vec = chars + .iter() + .enumerate() + .map(|(i, c)| { + if *c == '\n' { + 0.0 + } else { + let l = look(i); + editor_glyphs::advance(&l.font, l.italic, *c, l.size) + } + }) + .collect(); + let sizes: Vec = (0..chars.len()).map(|i| look(i).size).collect(); + // Logical lines: paragraphs split at `\n`, wrapped. + let mut ranges: Vec<(usize, usize, bool)> = Vec::new(); + let mut p0 = 0usize; + let mut para_rtl = false; + for p1 in (0..=chars.len()).filter(|i| *i == chars.len() || chars.get(*i) == Some(&'\n')) { + let par: String = chars.get(p0..p1).unwrap_or_default().iter().collect(); + // A paragraph without strong characters keeps the direction of the one before. + para_rtl = cadcraft_fonts::bidi::base_rtl(&par).unwrap_or(para_rtl); + let mut s = p0; + while s < p1 { + let mut w = 0.0; + let mut e = s; + let mut last_space = None; + while e < p1 { + let a = adv.get(e).copied().unwrap_or(0.0); + if let Some(limit) = wrap + && w + a > limit + && e > s + && chars.get(e) != Some(&' ') + { + break; + } + if chars.get(e) == Some(&' ') { + last_space = Some(e + 1); + } + w += a; + e += 1; + } + if e < p1 + && let Some(b) = last_space.filter(|b| *b > s && *b < e) + { + e = b; + } + ranges.push((s, e, para_rtl)); + s = e; + } + if p0 == p1 { + ranges.push((p0, p1, para_rtl)); + } + p0 = p1 + 1; + } + if ranges.is_empty() { + ranges.push((0, 0, false)); + } + let mut lines = Vec::with_capacity(ranges.len()); + let mut y = 0.0; + let mut width: f32 = 0.0; + for (s, e, rtl) in ranges { + let max = (s..e).filter_map(|i| sizes.get(i).copied()).fold(0.0f32, f32::max); + let size = if max > 0.0 { max } else { default_size }; + let height = size * 1.45; + let baseline = y + size * 1.05; + let text: String = chars.get(s..e).unwrap_or_default().iter().collect(); + let order: Vec = if cadcraft_fonts::bidi::has_rtl(&text) { + let levels = cadcraft_fonts::bidi::char_levels(&text, Some(rtl)); + cadcraft_fonts::bidi::reorder(&levels).into_iter().map(|k| k + s).collect::>() + } else { + (s..e).collect() + }; + let levels = if cadcraft_fonts::bidi::has_rtl(&text) { cadcraft_fonts::bidi::char_levels(&text, Some(rtl)) } else { Vec::new() }; + let mut x = 0.0; + let mut cells = Vec::with_capacity(order.len()); + for i in order { + let w = adv.get(i).copied().unwrap_or(0.0); + let r = levels.get(i - s).is_some_and(|l| l % 2 == 1); + cells.push(Cell { idx: i, x, w, rtl: r }); + x += w; + } + width = width.max(x); + lines.push(Line { start: s, end: e, top: y, height, baseline, rtl, cells }); + y += height; + } + Layout { lines, width, height: y } +} + +impl Layout { + /// The line the caret at `c` is on: the last line holding `c` (a wrapped line's end is the + /// next line's start). + fn line_of(&self, c: usize) -> usize { + self.lines.iter().rposition(|l| l.start <= c && c <= l.end).unwrap_or(0) + } + fn cell(&self, line: usize, idx: usize) -> Option { + self.lines.get(line)?.cells.iter().find(|k| k.idx == idx).copied() + } + /// The caret's x at `c`: after the character before it (its right edge in left-to-right + /// text, its left edge in right-to-left text); at a line's start, before its first + /// character. + fn caret_x(&self, c: usize) -> (usize, f32) { + let li = self.line_of(c); + let Some(l) = self.lines.get(li) else { return (0, 0.0) }; + if c > l.start + && let Some(k) = self.cell(li, c - 1) + { + return (li, if k.rtl { k.x } else { k.x + k.w }); + } + if let Some(k) = self.cell(li, c) { + return (li, if k.rtl { k.x + k.w } else { k.x }); + } + // An empty line: at its start side. + let right = l.cells.iter().map(|k| k.x + k.w).fold(0.0, f32::max); + (li, if l.rtl { right } else { 0.0 }) + } + /// The caret position nearest `x` on line `li`. + fn index_at(&self, li: usize, x: f32) -> usize { + let Some(l) = self.lines.get(li) else { return 0 }; + let mut best = (f32::INFINITY, l.start); + for c in l.start..=l.end { + let (cl, cx) = self.caret_x(c); + if cl != li { + continue; + } + let d = (cx - x).abs(); + if d < best.0 { + best = (d, c); + } + } + best.1 + } + /// The caret position one place left (`dir` −1) or right (+1) on screen from `c`. + fn step(&self, c: usize, dir: f32) -> usize { + let (li, x) = self.caret_x(c); + let Some(l) = self.lines.get(li) else { return c }; + let mut best: Option<(f32, usize)> = None; + for k in l.start..=l.end { + let (kl, kx) = self.caret_x(k); + if kl != li || k == c { + continue; + } + let d = (kx - x) * dir; + if d > 0.5 && best.is_none_or(|(bd, bk)| d < bd - 0.01 || ((d - bd).abs() <= 0.01 && k.abs_diff(c) < bk.abs_diff(c))) { + best = Some((d, k)); + } + } + if let Some((_, k)) = best { + return k; + } + // Off the end of the line: the neighbouring line, in reading order. + let forward = (dir > 0.0) != l.rtl; + if forward { + if li + 1 < self.lines.len() { + return self.lines.get(li + 1).map_or(c, |n| n.start); + } + } else if li > 0 { + // At a soft wrap the previous line ends where this one starts: the same caret place, + // which belongs to this line. Go one character into the previous line instead. + return self.lines.get(li - 1).map_or(c, |p| if p.end == c { c.saturating_sub(1).max(p.start) } else { p.end }); + } + c + } +} + +/// Character classes for word moves and double clicks. +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn word_left(chars: &[char], mut c: usize) -> usize { + while c > 0 && chars.get(c - 1).is_some_and(|ch| !is_word(*ch)) { + c -= 1; + } + while c > 0 && chars.get(c - 1).is_some_and(|ch| is_word(*ch)) { + c -= 1; + } + c +} + +fn word_right(chars: &[char], mut c: usize) -> usize { + let n = chars.len(); + while c < n && chars.get(c).is_some_and(|ch| is_word(*ch)) { + c += 1; + } + while c < n && chars.get(c).is_some_and(|ch| !is_word(*ch)) { + c += 1; + } + c +} + +/// Replace the selection by `s` (an empty `s` deletes it). +fn replace(chars: &mut Vec, st: &mut EditState, s: &str, max_chars: usize) -> bool { + let (a, b) = st.range(); + let ins: Vec = s.chars().collect(); + if a == b && ins.is_empty() { + return false; + } + let room = max_chars.saturating_sub(chars.len() - (b - a)); + let ins: Vec = ins.into_iter().take(room).collect(); + let b = b.min(chars.len()); + let a = a.min(b); + chars.splice(a..b, ins.iter().copied()); + st.cursor = a + ins.len(); + st.anchor = st.cursor; + true +} + +/// What the box shows and takes: the characters' look, one line or several, the width +/// available to the text, the size of text without a look and the most characters. +struct Frame<'a> { + look: &'a dyn Fn(usize) -> Look, + single_line: bool, + inner_w: f32, + default_size: f32, + max_chars: usize, +} + +impl Frame<'_> { + fn layout(&self, chars: &[char]) -> Layout { + layout(chars, self.look, (!self.single_line).then_some(self.inner_w), self.default_size) + } +} + +/// Show the box: `width` wide, at least `min_rows` lines tall (one line: `single_line`), the +/// characters looking as `look` says. Returns whether the text changed. +#[allow(clippy::too_many_arguments)] +pub fn show( + ui: &mut egui::Ui, + id: egui::Id, + text: &mut String, + st: &mut EditState, + single_line: bool, + width: f32, + min_rows: usize, + look: &dyn Fn(usize) -> Look, + default_size: f32, + max_chars: usize, +) -> Output { + let margin = 5.0; + let mut chars: Vec = text.chars().collect(); + let n0 = chars.len(); + st.cursor = st.cursor.min(n0); + st.anchor = st.anchor.min(n0); + let frame = Frame { look, single_line, inner_w: (width - 2.0 * margin).max(20.0), default_size, max_chars }; + let lay = frame.layout(&chars); + let row_h = default_size * 1.45; + let h = lay.height.max(row_h * min_rows.max(1) as f32) + 2.0 * margin; + let (rect, _) = ui.allocate_exact_size(vec2(width, h), Sense::hover()); + let focused = ui.memory(|m| m.has_focus(id)); + let response = ui.interact(rect, id, Sense::click_and_drag()); + if response.clicked() || response.drag_started() { + ui.memory_mut(|m| m.request_focus(id)); + } + // The text cursor (I-beam) over the text, as in any text box. + if response.hovered() || response.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Text); + } + if focused { + ui.memory_mut(|m| { + m.set_focus_lock_filter(id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false }) + }); + } + let scroll = if single_line { st.scroll_x } else { 0.0 }; + pointer(ui, &response, st, &chars, &lay, rect.min + vec2(margin - scroll, margin)); + let changed = focused && edit(ui, &mut chars, st, &frame); + if changed { + *text = chars.iter().collect(); + } + let caret = paint(ui, Painted { id, rect, margin, row_h, focused, response: &response }, &chars, st, &frame); + Output { response, changed, caret } +} + +/// Mouse: place the caret, drag to select, double-click a word. `origin`: the text's top-left +/// on screen. +fn pointer(ui: &egui::Ui, response: &egui::Response, st: &mut EditState, chars: &[char], lay: &Layout, origin: Pos2) { + let hit = |p: Pos2| -> usize { + let y = p.y - origin.y; + let li = lay.lines.iter().position(|l| y < l.top + l.height).unwrap_or(lay.lines.len().saturating_sub(1)); + lay.index_at(li, p.x - origin.x) + }; + let shift = ui.input(|i| i.modifiers.shift); + let Some(p) = response.interact_pointer_pos() else { return }; + if response.double_clicked() { + let c = hit(p); + st.anchor = word_left(chars, (c + 1).min(chars.len())); + st.cursor = word_right(chars, st.anchor).min(chars.len()); + while st.cursor > st.anchor && chars.get(st.cursor - 1).is_some_and(|c| !is_word(*c)) { + st.cursor -= 1; + } + } else if response.drag_started() || response.clicked() { + st.cursor = hit(p); + if !shift { + st.anchor = st.cursor; + } + st.preferred_x = None; + } else if response.dragged() { + st.cursor = hit(p); + } +} + +/// This frame's typing, pasting and keys; whether the text changed. +fn edit(ui: &egui::Ui, chars: &mut Vec, st: &mut EditState, frame: &Frame<'_>) -> bool { + let events = ui.input(|i| i.events.clone()); + let before: String = chars.iter().collect(); + let before_cursor = st.cursor; + let mut edited = false; + let mut changed = false; + for ev in events { + match ev { + Event::Ime(egui::ImeEvent::Preedit { text, .. }) => st.preedit = text, + Event::Text(s) | Event::Paste(s) | Event::Ime(egui::ImeEvent::Commit(s)) => { + st.preedit.clear(); + // Line breaks (Windows' \r\n too) become spaces in a one-line box, before + // other control characters are dropped. + let s = s.replace("\r\n", "\n").replace('\r', "\n"); + let s = if frame.single_line { s.replace('\n', " ") } else { s }; + let s: String = s.chars().filter(|c| !c.is_control() || *c == '\n').collect(); + edited |= replace(chars, st, &s, frame.max_chars); + } + Event::Copy | Event::Cut => { + let (a, b) = st.range(); + if a < b { + ui.ctx().copy_text(chars.get(a..b).unwrap_or_default().iter().collect()); + if matches!(ev, Event::Cut) { + edited |= replace(chars, st, "", frame.max_chars); + } + } + } + Event::Key { key: k, pressed: true, modifiers, .. } => { + let (e, c) = key(chars, st, k, modifiers, frame); + edited |= e; + changed |= c; + } + _ => {} + } + } + if edited { + st.undo.push((before, before_cursor)); + if st.undo.len() > MAX_UNDO { + st.undo.remove(0); + } + st.redo.clear(); + st.preferred_x = None; + changed = true; + } + changed +} + +/// One key: (the text was edited, the text changed by undo or redo). +fn key(chars: &mut Vec, st: &mut EditState, key: Key, modifiers: egui::Modifiers, frame: &Frame<'_>) -> (bool, bool) { + let word = modifiers.command || modifiers.alt; + let max_chars = frame.max_chars; + // Laid out only for the keys that move by what is on screen (arrows, Home, End). + let lay = |chars: &[char]| frame.layout(chars); + let mut moved = None; + let mut edited = false; + let mut changed = false; + match key { + Key::ArrowLeft | Key::ArrowRight => { + let lay = lay(chars); + let dir = if key == Key::ArrowLeft { -1.0 } else { 1.0 }; + let (a, b) = st.range(); + moved = Some(if word { + // A word in reading order: right is forward in left-to-right text. + let li = lay.line_of(st.cursor); + let rtl = lay.lines.get(li).is_some_and(|l| l.rtl); + if (dir > 0.0) != rtl { word_right(chars, st.cursor) } else { word_left(chars, st.cursor) } + } else if a != b && !modifiers.shift { + // Collapse the selection at its left or right end on screen. + let (xa, xb) = (lay.caret_x(a).1, lay.caret_x(b).1); + if (xa < xb) == (dir < 0.0) { a } else { b } + } else { + lay.step(st.cursor, dir) + }); + st.preferred_x = None; + } + Key::ArrowUp | Key::ArrowDown => { + let lay = lay(chars); + let (li, x) = lay.caret_x(st.cursor); + let px = *st.preferred_x.get_or_insert(x); + let to = if key == Key::ArrowUp { li.checked_sub(1) } else { Some(li + 1).filter(|n| *n < lay.lines.len()) }; + moved = Some(match to { + Some(n) => lay.index_at(n, px), + None if key == Key::ArrowUp => 0, + None => chars.len(), + }); + } + Key::Home => { + let lay = lay(chars); + moved = Some(if modifiers.command { 0 } else { lay.lines.get(lay.line_of(st.cursor)).map_or(0, |l| l.start) }); + st.preferred_x = None; + } + Key::End => { + let lay = lay(chars); + moved = Some(if modifiers.command { chars.len() } else { lay.lines.get(lay.line_of(st.cursor)).map_or(0, |l| l.end) }); + st.preferred_x = None; + } + Key::Backspace => { + if st.cursor == st.anchor && st.cursor > 0 { + st.anchor = if word { word_left(chars, st.cursor) } else { st.cursor - 1 }; + } + edited |= replace(chars, st, "", max_chars); + } + Key::Delete => { + if st.cursor == st.anchor && st.cursor < chars.len() { + st.anchor = if word { word_right(chars, st.cursor) } else { st.cursor + 1 }; + } + edited |= replace(chars, st, "", max_chars); + } + Key::Enter if !frame.single_line && !modifiers.command => { + edited |= replace(chars, st, "\n", max_chars); + } + Key::A if modifiers.command => { + st.anchor = 0; + st.cursor = chars.len(); + } + Key::Z | Key::Y if modifiers.command => { + let redo = key == Key::Y || modifiers.shift; + let (from, to) = if redo { (&mut st.redo, &mut st.undo) } else { (&mut st.undo, &mut st.redo) }; + if let Some((prev, c)) = from.pop() { + to.push((chars.iter().collect(), st.cursor)); + *chars = prev.chars().collect(); + st.cursor = c.min(chars.len()); + st.anchor = st.cursor; + changed = true; + } + } + _ => {} + } + if let Some(c) = moved { + st.cursor = c.min(chars.len()); + if !modifiers.shift { + st.anchor = st.cursor; + } + } + (edited, changed) +} + +/// Where and how the box is painted. +struct Painted<'a> { + id: egui::Id, + rect: Rect, + margin: f32, + row_h: f32, + focused: bool, + response: &'a egui::Response, +} + +/// Paint the box, the selection, the characters and the caret (and hand the caret to the IME); +/// the caret's bottom on screen. +fn paint(ui: &egui::Ui, b: Painted<'_>, chars: &[char], st: &mut EditState, frame: &Frame<'_>) -> Pos2 { + let Painted { id, rect, margin, row_h, focused, response } = b; + let t = crate::theme::Tokens::get(); + let look = frame.look; + let single_line = frame.single_line; + let inner_w = frame.inner_w; + let origin = |sx: f32| pos2(rect.left() + margin + sx, rect.top() + margin); + let lay = frame.layout(chars); + let p = ui.painter_at(rect); + p.rect_filled(rect, 2.0, t.field); + p.rect_stroke(rect, 2.0, Stroke::new(if focused { 1.5 } else { 1.0 }, if focused { t.accent } else { t.border }), egui::StrokeKind::Inside); + let (cl, cx) = lay.caret_x(st.cursor); + // A one-line box scrolls to keep the caret in sight. + if single_line { + let view = inner_w; + if cx - st.scroll_x > view - 2.0 { + st.scroll_x = cx - view + 2.0; + } else if cx - st.scroll_x < 0.0 { + st.scroll_x = cx; + } + st.scroll_x = st.scroll_x.clamp(0.0, (lay.width - view + 4.0).max(0.0)); + } + let scroll = if single_line { st.scroll_x } else { 0.0 }; + let clip = p.with_clip_rect(rect.shrink(2.0)); + let at = |x: f32, y: f32| origin(x - scroll) + vec2(0.0, y); + let (a, b) = st.range(); + let sel_fill = if focused { t.accent.gamma_multiply(0.45) } else { t.accent.gamma_multiply(0.25) }; + for l in &lay.lines { + for k in &l.cells { + if k.idx >= a && k.idx < b { + clip.rect_filled(Rect::from_min_max(at(k.x, l.top), at(k.x + k.w, l.top + l.height)), 0.0, sel_fill); + } + } + // A selected paragraph break: a sliver at the line's end. + if l.end >= a && l.end < b && chars.get(l.end) == Some(&'\n') { + let ex = if l.rtl { 0.0 } else { l.cells.iter().map(|k| k.x + k.w).fold(0.0, f32::max) }; + let x0 = if l.rtl { ex - 6.0 } else { ex }; + clip.rect_filled(Rect::from_min_max(at(x0, l.top), at(x0 + 6.0, l.top + l.height)), 0.0, sel_fill); + } + for k in &l.cells { + let Some(c) = chars.get(k.idx).copied() else { continue }; + let lk = look(k.idx); + let c = if k.rtl { cadcraft_fonts::bidi::mirror(c) } else { c }; + editor_glyphs::paint(&clip, &lk.font, lk.italic, lk.bold, c, at(k.x, l.baseline), lk.size, lk.color); + if lk.underline { + let y = l.baseline + lk.size * 0.15; + clip.line_segment([at(k.x, y), at(k.x + k.w, y)], Stroke::new(1.0, lk.color)); + } + } + } + let caret_bottom = { + let l = lay.lines.get(cl); + let (top, hgt) = l.map_or((0.0, row_h), |l| (l.top, l.height)); + at(cx, top + hgt) + }; + if focused && !st.preedit.is_empty() { + // The composition, underlined, after the caret. + let l = lay.lines.get(cl); + let (top, hgt) = l.map_or((0.0, row_h), |l| (l.top, l.height)); + let size = look(st.cursor.saturating_sub(1)).size.max(8.0); + let g = ui.painter().layout_no_wrap(st.preedit.clone(), egui::FontId::proportional(size), t.text); + let w = g.size().x; + let y = top + (hgt - g.size().y) / 2.0; + clip.rect_filled(Rect::from_min_size(at(cx, top), vec2(w, hgt)), 0.0, t.panel); + clip.galley(at(cx, y), g, t.text); + clip.line_segment([at(cx, top + hgt - 2.0), at(cx + w, top + hgt - 2.0)], Stroke::new(1.0, t.accent)); + } + if focused { + let l = lay.lines.get(cl); + let (top, hgt) = l.map_or((0.0, row_h), |l| (l.top, l.height)); + let blink = ui.input(|i| i.time) % 1.0 < 0.6; + if blink { + clip.line_segment([at(cx, top + 2.0), at(cx, top + hgt - 2.0)], Stroke::new(1.5, t.text)); + } + ui.ctx().request_repaint_after(std::time::Duration::from_millis(300)); + let caret_rect = Rect::from_min_max(at(cx, top), at(cx + 1.0, top + hgt)); + // The IME context is this editor's; a new generation each time it takes the keyboard. + let generation_id = id.with("ime_generation"); + let mut generation: u64 = ui.data(|d| d.get_temp(generation_id)).unwrap_or(0); + if response.gained_focus() { + generation = generation.wrapping_add(1); + ui.data_mut(|d| d.insert_temp(generation_id, generation)); + } + ui.ctx().output_mut(|o| o.ime = Some(egui::output::IMEOutput::new(id, generation, egui::IMEPurpose::Normal, rect, caret_rect))); + } + caret_bottom +} + +#[cfg(test)] +mod tests { + use super::*; + + fn look(_: usize) -> Look { + Look { + font: EditorFont { width_factor: 1.0, ..Default::default() }, + italic: false, + bold: false, + underline: false, + size: 20.0, + color: Color32::WHITE, + } + } + + fn lay(s: &str) -> (Vec, Layout) { + let c: Vec = s.chars().collect(); + let l = layout(&c, &look, None, 20.0); + (c, l) + } + + #[test] + fn mixed_scripts_show_in_display_order() { + // Hebrew paragraph with an English word: the English word sits at the left, in its own + // order, the Hebrew reads from the right. + let (_, l) = lay("שלום abc"); + let line = &l.lines[0]; + assert!(line.rtl); + let order: Vec = line.cells.iter().map(|k| k.idx).collect(); + assert_eq!(order, vec![5, 6, 7, 4, 3, 2, 1, 0]); + // English paragraph with a Hebrew word: the Hebrew word reversed in place. + let (_, l) = lay("ab שלום cd"); + let order: Vec = l.lines[0].cells.iter().map(|k| k.idx).collect(); + assert_eq!(order, vec![0, 1, 2, 6, 5, 4, 3, 7, 8, 9]); + } + + #[test] + fn arrows_move_visually_and_reach_every_place() { + let (c, l) = lay("ab שלום cd"); + // From the start, Right walks every caret place once, left to right on screen. + let mut at = 0; + let mut seen = vec![at]; + let mut xs = vec![l.caret_x(at).1]; + for _ in 0..c.len() + 2 { + let n = l.step(at, 1.0); + if n == at { + break; + } + at = n; + seen.push(at); + xs.push(l.caret_x(at).1); + } + assert!(xs.windows(2).all(|w| w[1] > w[0]), "{xs:?}"); + assert!(seen.len() >= c.len() - 1, "{seen:?}"); + // In a right-to-left line, Right from the logical start goes toward the end of the text + // on screen (left to right), i.e. back in reading order. + let (_, l) = lay("שלום"); + let x0 = l.caret_x(0).1; + assert!(x0 > l.caret_x(4).1, "the start of Hebrew text is at the right"); + assert_eq!(l.step(0, -1.0), 1, "Left from the start of Hebrew reads on"); + } + + #[test] + fn typing_replaces_the_selection_and_undo_restores() { + let mut chars: Vec = "hello".chars().collect(); + let mut st = EditState { cursor: 1, anchor: 4, ..Default::default() }; + assert!(replace(&mut chars, &mut st, "XY", 100)); + assert_eq!(chars.iter().collect::(), "hXYo"); + assert_eq!((st.cursor, st.anchor), (3, 3)); + let mut st = EditState::at(4); + assert!(replace(&mut chars, &mut st, "123456", 6), "capped at the limit"); + assert_eq!(chars.len(), 6); + assert_eq!(word_left(&"one two".chars().collect::>(), 7), 4); + } + + /// Left (and Right) walk through a soft-wrapped paragraph, across the wrap, end to end. + #[test] + fn arrows_cross_a_soft_wrap_both_ways() { + let c: Vec = "aaaa bbbb cccc dddd".chars().collect(); + let one = editor_glyphs::advance(&look(0).font, false, 'a', 20.0); + let l = layout(&c, &look, Some(one * 6.5), 20.0); + assert!(l.lines.len() >= 2, "wrapped"); + assert!(l.lines.windows(2).any(|w| w[0].end == w[1].start), "a soft wrap shares its caret place"); + let walk = |from: usize, dir: f32| { + let mut at = from; + for _ in 0..c.len() * 2 { + let n = l.step(at, dir); + if n == at { + break; + } + at = n; + } + at + }; + assert_eq!(walk(c.len(), -1.0), 0, "Left from the end reaches the start"); + assert_eq!(walk(0, 1.0), c.len(), "Right from the start reaches the end"); + } + + /// A paste of several lines into a one-line box keeps a space where each break was + /// (`\n` and Windows' `\r\n`), instead of running the lines together (#2034 review). + #[test] + fn a_pasted_line_break_is_a_space_in_a_one_line_box() { + let ctx = egui::Context::default(); + for (pasted, want_line, want_box) in [("one\ntwo", "one two", "one\ntwo"), ("one\r\ntwo\tthree", "one twothree", "one\ntwothree")] { + for single in [true, false] { + let mut text = String::new(); + let mut st = EditState::default(); + let id = egui::Id::unique(("paste_test", single, pasted)); + let raw = |events| egui::RawInput { events, ..Default::default() }; + let run = |text: &mut String, st: &mut EditState, events| { + let mut out = ctx.run_ui(raw(events), |ui| { + ui.memory_mut(|m| m.request_focus(id)); + show(ui, id, text, st, single, 300.0, 1, &look, 20.0, 1000); + }); + out.textures_delta.clear(); + }; + run(&mut text, &mut st, Vec::new()); + run(&mut text, &mut st, vec![Event::Paste(pasted.into())]); + assert_eq!(text, if single { want_line } else { want_box }, "single line: {single}"); + } + } + } + + #[test] + fn wrapping_breaks_at_spaces() { + let c: Vec = "aaaa bbbb cccc".chars().collect(); + let one = editor_glyphs::advance(&look(0).font, false, 'a', 20.0); + let l = layout(&c, &look, Some(one * 6.5), 20.0); + assert!(l.lines.len() >= 2); + assert_eq!(l.lines[0].start, 0); + assert_eq!(c[l.lines[1].start], 'b'); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 08b8b1c3c5..31f9bd49fa 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -609,6 +609,12 @@ fn handle_double_click(app: &mut CadApp, ctx: DoubleClickContext<'_>) -> Option< let pp = xf_paper.to_world(hp); let in_rect = |v: &cadcraft_doc::Viewport| (pp.x - v.center.x).abs() <= v.width / 2.0 && (pp.y - v.center.y).abs() <= v.height / 2.0; let in_active = active_viewport.as_ref().is_some_and(|v| active_clip.as_ref().map_or(in_rect(v), |c| c.contains(pp))); + // On the sheet itself (no viewport active), a block, text or dimension drawn on the sheet + // is edited as in model space; elsewhere the click goes into a viewport. + let on_sheet = app.session.state().is_ok_and(|st| st.mspace.is_none()); + if on_sheet && app.session.running.is_none() && edit_text_at(app, pp) { + return None; + } if !in_active { app.canvas.hot_grips.clear(); app.session.pending_window = None; @@ -622,7 +628,8 @@ fn handle_double_click(app: &mut CadApp, ctx: DoubleClickContext<'_>) -> Option< return None; } } - // Double-click text to edit it, as in AutoCAD: TEXTEDIT with that object already picked. + // Double-click text, a dimension, a multileader or a table cell to edit it in place, as in + // AutoCAD: TEXTEDIT (TABLEDIT) with that object already picked. if inside && double && app.session.running.is_none() diff --git a/crates/ui-egui/src/canvas/pick.rs b/crates/ui-egui/src/canvas/pick.rs index b751117163..ee93f710aa 100644 --- a/crates/ui-egui/src/canvas/pick.rs +++ b/crates/ui-egui/src/canvas/pick.rs @@ -26,21 +26,45 @@ pub(super) fn wheel_zoom_points(events: &[egui::Event], opts: &egui::InputOption } /// The model space tiles on screen (none without tiling): each tile's rectangle in `full`. -/// Start TEXTEDIT on the text, mtext, attribute definition or multileader text at `p` (the objects -/// its shortcut menu offers Edit Text for, and multileaders, #1081); false when there is none. +/// Start TEXTEDIT on the text, mtext or attribute definition at `p` (the objects its shortcut menu +/// offers Edit Text for); false when there is none. pub(super) fn edit_text_at(app: &mut CadApp, p: Vec2) -> bool { use cadcraft_engine::doc::EntityKind; - let is_text = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { + // A block reference: its attributes (Enhanced Attribute Editor), or the Block Editor for a + // block without them, as in AutoCAD. External references are left alone. + let block = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { + let d = app.session.doc().ok()?; + let EntityKind::Insert(i) = &d.entity(h)?.kind else { return None }; + let xref = d.block(&i.block).is_some_and(|b| b.xref_path.is_some()); + (!xref).then(|| (h, i.attribs.iter().any(|a| !a.constant))) + }); + if let Some((h, attributes)) = block { + if attributes { + app.start("attedit"); + if let Err(e) = app.session.input(Input::Pick(vec![h])) { + app.session.echo(e.to_string()); + } + } else if let Err(e) = app.run("bedit", serde_json::json!({ "handle": h.hex() })) { + app.session.echo(e); + } + return true; + } + let picked = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { app.session.doc().ok()?.entity(h).map(|e| match &e.kind { - EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) => true, - EntityKind::MLeader(m) => m.text.is_some(), - _ => false, + EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_) => Some("textedit.object"), + EntityKind::MLeader(m) if m.text.is_some() => Some("textedit.object"), + EntityKind::Table(t) if t.cell_at_point(p).is_some() => Some("tabledit.cell"), + _ => None, }) }); - if is_text != Some(true) { - return false; - } - app.start("textedit"); + // Inside a table cell, away from its lines: the cell. + let command = picked.flatten().or_else(|| { + let d = app.session.doc().ok()?; + let space = d.space(&app.session.space())?; + space.iter().any(|e| matches!(&e.kind, EntityKind::Table(t) if t.cell_at_point(p).is_some())).then_some("tabledit.cell") + }); + let Some(command) = command else { return false }; + app.start(command); if let Err(e) = app.session.input(Input::Point(p)) { app.session.echo(e.to_string()); } @@ -64,6 +88,37 @@ mod hatch_pick_tests { use crate::{CadApp, Services}; + /// An external reference whose insert names its block in other letter case is still left + /// alone (no Block Editor), as block names are matched everywhere else (#2326 review). + #[test] + fn an_xref_named_in_other_case_is_left_alone() { + use cadcraft_engine::doc::{Block, Common, EntityKind, Insert, Space}; + use cadcraft_geom::Vec3; + let mut app = CadApp::new(Session::new(), Services::default()); + let d = app.session.doc_mut().unwrap(); + let mut b = Block::new("SITEPLAN"); + b.xref_path = Some("siteplan.dxf".into()); + let line = cadcraft_engine::doc::Line { a: Vec3::new(-5.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) }; + b.entities.push(cadcraft_engine::doc::Entity::new(cadcraft_engine::doc::Handle(0x7001), EntityKind::Line(line))); + d.blocks.insert("SITEPLAN".into(), std::sync::Arc::new(b)); + let ins = Insert { + clip: Default::default(), + block: "siteplan".into(), + insert: Vec3::ZERO, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + assert!(cadcraft_engine::cmd::curves::pick_at(&app.session, Vec2::ZERO).is_some(), "the reference is picked"); + assert!(!super::edit_text_at(&mut app, Vec2::ZERO), "nothing to edit: no Block Editor attempt for an xref"); + assert!(app.session.state().ok().and_then(|st| st.block_editor()).is_none()); + } + #[test] fn hatch_at_finds_a_hatch_under_the_cursor_only() { let mut app = CadApp::new(Session::new(), Services::default()); @@ -75,6 +130,51 @@ mod hatch_pick_tests { assert_eq!(super::hatch_at(&app, Vec2::new(60.0, 60.0), 10.0), None); } + #[test] + fn double_clicking_text_dimensions_and_table_cells_opens_the_in_place_editor() { + let mut app = CadApp::new(Session::new(), Services::default()); + // The text sits away from the drawing area's top-left corner (the viewport label). + app.session.execute("line", &json!({ "points": [[-10, 20], [-9, 20]] })).unwrap(); + app.session.execute("mtext", &json!({ "at": [0, 10], "text": "hello world", "height": 1.0 })).unwrap(); + app.session.execute("table", &json!({ "at": [20, 10], "rows": 2, "cols": 2, "colWidth": 6, "rowHeight": 2 })).unwrap(); + let _ = app.session.zoom_extents(); + let ctx = egui::Context::default(); + let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))); + let mut time = 0.0; + let mut frame = |app: &mut CadApp, events: Vec| { + time += 0.1; + app.logic(&ctx); + let input = egui::RawInput { screen_rect: screen, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.ui(ui)); + out.textures_delta.clear(); + }; + let mut double_click = |app: &mut CadApp, world: Vec2| { + // Far enough from any earlier click not to count as its second or third. + for _ in 0..10 { + frame(app, Vec::new()); + } + let at = app.canvas.xf.unwrap().to_screen(world); + let button = |pressed| egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::default(), + }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true), button(false)]); + frame(app, vec![button(true), button(false)]); + frame(app, Vec::new()); + }; + double_click(&mut app, Vec2::new(1.0, 9.6)); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("textedit.object")); + assert!(matches!(app.session.text_editor().map(|e| e.kind), Some(cadcraft_engine::EditorKind::MText))); + app.session.cancel(); + app.session.set_selection(Vec::new()); + double_click(&mut app, Vec2::new(23.0, 7.0)); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("tabledit.cell")); + assert!(matches!(app.session.text_editor().map(|e| e.kind), Some(cadcraft_engine::EditorKind::TableCell { .. }))); + } + #[test] fn double_clicking_a_hatch_opens_the_hatch_edit_dialog() { let mut app = CadApp::new(Session::new(), Services::default()); diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 0e9124400f..d8f2035bed 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -823,7 +823,18 @@ mod tests { } #[test] + /// The command line's own IME, at a text prompt it collects (here without the in-place + /// editor, which takes the keyboard when it is shown and has its own composition). fn ime_preedit_is_shown_and_its_commit_is_inserted_once() { + fn keys(app: &mut CadApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + keyboard(app, ui.ctx()); + }); + out.textures_delta.clear(); + out + } use cadcraft_engine::geom::Vec2; let mut app = CadApp::new(Session::new(), crate::Services::default()); app.run("text", serde_json::json!({"at": [0, 0], "text": "HELLO", "height": 2.5})).unwrap(); @@ -831,26 +842,26 @@ mod tests { app.session.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap(); assert_eq!(app.session.current_prompt().map(|p| p.message.clone()).as_deref(), Some("Enter new text")); let ctx = egui::Context::default(); - let out = frame(&mut app, &ctx, Vec::new()); + let out = keys(&mut app, &ctx, Vec::new()); // The IME is enabled for the command line while it is collecting text. assert!(out.platform_output.ime.is_some()); // Composition is shown at the command line but is not part of the text being edited. - frame(&mut app, &ctx, vec![Event::Ime(egui::ImeEvent::Preedit { text: "zhong".into(), active_range_chars: None })]); + keys(&mut app, &ctx, vec![Event::Ime(egui::ImeEvent::Preedit { text: "zhong".into(), active_range_chars: None })]); assert_eq!(app.cmd.preedit, "zhong"); assert!(app.cmd.buffer.is_empty()); // The committed text replaces the pre-edit, exactly once. - frame(&mut app, &ctx, vec![Event::Ime(egui::ImeEvent::Commit("中文".into()))]); + keys(&mut app, &ctx, vec![Event::Ime(egui::ImeEvent::Commit("中文".into()))]); assert!(app.cmd.preedit.is_empty()); assert_eq!(app.cmd.buffer, "中文"); let enter = |pressed| Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; - frame(&mut app, &ctx, vec![enter(true), enter(false)]); + keys(&mut app, &ctx, vec![enter(true), enter(false)]); let text = app.session.doc().unwrap().model.iter().next().map(|e| match &e.kind { cadcraft_engine::doc::EntityKind::Text(t) => t.value.clone(), _ => String::new(), }); assert_eq!(text.as_deref(), Some("中文")); // Back to selecting objects: the next frame lets the IME go, so it can't swallow ASCII typing. - let out = frame(&mut app, &ctx, Vec::new()); + let out = keys(&mut app, &ctx, Vec::new()); assert!(out.platform_output.ime.is_none()); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 63684651b6..db406960a0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -28,6 +28,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), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), @@ -365,6 +366,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/editor_glyphs.rs b/crates/ui-egui/src/editor_glyphs.rs new file mode 100644 index 0000000000..25d018d8bf --- /dev/null +++ b/crates/ui-egui/src/editor_glyphs.rs @@ -0,0 +1,189 @@ +//! The text editors show text in the drawing's own fonts: each character is drawn with the +//! drawing's shaping (SHX strokes, TrueType outlines, the built-in stroke font and its fallbacks) +//! over an invisible egui text box whose advances are set to the font's, so the caret, the +//! selection and the glyphs line up. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock, PoisonError}; + +use cadcraft_fonts::{Shaped, TextFont}; +use egui::{Color32, Pos2, Stroke}; + +/// Most characters kept shaped. +const MAX_CACHED: usize = 4096; +/// The egui font's cap height as a share of its size: drawing fonts are scaled so their cap +/// height (the text height) matches it. +pub const CAP: f32 = 0.7; +/// Slant of italic text (radians), as the style's oblique angle adds to. +const ITALIC: f64 = 0.2618; + +/// The font a run of the editor is set in. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct EditorFont { + /// Style font file or inline family (`romans.shx`, `arial.ttf`, `Arial`). + pub font: String, + pub big_font: String, + pub width_factor: f64, + /// Radians. + pub oblique: f64, +} + +impl EditorFont { + fn wf(&self) -> f64 { + if self.width_factor.is_finite() && self.width_factor > 0.01 { self.width_factor.min(100.0) } else { 1.0 } + } +} + +type Key = (String, String, u64, u64, char); + +struct Glyph { + shaped: Shaped, + /// Advance at cap height 1. + advance: f64, +} + +fn cache() -> &'static Mutex>> { + static C: OnceLock>>> = OnceLock::new(); + C.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn fonts() -> &'static Mutex> { + static F: OnceLock>> = OnceLock::new(); + F.get_or_init(|| Mutex::new(HashMap::new())) +} + +/// Forget what was worked out with fonts that changed since: the font folders were edited or +/// searched again ([`cadcraft_fonts::ttf::generation`], [`cadcraft_fonts::shx::generation`]), so a +/// font that was missing may be there. +fn follow_font_changes() { + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = cadcraft_fonts::ttf::generation().wrapping_add(cadcraft_fonts::shx::generation() << 32); + if SEEN.swap(now, std::sync::atomic::Ordering::Relaxed) != now { + clear(); + } +} + +fn resolve(font: &str, big: &str) -> TextFont { + follow_font_changes(); + let k = (font.to_string(), big.to_string()); + let mut f = fonts().lock().unwrap_or_else(PoisonError::into_inner); + if let Some(t) = f.get(&k) { + return t.clone(); + } + let t = TextFont::resolve_style(font, big, false); + if f.len() > 64 { + f.clear(); + } + f.insert(k, t.clone()); + t +} + +/// Forget resolved fonts (the user's font folders changed). +pub fn clear() { + fonts().lock().unwrap_or_else(PoisonError::into_inner).clear(); + cache().lock().unwrap_or_else(PoisonError::into_inner).clear(); +} + +fn glyph(f: &EditorFont, italic: bool, c: char) -> std::sync::Arc { + follow_font_changes(); + let oblique = f.oblique + if italic { ITALIC } else { 0.0 }; + let key = (f.font.clone(), f.big_font.clone(), f.wf().to_bits(), oblique.to_bits(), c); + if let Some(g) = cache().lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + return g.clone(); + } + let font = resolve(&f.font, &f.big_font); + let s = c.to_string(); + let shaped = if c.is_whitespace() { Shaped::default() } else { cadcraft_fonts::shape_line(&font, &s, 1.0, f.wf(), oblique) }; + // A line's width leaves out the gap after its last character: the advance is what a second + // copy of the character adds. + let two: String = [c, c].iter().collect(); + let mut advance = cadcraft_fonts::text_width(&font, &two, 1.0, f.wf()) - cadcraft_fonts::text_width(&font, &s, 1.0, f.wf()); + if !advance.is_finite() || advance <= 0.0 { + advance = if c.is_whitespace() { cadcraft_fonts::space_width(&font, 1.0, f.wf()) } else { shaped.width }; + } + let g = std::sync::Arc::new(Glyph { shaped, advance: if advance.is_finite() { advance.clamp(0.0, 20.0) } else { 0.6 } }); + let mut c2 = cache().lock().unwrap_or_else(PoisonError::into_inner); + if c2.len() >= MAX_CACHED { + c2.clear(); + } + c2.insert(key, g.clone()); + g +} + +/// Advance of `c` in `f`, in points, at egui font size `size`. +pub fn advance(f: &EditorFont, italic: bool, c: char, size: f32) -> f32 { + (glyph(f, italic, c).advance as f32) * size * CAP +} + +/// Draw `c` in `f` with its baseline-left at `at` (screen), at egui font size `size`. +#[allow(clippy::too_many_arguments)] +pub fn paint(painter: &egui::Painter, f: &EditorFont, italic: bool, bold: bool, c: char, at: Pos2, size: f32, color: Color32) { + if c.is_whitespace() || c.is_control() { + return; + } + let g = glyph(f, italic, c); + let k = size * CAP; + let map = |p: cadcraft_geom::Vec2| Pos2::new(at.x + p.x as f32 * k, at.y - p.y as f32 * k); + let w = (k / if bold { 7.0 } else { 12.0 }).clamp(1.0, 4.0); + for s in &g.shaped.strokes { + let pts: Vec = s.iter().map(|p| map(*p)).collect(); + if pts.len() == 1 + && let Some(p) = pts.first() + { + painter.circle_filled(*p, w / 2.0, color); + } else if pts.len() >= 2 { + painter.add(egui::Shape::line(pts, Stroke::new(w, color))); + } + } + for contours in &g.shaped.glyphs { + let tris = cadcraft_render::triangulate_glyph(contours); + if tris.len() < 3 { + continue; + } + let mut mesh = egui::Mesh::default(); + for p in &tris { + mesh.colored_vertex(map(*p), color); + } + mesh.indices = (0..u32::try_from(mesh.vertices.len()).unwrap_or(0)).collect(); + painter.add(egui::Shape::mesh(mesh)); + if bold { + for ct in contours { + let mut pts: Vec = ct.iter().map(|p| map(*p)).collect(); + if let Some(first) = pts.first().copied() { + pts.push(first); + } + painter.add(egui::Shape::line(pts, Stroke::new((k / 30.0).clamp(0.5, 2.0), color))); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_stroke_font_gives_advances_and_strokes() { + let f = EditorFont { font: String::new(), big_font: String::new(), width_factor: 1.0, oblique: 0.0 }; + let a = advance(&f, false, 'A', 20.0); + let i = advance(&f, false, 'i', 20.0); + assert!(a > 5.0 && a < 30.0, "{a}"); + assert!(i < a, "an i is narrower than an A"); + let wide = EditorFont { width_factor: 2.0, ..f.clone() }; + assert!(advance(&wide, false, 'A', 20.0) > a * 1.5); + assert!(advance(&f, false, ' ', 20.0) > 0.0); + assert!(!glyph(&f, false, 'A').shaped.strokes.is_empty()); + } + + /// A font missing when the editor first asked for it is looked up again once the fonts are + /// searched again (a font folder added), without restarting (#2034 review). + #[test] + fn a_rescan_forgets_resolved_fonts() { + let key = ("cadcraft_editor_cache_test.shx".to_string(), String::new()); + let _ = resolve(&key.0, ""); + assert!(fonts().lock().unwrap_or_else(PoisonError::into_inner).contains_key(&key)); + cadcraft_fonts::ttf::rescan(); + let _ = resolve("", ""); + assert!(!fonts().lock().unwrap_or_else(PoisonError::into_inner).contains_key(&key), "forgotten after the rescan"); + } +} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 87252d5337..5cda15655f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1062,3 +1062,5 @@ # ArtCraft feature naming Additional Tools Дополнительные инструменты + Type to search Введите для поиска + No font matches Нет подходящих шрифтов diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 2d0a6faa51..88c754f5c6 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1416,6 +1416,10 @@ Save Layout as Template 将布局另存为样板 Set Dynamic Property 设置动态特性 Units 单位 + Text Formulas 文字公式 + Update Fields 更新字段 + Edit Table Cells 编辑表格单元格 + Edit Text 编辑文字 Find All 查找全部 Find what: 查找内容: Match case 区分大小写 @@ -1515,8 +1519,9 @@ menu View 视图 Xref 外部参照 Xref Clip Frame 外部参照剪裁边框 Ctrl+Enter to apply Ctrl+Enter 应用 - Edit Text 编辑文字 The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。 # ArtCraft feature naming Additional Tools 其他工具 + Type to search 输入以搜索 + No font matches 没有匹配的字体 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ceb5945d84..ec400a94ae 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -21,6 +21,7 @@ pub mod aliasdlg; pub mod animation; pub mod autosave; pub mod bedit; +pub mod bidi_edit; pub mod canvas; pub mod capture; pub mod chrome; @@ -32,6 +33,7 @@ pub mod control; pub mod credits; pub mod dialogs; pub mod docking; +pub mod editor_glyphs; pub mod fault; // The Find and Replace window behind the FIND command. pub mod finddlg; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d8e98a42cf..9f565390f1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -130,6 +130,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), @@ -537,6 +538,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 941940e1bf..e7bc838321 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -1,21 +1,24 @@ -//! The in-place MTEXT editor: while MTEXT asks for its text, a text box opens on the canvas at +//! The in-place text editor: while MTEXT asks for its text, a text box opens on the canvas at //! the text's location and width with a formatting toolbar (font, height, bold, italic, //! underline, overline, colour, alignment, lists, tabs) and a ruler for the paragraph's indents //! and tab stops. The text and its formats live in the engine's -//! [`cadcraft_engine::mtext_edit::Formatted`]; this file only draws and forwards edits. TEXTEDIT -//! (and so a double-click) on an existing MTEXT opens it here with its contents (#842). - -use std::sync::Arc; +//! [`cadcraft_engine::mtext_edit::Formatted`]; this file only draws and forwards edits. +//! +//! The same editor edits existing text when a command describes it +//! ([`cadcraft_engine::Session::text_editor`]): double-click multiline text or a multileader +//! (toolbar and ruler), one line of text (a plain line, Enter finishes), a dimension (`<>` is +//! the measured value) or a table cell (Tab and Shift+Tab move to the next and previous cell, +//! Alt+↑ and Alt+↓ to the cell above and below). +use cadcraft_engine::EditorKind; use cadcraft_engine::mtext_edit::{CharFmt, Flag, Formatted, ListStyle, MTextColor, ParaAlign, TabKind}; -use egui::text::{CCursor, CCursorRange, LayoutJob}; -use egui::{Align2, Color32, FontId, Rect, RichText, Sense, Shape, Stroke, TextFormat, pos2, vec2}; +use egui::{Align2, Color32, FontId, Rect, RichText, Sense, Shape, Stroke, pos2, vec2}; use crate::CadApp; use crate::theme::Tokens; /// Smallest and largest size of the text in the box, in points: the box stays readable at any zoom. -const MIN_PX: f32 = 13.0; +const MIN_PX: f32 = 18.0; const MAX_PX: f32 = 36.0; /// Families the font list offers besides the one set in the text. const FAMILIES: [&str; 6] = ["Arial", "Times New Roman", "Courier New", "Verdana", "Georgia", "Calibri"]; @@ -73,12 +76,26 @@ struct State { sel: (usize, usize), /// A caret position to set on the text box in the next frame (after a toolbar insertion). caret: Option, - /// The text box has had keyboard focus: it takes it once when the editor opens, so typing - /// goes into the text, not to the command line. - focused: bool, - /// The MTEXT the state was made for (its insertion point and contents when it opened): a - /// state kept for another one is not reused, so one MTEXT's text never goes to the next. - target: Option<(cadcraft_engine::geom::Vec3, String)>, + /// The object being edited ([`cadcraft_engine::TextEditor::key`]): another one reloads. + key: String, + /// Give the text box the keyboard in the next frame. + focus: bool, + /// The text style's font: the text box shows the text in it. + font: crate::editor_glyphs::EditorFont, + /// The text box's caret and selection. + edit: crate::bidi_edit::EditState, + /// Formula completion: the highlighted function, and the text it was closed for (Escape). + fx_index: usize, + fx_closed: Option, + /// Where the completion list goes (the caret's bottom, last frame). + fx_at: egui::Pos2, + /// Undo and redo steps of the whole editor (text and formatting), with the selection then. + undo: Vec<(Formatted, usize, usize)>, + redo: Vec<(Formatted, usize, usize)>, + /// When the last undo step was recorded (typing within a second makes one step). + undo_at: f64, + /// What is typed in the font list to narrow it. + font_filter: String, } fn state_id() -> egui::Id { @@ -98,54 +115,161 @@ fn color32(c: MTextColor) -> Color32 { Color32::from_rgb(rgb.0, rgb.1, rgb.2) } -/// Show the editor while MTEXT, or TEXTEDIT on an MTEXT, collects its text; clears its state -/// when neither is running. +/// Show the editor while MTEXT collects its text; clears its state when it isn't running. pub fn show(app: &mut CadApp, ctx: &egui::Context) { - let mtext = app.session.editing_mtext(); + let editor = app.session.text_editor(); let asking = app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point); - let (Some(mt), true) = (mtext, asking) else { + let (Some(editor), true) = (editor, asking) else { ctx.data_mut(|d| d.remove::(state_id())); return; }; + let mt = &editor.mtext; + let kind = editor.kind.clone(); let t = Tokens::get(); let (rect, scale) = app.canvas.xf.map_or((ctx.content_rect(), 20.0), |x| (x.rect, x.scale.max(1e-6))); - let target = (mt.insert, mt.contents.clone()); - let kept = ctx.data_mut(|d| d.get_temp::(state_id())).filter(|st| st.target.as_ref() == Some(&target)); - let mut st = kept.unwrap_or_else(|| { - // An existing MTEXT (TEXTEDIT) starts with its contents and their formats. - let mut fmt = if mt.contents.is_empty() { Formatted::default() } else { Formatted::from_contents_with_height(&mt.contents, Some(mt.height)) }; - if let Some(f) = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).map(|s| s.font.clone())) { + let mut st = ctx.data_mut(|d| d.get_temp::(state_id())).filter(|st| st.key == editor.key).unwrap_or_else(|| { + let mut fmt = match &kind { + EditorKind::NewMText => Formatted::default(), + // One line of plain text: backslashes and braces are text, not codes. + EditorKind::Line => { + let mut f = Formatted::default(); + f.set_text(&mt.contents, &CharFmt::default()); + f + } + _ => Formatted::from_contents(&mt.contents), + }; + let style = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).cloned()); + if let Some(f) = style.as_ref().map(|s| s.font.clone()) { // A family name, not a font file (`txt.shx`, `arial.ttf`). if !f.is_empty() && !f.contains('.') { fmt.base_font = f; } } - // An existing text opens with the caret at its end. - let caret = (!fmt.is_empty()).then(|| fmt.len()); - State { fmt, typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret, focused: false, target: Some(target.clone()) } + let font = style + .map(|s| crate::editor_glyphs::EditorFont { font: s.font, big_font: s.big_font, width_factor: s.width_factor, oblique: s.oblique }) + .unwrap_or_else(|| crate::editor_glyphs::EditorFont { width_factor: 1.0, ..Default::default() }); + let end = fmt.len(); + // Existing text opens selected as a whole: typing replaces it, an arrow key keeps it. + let existing = !matches!(kind, EditorKind::NewMText) && end > 0; + State { + fmt, + typing: CharFmt::default(), + typing_at: end, + top: 70.0, + sel: if existing { (end, 0) } else { (end, end) }, + caret: (!existing).then_some(end), + key: editor.key.clone(), + focus: true, + font, + edit: if existing { crate::bidi_edit::EditState::all(end) } else { crate::bidi_edit::EditState::at(end) }, + fx_index: 0, + fx_closed: None, + fx_at: pos2(0.0, 0.0), + undo: Vec::new(), + redo: Vec::new(), + undo_at: 0.0, + font_filter: String::new(), + } + }); + let line = kind == EditorKind::Line; + let cell = matches!(kind, EditorKind::TableCell { .. }); + let formatting = !line; + let ruler_shown = matches!(kind, EditorKind::NewMText | EditorKind::MText); + // Keys the editor takes before the text box: Tab between table cells, Enter ends one line. + // While a formula's function list is open, Tab puts the function in (below). + let mut done = Done::No; + let completing = completion(&st).is_some(); + if cell { + ctx.input_mut(|i| { + if i.consume_key(egui::Modifiers::SHIFT, egui::Key::Tab) { + done = Done::Move("Previous"); + } else if !completing && i.consume_key(egui::Modifiers::NONE, egui::Key::Tab) { + done = Done::Move("Next"); + } else if i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowUp) { + done = Done::Move("Up"); + } else if i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowDown) { + done = Done::Move("Down"); + } + }); + } + // Undo and redo (Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z, ⌘ on a Mac), taken before the text box. + let before = (st.fmt.clone(), st.edit.cursor, st.edit.anchor); + let mut undo_redo: Option = None; + ctx.input_mut(|i| { + if i.consume_key(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::Z) || i.consume_key(egui::Modifiers::COMMAND, egui::Key::Y) { + undo_redo = Some(false); + } else if i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z) { + undo_redo = Some(true); + } }); + // Formula completion: the arrows choose a function, Tab or Enter puts it in, Escape closes + // the list (taken before the text box and before Enter finishes one line of text). + let fx = completion(&st); + if let Some((_, list)) = &fx { + let n = list.len().max(1); + ctx.input_mut(|i| { + if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) { + st.fx_index = (st.fx_index + 1) % n; + } + if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) { + st.fx_index = (st.fx_index + n - 1) % n; + } + }); + let pick = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Tab) || i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + if pick { + let k = st.fx_index; + accept_completion(&mut st, k); + } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + st.fx_closed = Some(st.fmt.text().to_string()); + } + } + if line && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + done = Done::Ok; + } + // Ctrl+Enter (⌘↩) finishes, taken before the text box can make it a new line. + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Enter)) { + done = Done::Ok; + } let base_h = if mt.height > 0.0 { mt.height } else { 0.2 }; let px = ((base_h * scale) as f32).clamp(MIN_PX, MAX_PX); - let width = if mt.width > 0.0 { ((mt.width * scale) as f32).clamp(280.0, rect.width().max(280.0) * 0.9) } else { 380.0 }; + let width = editor_width(mt.width * scale, rect.width()); // The box's top-left corner on screen (rotation is ignored while editing). let code = usize::from(mt.attach.clamp(1, 9) - 1); let (col, row) = ((code % 3) as f64, (code / 3) as f64); let ww = f64::from(width) / scale; - let corner = cadcraft_geom::Vec2::new(mt.insert.x - col * ww / 2.0, mt.insert.y + row * base_h * 2.0); + // One line of text: the editor's line sits on the text's own line (its top a little above the + // cap height), so what is typed shows where the text goes. + let rise = if line { 0.75 } else { 2.0 }; + let corner = cadcraft_geom::Vec2::new(mt.insert.x - col * ww / 2.0, mt.insert.y + row * base_h * rise); let at = app.canvas.xf.map_or(rect.center(), |x| x.to_screen(corner)); let max_x = (rect.right() - width - 8.0).max(rect.left()); let pos = pos2(at.x.clamp(rect.left(), max_x), at.y.clamp(rect.top() + st.top, (rect.bottom() - 120.0).max(rect.top() + st.top))); - let mut done = Done::No; let top_start = pos.y - st.top; egui::Area::new(egui::Id::unique("mtext_editor_area")).order(egui::Order::Foreground).fixed_pos(pos2(pos.x, top_start)).show(ctx, |ui| { egui::Frame::NONE.fill(t.panel).stroke(Stroke::new(1.0, t.accent)).inner_margin(egui::Margin::same(0)).show(ui, |ui| { ui.set_width(width); let y0 = ui.cursor().top(); - toolbar(ui, &mut st, base_h); - ruler(ui, &mut st, px, width, base_h); + let title = match &kind { + EditorKind::NewMText | EditorKind::MText => crate::tl!("Multiline Text").to_string(), + EditorKind::Line => crate::tl!("Text").to_string(), + EditorKind::Dimension { .. } => crate::tl!("Dimension Text").to_string(), + EditorKind::TableCell { name } => format!("{} {name}", crate::tl!("Cell")), + }; + if header(ui, &title, cell) { + done = Done::Cancel; + } + if formatting { + toolbar(ui, &mut st, base_h); + } + if ruler_shown { + ruler(ui, &mut st, px, width, base_h); + } + if let EditorKind::Dimension { measured } = &kind { + dimension_row(ui, &mut st, measured); + } st.top = ui.cursor().top() - y0; - text_box(ui, &mut st, base_h, px, width, &t); + text_box(ui, &mut st, base_h, px, width, &t, line); ui.horizontal(|ui| { ui.add_space(4.0); if ui.button(crate::tl!("OK")).clicked() { @@ -154,37 +278,128 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { if ui.button(crate::tl!("Cancel")).clicked() { done = Done::Cancel; } - let finish = if ui.ctx().os().is_mac() { crate::tl!("⌘↩ to finish") } else { crate::tl!("Ctrl+Enter to finish") }; + ui.add_space(6.0); + let mac = ui.ctx().os().is_mac(); + let tip = |undo: bool| match (undo, mac) { + (true, true) => crate::tl!("Undo (⌘Z)"), + (true, false) => crate::tl!("Undo (Ctrl+Z)"), + (false, true) => crate::tl!("Redo (⇧⌘Z)"), + (false, false) => crate::tl!("Redo (Ctrl+Y)"), + }; + for (undo, icon) in [(true, crate::icons::Icon::Undo), (false, crate::icons::Icon::Redo)] { + let any = if undo { !st.undo.is_empty() } else { !st.redo.is_empty() }; + let (r, resp) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click()); + if resp.hovered() && any { + ui.painter().rect_filled(r, 3.0, t.control_hover); + } + crate::icons::paint(ui.painter(), r.shrink(3.0), icon, !any); + if resp.on_hover_text(tip(undo)).clicked() && any { + undo_redo = Some(undo); + } + } + if cell { + if icon_button(ui, false, crate::tl!("Previous cell (Shift+Tab)"), |p, r, c| paint_triangle(p, r, c, -1.0)).clicked() { + done = Done::Move("Previous"); + } + if icon_button(ui, false, crate::tl!("Next cell (Tab)"), |p, r, c| paint_triangle(p, r, c, 1.0)).clicked() { + done = Done::Move("Next"); + } + } + let finish = match (line, ui.ctx().os().is_mac()) { + (true, _) => crate::tl!("Enter to finish"), + (false, true) => crate::tl!("⌘↩ to finish"), + (false, false) => crate::tl!("Ctrl+Enter to finish"), + }; ui.label(RichText::new(finish).small().color(t.text_dim)); }); }); }); + let now = ctx.input(|i| i.time); + match undo_redo { + Some(undo) => { + let (from, to) = if undo { (&mut st.undo, &mut st.redo) } else { (&mut st.redo, &mut st.undo) }; + if let Some((f, c, a)) = from.pop() { + to.push((st.fmt.clone(), st.edit.cursor, st.edit.anchor)); + st.fmt = f; + st.edit.cursor = c.min(st.fmt.len()); + st.edit.anchor = a.min(st.fmt.len()); + st.sel = (st.edit.cursor, st.edit.anchor); + st.typing_at = st.edit.cursor; + st.undo_at = 0.0; + } + } + None if st.fmt != before.0 => { + // Typing within a second of the last change is one step. + if now - st.undo_at > 1.0 || st.undo.is_empty() { + st.undo.push(before); + if st.undo.len() > 200 { + st.undo.remove(0); + } + } + st.undo_at = now; + st.redo.clear(); + } + None => {} + } + if let Some((_, list)) = completion(&st) { + let mut clicked = None; + egui::Area::new(egui::Id::unique("mtext_formula_list")).order(egui::Order::Tooltip).fixed_pos(st.fx_at + vec2(0.0, 4.0)).show(ctx, |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_min_width(260.0); + for (k, (name, args, _)) in list.iter().enumerate().take(10) { + let r = ui.selectable_label(k == st.fx_index, RichText::new(format!("{name}({args})")).monospace()); + if r.clicked() { + clicked = Some(k); + } + } + if let Some((_, _, what)) = list.get(st.fx_index) { + ui.separator(); + ui.label(RichText::new(crate::i18n::t(what)).small().color(t.text_dim)); + } + ui.label(RichText::new(crate::tl!("Tab or Enter: insert · Esc: close")).small().color(t.text_faint)); + }); + }); + if let Some(k) = clicked { + accept_completion(&mut st, k); + } + } if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { done = Done::Cancel; - } else if ctx.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Enter)) { - done = Done::Ok; } + let contents = if line { st.fmt.text().to_string() } else { st.fmt.to_contents() }; match done { Done::No => { ctx.data_mut(|d| d.insert_temp(state_id(), st)); } - Done::Ok => { + Done::Ok if kind == EditorKind::NewMText => { ctx.data_mut(|d| d.remove::(state_id())); // The editor holds the whole contents: one input, then Enter ends MTEXT's text entry. - // Emptied while editing an existing MTEXT: it keeps its text (Enter), as TEXTEDIT - // keeps it for an empty answer, and for one left unchanged (no undo step). - let textedit = app.session.running.as_ref().is_some_and(|r| r.id == "textedit"); - let contents = st.fmt.to_contents(); - let unchanged = textedit && Formatted::leaves_unchanged(&mt.contents, Some(mt.height), &contents); - if !st.fmt.is_empty() && !unchanged { - let _ = app.session.input(cadcraft_engine::Input::Text(contents)); - } else if textedit { + if !st.fmt.is_empty() { + let r = app.session.input(cadcraft_engine::Input::Text(contents)); + report(app, r); + } + // MTEXT ends its text with Enter; MLEADER takes Enter for "no text" when nothing was typed. + let still_asking = app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point); + if app.session.running.as_ref().is_some_and(|r| r.id == "mtext") || (st.fmt.is_empty() && still_asking) { let _ = app.session.input(cadcraft_engine::Input::Enter); } - if app.session.running.as_ref().is_some_and(|r| r.id == "mtext") { + } + Done::Ok => { + ctx.data_mut(|d| d.remove::(state_id())); + // Existing text: the new contents (even empty), then a table cell ends its editing. + let r = app.session.input(cadcraft_engine::Input::Text(contents)); + report(app, r); + if cell { let _ = app.session.input(cadcraft_engine::Input::Enter); } } + Done::Move(dir) => { + ctx.data_mut(|d| d.remove::(state_id())); + let r = app.session.input(cadcraft_engine::Input::Text(contents)); + report(app, r); + let r = app.session.input(cadcraft_engine::Input::Keyword(dir.into())); + report(app, r); + } Done::Cancel => { ctx.data_mut(|d| d.remove::(state_id())); app.session.cancel(); @@ -192,11 +407,39 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } } +/// Show a refused edit on the command line. +fn report(app: &mut CadApp, r: Result) { + if let Err(e) = r { + app.session.echo(e.to_string()); + } +} + #[derive(PartialEq)] enum Done { No, Ok, Cancel, + /// Keep this cell's text and move to another (a TABLEDIT move keyword). + Move(&'static str), +} + +/// A dimension's text: what `<>` stands for, and buttons to insert it or go back to it alone. +fn dimension_row(ui: &mut egui::Ui, st: &mut State, measured: &str) { + let t = Tokens::get(); + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.label(RichText::new(format!("<> = {measured}")).monospace().color(t.text)); + ui.label(RichText::new(crate::tl!("the measured value")).small().color(t.text_dim)); + if ui.small_button(crate::tl!("Insert <>")).on_hover_text(crate::tl!("Insert the measured value at the cursor")).clicked() { + insert(st, "<>"); + } + if ui.small_button(crate::tl!("Measured Value Only")).on_hover_text(crate::tl!("Replace the text with the measured value")).clicked() { + st.fmt = Formatted::from_contents("<>"); + st.sel = (2, 2); + st.caret = Some(2); + st.typing_at = 2; + } + }); } /// Change the selected characters' format, or the next typed ones' when nothing is selected. @@ -242,12 +485,26 @@ fn set_flag(c: &mut CharFmt, f: Flag, on: bool) { } } +/// The font list: the fonts in the user's font folders, then the installed and usual ones, then +/// the text's own (`current`), those whose name holds `filter` (any case). +fn font_families(mut families: Vec, current: Option, filter: &str) -> Vec { + for f in FAMILIES.iter().map(|s| s.to_string()).chain(current) { + if !families.iter().any(|x| x.eq_ignore_ascii_case(&f)) { + families.push(f); + } + } + let want = filter.trim().to_lowercase(); + families.retain(|f| want.is_empty() || f.to_lowercase().contains(&want)); + families +} + /// MTEXT formatting toolbar for the current selection: font, height, bold/italic/underline/overline, colour, alignment, lists, tab, degree/plus-minus and Diameter. Font, bold/italic/underline/overline, ByLayer/palette colour, alignment, list, tab and special-character changes refocus the editor; height and custom RGB colour changes do not. fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { let cur = current(st); let range = st.sel.0.min(st.sel.1)..st.sel.0.max(st.sel.1); let mut refocus = false; - ui.horizontal_wrapped(|ui| { + // Row 1: character format. + ui.horizontal(|ui| { ui.add_space(4.0); // Font let shown = cur.font.clone().unwrap_or_else(|| st.fmt.base_font.clone()); @@ -255,9 +512,20 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { .width(120.0) .selected_text(shown.clone()) .show_ui(ui, |ui| { - for fam in FAMILIES.iter().map(ToString::to_string).chain(cur.font.clone().filter(|f| !FAMILIES.contains(&f.as_str()))) { + // Typing narrows the list: the field takes the keyboard while the list is open. + let filter = + ui.add(egui::TextEdit::singleline(&mut st.font_filter).hint_text(crate::tl!("Type to search")).desired_width(f32::INFINITY)); + if !filter.has_focus() { + filter.request_focus(); + } + let families = font_families(crate::options::font_choices().1, cur.font.clone(), &st.font_filter); + if families.is_empty() { + ui.label(RichText::new(crate::tl!("No font matches")).weak()); + } + for fam in families { if ui.selectable_label(shown == fam, &fam).clicked() { change(st, |c| c.font = Some(fam.clone())); + st.font_filter.clear(); refocus = true; } } @@ -268,10 +536,7 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { let mut h = cur.height.unwrap_or(base_h); if height_field(ui, &mut h, base_h) { let none = (h - base_h).abs() < 1e-9; - change(st, |c| { - c.height = (!none).then_some(h); - c.height_rel = None; - }); + change(st, |c| c.height = (!none).then_some(h)); } ui.separator(); for (flag, label, tip) in [ @@ -285,9 +550,16 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { refocus = true; } } - // Colour + ui.separator(); + // Colour: an A over a bar in the colour, as word processors show it. let swatch = cur.color.map_or(ui.visuals().text_color(), color32); - ui.menu_button(RichText::new("A").color(swatch).strong(), |ui| { + let resp = icon_button_wide(ui, false, crate::tl!("Text color"), |p, r, c| { + let a = Rect::from_min_size(r.min, vec2(r.height(), r.height())); + p.text(pos2(a.center().x, a.top() + a.height() * 0.42), Align2::CENTER_CENTER, "A", FontId::proportional(a.height() * 0.8), c); + p.rect_filled(Rect::from_min_max(pos2(a.left() + 1.0, a.bottom() - 3.0), pos2(a.right() - 1.0, a.bottom())), 0.0, swatch); + paint_chevron(p, Rect::from_min_max(pos2(a.right() + 1.0, r.top()), r.max), c); + }); + egui::Popup::menu(&resp).show(|ui| { if ui.button(crate::tl!("ByLayer")).clicked() { change(st, |c| c.color = None); refocus = true; @@ -312,113 +584,199 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { let v = (u32::from(rgb[0]) << 16) | (u32::from(rgb[1]) << 8) | u32::from(rgb[2]); change(st, |c| c.color = Some(MTextColor::Rgb(v))); } - }) - .response - .accessible_name(crate::tl!("Text color")) - .on_hover_text(crate::tl!("Text color")); - ui.separator(); - // Paragraph alignment + }); + }); + // Row 2: paragraph, lists, tab and symbols. + ui.horizontal(|ui| { + ui.add_space(4.0); let para = st.fmt.para(st.fmt.paragraph_of(range.start)); for (al, tip) in [ - (ParaAlign::Left, crate::tl!("Left")), + (ParaAlign::Left, crate::tl!("Align left")), (ParaAlign::Center, crate::tl!("Center")), - (ParaAlign::Right, crate::tl!("Right")), + (ParaAlign::Right, crate::tl!("Align right")), (ParaAlign::Justify, crate::tl!("Justify")), ] { let on = para.align == al; - if formatting_button(ui, FormattingIcon::Align(al), tip, on) { + if icon_button(ui, on, tip, |p, r, c| paint_align(p, r, c, al)).clicked() { st.fmt.edit_paras(range.clone(), |p| p.align = if on { ParaAlign::Default } else { al }); refocus = true; } } ui.separator(); - // Lists and special characters - if formatting_button(ui, FormattingIcon::Bullets, crate::tl!("Bulleted list"), false) { + if icon_button(ui, false, crate::tl!("Bulleted list"), |p, r, c| paint_list(p, r, c, false)).clicked() { st.fmt.make_list(range.clone(), ListStyle::Bullet, 3.0 * base_h); refocus = true; } - if formatting_button(ui, FormattingIcon::Numbers, crate::tl!("Numbered list"), false) { + if icon_button(ui, false, crate::tl!("Numbered list"), |p, r, c| paint_list(p, r, c, true)).clicked() { st.fmt.make_list(range.clone(), ListStyle::Number, 3.0 * base_h); refocus = true; } - if formatting_button(ui, FormattingIcon::Tab, crate::tl!("Insert tab"), false) { + ui.separator(); + if icon_button(ui, false, crate::tl!("Insert tab"), paint_tab).clicked() { insert(st, "\t"); refocus = true; } - for (glyph, tip, code) in [("°", crate::tl!("Degree"), "°"), ("±", crate::tl!("Plus/minus"), "±")] { - if ui.button(glyph).on_hover_text(tip).clicked() { - insert(st, code); - refocus = true; - } - } - if diameter_button(ui) { - insert(st, "⌀"); - refocus = true; - } + let resp = icon_button_wide(ui, false, crate::tl!("Additional symbols"), |p, r, c| { + let a = Rect::from_min_size(r.min, vec2(r.height(), r.height())); + p.text(a.center(), Align2::CENTER_CENTER, "Ω", FontId::proportional(a.height() * 0.85), c); + paint_chevron(p, Rect::from_min_max(pos2(a.right() + 1.0, r.top()), r.max), c); + }); + egui::Popup::menu(&resp).show(|ui| { + ui.label(RichText::new(crate::tl!("Additional symbols")).strong()); + // Only the signs the interface fonts can draw (all of them with the system fonts; the + // web build has the bundled ones), and the diameter sign, which is painted. + let font = FontId::proportional(17.0); + let shown: Vec<&(&str, &str)> = + SYMBOLS.iter().filter(|(sym, _)| *sym == "⌀" || ui.fonts_mut(|f| sym.chars().all(|c| f.has_glyph(&font, c)))).collect(); + egui::Grid::new("mtext_symbols").spacing(vec2(2.0, 2.0)).show(ui, |ui| { + for (i, (sym, name)) in shown.into_iter().enumerate() { + let b = egui::Button::new(RichText::new(*sym).size(17.0)).min_size(vec2(30.0, 28.0)); + if ui + .add(b) + .accessible_name(crate::i18n::t(name)) + .on_hover_text(format!("{} ({sym}, U+{:04X})", crate::i18n::t(name), sym.chars().next().map_or(0, u32::from))) + .clicked() + { + insert(st, sym); + refocus = true; + ui.close(); + } + if i % 8 == 7 { + ui.end_row(); + } + } + }); + }); }); if refocus { ui.ctx().memory_mut(|m| m.request_focus(edit_id())); } } -/// Formatting marks use geometry so the toolbar works with the bundled font stack on web too. -enum FormattingIcon { - Align(ParaAlign), - Bullets, - Numbers, - Tab, -} - -/// Glyph-only MTEXT toolbar button: paints `icon`, exposes `label` as its accessible name and tooltip, and returns whether it was clicked. -fn formatting_button(ui: &mut egui::Ui, icon: FormattingIcon, label: &str, selected: bool) -> bool { - let response = ui - .add(egui::Button::new(" ").selected(selected).min_size(vec2(22.0, ui.spacing().interact_size.y))) - .accessible_name(label) - .on_hover_text(label); - let painter = ui.painter(); - let c = response.rect.center(); - let color = if response.enabled() { ui.visuals().text_color() } else { ui.visuals().weak_text_color() }; - let stroke = Stroke::new(1.2, color); - match icon { - FormattingIcon::Align(align) => { - for row in 0..3 { - let width = if row == 1 && align != ParaAlign::Justify { 8.0 } else { 14.0 }; - let x = match align { - ParaAlign::Center => -width / 2.0, - ParaAlign::Right => 7.0 - width, - _ => -7.0, - }; - let y = (row as f32 - 1.0) * 4.0; - painter.line_segment([c + vec2(x, y), c + vec2(x + width, y)], stroke); - } - } - FormattingIcon::Bullets | FormattingIcon::Numbers => { - for row in 0..3 { - let y = (row as f32 - 1.0) * 5.0; - if matches!(icon, FormattingIcon::Bullets) { - painter.circle_filled(c + vec2(-6.0, y), 1.2, color); - } else { - painter.text(c + vec2(-6.0, y), Align2::CENTER_CENTER, (row + 1).to_string(), FontId::proportional(7.0), color); - } - painter.line_segment([c + vec2(-2.0, y), c + vec2(7.0, y)], stroke); - } - } - FormattingIcon::Tab => { - for [a, b] in [ - [vec2(-7.0, 0.0), vec2(4.0, 0.0)], - [vec2(0.0, -4.0), vec2(4.0, 0.0)], - [vec2(0.0, 4.0), vec2(4.0, 0.0)], - [vec2(7.0, -5.0), vec2(7.0, 5.0)], - ] { - painter.line_segment([c + a, c + b], stroke); - } +/// The editor's width on screen for a text `text_w` wide (pixels; 0 or less: no width set) on a +/// canvas `canvas_w` wide: at least 380 pixels, at most nine tenths of the canvas, and never a +/// minimum above the maximum (a narrow window). +fn editor_width(text_w: f64, canvas_w: f32) -> f32 { + let max = (canvas_w * 0.9).max(120.0); + let min = 380.0_f32.min(max); + let w = text_w as f32; + if text_w > 0.0 && w.is_finite() { w.clamp(min, max) } else { min } +} + +/// The symbols of the Additional symbols menu: drafting marks, comparisons, Greek letters, +/// powers and fractions. +const SYMBOLS: [(&str, &str); 32] = [ + ("°", "Degree"), + ("±", "Plus/minus"), + ("⌀", "Diameter"), + ("∠", "Angle"), + ("⊥", "Perpendicular"), + ("∥", "Parallel"), + ("℄", "Center line"), + ("⌒", "Arc"), + ("≈", "Almost equal"), + ("≠", "Not equal"), + ("≤", "Less than or equal"), + ("≥", "Greater than or equal"), + ("×", "Multiplication"), + ("÷", "Division"), + ("√", "Square root"), + ("∞", "Infinity"), + ("Δ", "Delta"), + ("Ω", "Ohm"), + ("µ", "Micro"), + ("π", "Pi"), + ("α", "Alpha"), + ("β", "Beta"), + ("γ", "Gamma"), + ("φ", "Phi"), + ("²", "Squared"), + ("³", "Cubed"), + ("½", "One half"), + ("¼", "One quarter"), + ("¾", "Three quarters"), + ("‰", "Per mille"), + ("•", "Bullet"), + ("№", "Number sign"), +]; + +/// A square toolbar button drawn by `paint` (icon rectangle, colour): lit when `on`. +fn icon_button(ui: &mut egui::Ui, on: bool, tip: &str, paint: impl FnOnce(&egui::Painter, Rect, Color32)) -> egui::Response { + icon_button_sized(ui, on, tip, vec2(24.0, 22.0), vec2(16.0, 16.0), paint) +} + +/// A toolbar button with room for a drop-down arrow after its icon. +fn icon_button_wide(ui: &mut egui::Ui, on: bool, tip: &str, paint: impl FnOnce(&egui::Painter, Rect, Color32)) -> egui::Response { + icon_button_sized(ui, on, tip, vec2(32.0, 22.0), vec2(24.0, 16.0), paint) +} + +fn icon_button_sized( + ui: &mut egui::Ui, + on: bool, + tip: &str, + size: egui::Vec2, + icon: egui::Vec2, + paint: impl FnOnce(&egui::Painter, Rect, Color32), +) -> egui::Response { + let t = Tokens::get(); + let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); + let fill = if on { + Some(t.accent.gamma_multiply(0.45)) + } else if resp.hovered() { + Some(t.control_hover) + } else { + None + }; + if let Some(fill) = fill { + ui.painter().rect_filled(rect, 3.0, fill); + } + let color = if resp.hovered() || on { t.text } else { ui.visuals().text_color() }; + paint(ui.painter(), Rect::from_center_size(rect.center(), icon), color); + // Named on the node itself as well: on a clicked frame `widget_info` only emits an event. + let resp = resp.accessible_name(tip); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + resp.on_hover_text(crate::i18n::t(tip)) +} + +/// Paragraph alignment as word processors draw it: five lines of text, long and short, lined up +/// on the left, the centre or the right, or all full width. +fn paint_align(p: &egui::Painter, r: Rect, c: Color32, al: ParaAlign) { + let stroke = Stroke::new(1.6, c); + for i in 0..5 { + let y = r.top() + 1.5 + i as f32 * 3.25; + let w = match al { + ParaAlign::Justify => r.width(), + _ if i % 2 == 0 => r.width(), + ParaAlign::Center => r.width() * 0.6, + _ => r.width() * 0.62, + }; + let x0 = match al { + ParaAlign::Center => r.center().x - w / 2.0, + ParaAlign::Right => r.right() - w, + _ => r.left(), + }; + p.line_segment([pos2(x0, y), pos2(x0 + w, y)], stroke); + } +} + +/// A list: three lines, each after a bullet or its number (painted: the bundled fonts may not +/// have the list signs). +fn paint_list(p: &egui::Painter, r: Rect, c: Color32, numbered: bool) { + let stroke = Stroke::new(1.4, c); + for row in 0..3 { + let y = r.top() + 3.0 + row as f32 * 5.0; + let mark = pos2(r.left() + 3.0, y); + if numbered { + p.text(mark, Align2::CENTER_CENTER, (row + 1).to_string(), FontId::proportional(7.0), c); + } else { + p.circle_filled(mark, 1.4, c); } + p.line_segment([pos2(r.left() + 7.0, y), pos2(r.right(), y)], stroke); } - response.clicked() } -/// The MTEXT toolbar's height field. It has no visible caption, so the AccessKit label carries -/// the meaning of its hover tooltip; a tooltip alone leaves an unnamed spin button. +/// The toolbar's height field. It has no visible caption, so its accessibility label carries +/// what its tooltip says. fn height_field(ui: &mut egui::Ui, height: &mut f64, base_h: f64) -> bool { ui.add(egui::DragValue::new(height).speed(base_h * 0.02).range(base_h * 0.05..=base_h * 50.0).max_decimals(4)) .on_hover_text(crate::tl!("Text height")) @@ -426,27 +784,57 @@ fn height_field(ui: &mut egui::Ui, height: &mut f64, base_h: f64) -> bool { .changed() } -/// The MTEXT Diameter button. U+2300 is absent from every bundled face (including the -/// monochrome and emoji fallbacks) and the web build has no system fonts, so the sign is painted -/// rather than shaped from text. The semantic button name keeps the glyph-only control -/// discoverable to accessibility tools. -fn diameter_button(ui: &mut egui::Ui) -> bool { - let min_size = vec2(22.0, ui.spacing().interact_size.y); - let resp = ui.add(egui::Button::new(" ").min_size(min_size)).on_hover_text(crate::tl!("Diameter")); - let color = if resp.enabled() { ui.visuals().text_color() } else { ui.visuals().weak_text_color() }; - let stroke = Stroke::new(1.4, color); - let center = resp.rect.center(); - let radius = resp.rect.height() * 0.3; - let diagonal = radius * std::f32::consts::FRAC_1_SQRT_2; - let painter = ui.painter(); - painter.circle_stroke(center, radius, stroke); - painter.line_segment([center + vec2(-diagonal, diagonal), center + vec2(diagonal, -diagonal)], stroke); - // Name the node directly as well as through `WidgetInfo`: on a clicked frame `widget_info` - // emits an output event and does not update the AccessKit node, which would leave the - // glyph-only button unnamed for that frame. - let resp = resp.accessible_name(crate::tl!("Diameter")); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, resp.enabled(), crate::tl!("Diameter"))); - resp.clicked() +/// Insert tab: an arrow running into a stop. +fn paint_tab(p: &egui::Painter, r: Rect, c: Color32) { + let stroke = Stroke::new(1.6, c); + let y = r.center().y; + let stop = r.right() - 1.5; + p.line_segment([pos2(r.left() + 1.0, y), pos2(stop - 2.0, y)], stroke); + p.line_segment([pos2(stop - 6.5, y - 4.5), pos2(stop - 2.0, y)], stroke); + p.line_segment([pos2(stop - 6.5, y + 4.5), pos2(stop - 2.0, y)], stroke); + p.line_segment([pos2(stop, r.top() + 2.0), pos2(stop, r.bottom() - 2.0)], stroke); +} + +/// A small drop-down arrow in `r`. +fn paint_chevron(p: &egui::Painter, r: Rect, c: Color32) { + let m = r.center(); + p.add(Shape::convex_polygon(vec![pos2(m.x - 3.0, m.y - 1.5), pos2(m.x + 3.0, m.y - 1.5), pos2(m.x, m.y + 2.0)], c, Stroke::NONE)); +} + +/// A triangle pointing left (`dir` -1) or right (1). +fn paint_triangle(p: &egui::Painter, r: Rect, c: Color32, dir: f32) { + let m = r.center(); + let pts = vec![pos2(m.x + 4.0 * dir, m.y), pos2(m.x - 3.0 * dir, m.y - 5.0), pos2(m.x - 3.0 * dir, m.y + 5.0)]; + p.add(Shape::convex_polygon(pts, c, Stroke::NONE)); +} + +/// The editor's title and its close button (the same as Cancel); a table cell's hint. True when +/// the close button was clicked. +fn header(ui: &mut egui::Ui, title: &str, cell: bool) -> bool { + let t = Tokens::get(); + let mut close = false; + ui.horizontal(|ui| { + ui.add_space(6.0); + let label = ui.label(RichText::new(title).strong()); + if cell { + label.on_hover_text(crate::tl!("Tab: next cell · Shift+Tab: previous · Alt+↑↓: cell above, below")); + ui.label(RichText::new(crate::tl!("Tab: next cell")).small().color(t.text_dim)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(2.0); + let (rect, resp) = ui.allocate_exact_size(vec2(22.0, 20.0), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 3.0, Color32::from_rgb(196, 43, 28)); + } + let c = if resp.hovered() { Color32::WHITE } else { ui.visuals().text_color() }; + let k = Rect::from_center_size(rect.center(), vec2(9.0, 9.0)); + ui.painter().line_segment([k.left_top(), k.right_bottom()], Stroke::new(1.5, c)); + ui.painter().line_segment([k.right_top(), k.left_bottom()], Stroke::new(1.5, c)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::tl!("Close"))); + close = resp.on_hover_text(crate::tl!("Close (same as Cancel)")).clicked(); + }); + }); + close } /// Insert `s` at the caret (over the selection). @@ -527,95 +915,122 @@ fn ruler(ui: &mut egui::Ui, st: &mut State, px: f32, width: f32, base_h: f64) { bg.on_hover_text(crate::tl!("Click the ruler to add a tab stop, right-click to remove one")); } -/// MTEXT editor area with the formatted preview; restores a pending caret position before laying text out with `base_h`, `px`, `width` and the theme tokens. -fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, t: &Tokens) { +fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, t: &Tokens, line: bool) { let id = edit_id(); if let Some(at) = st.caret.take() { - let mut s = egui::TextEdit::load_state(ui.ctx(), id).unwrap_or_default(); - s.cursor.set_char_range(Some(CCursorRange::one(CCursor::new(at)))); - s.store(ui.ctx(), id); + st.edit.cursor = at; + st.edit.anchor = at; } let fmt = st.fmt.clone(); let default_color = t.text; - let mut layouter = move |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| -> Arc { - let mut job = LayoutJob::default(); - job.wrap.max_width = wrap; - let s = text.as_str(); - let mut run = String::new(); - let mut cur: Option = None; - let flush = |job: &mut LayoutJob, run: &mut String, f: &CharFmt| { - if run.is_empty() { - return; - } - let size = f.height.map_or(px, |h| (px * (h / base_h) as f32).clamp(6.0, 120.0)); - let color = f.color.map_or(default_color, color32); - job.append( - run, - 0.0, - TextFormat { - font_id: FontId::proportional(size), - color, - italics: f.italic, - underline: if f.underline { Stroke::new(1.0, color) } else { Stroke::NONE }, - // The editor has one weight of each font: bold is shown wider. - extra_letter_spacing: if f.bold { size * 0.06 } else { 0.0 }, - ..TextFormat::default() - }, - ); - run.clear(); - }; - for (i, c) in s.chars().enumerate() { - let f = fmt.fmt_at(i); - if cur.as_ref() != Some(&f) { - if let Some(p) = &cur { - flush(&mut job, &mut run, p); - } - cur = Some(f); - } - run.push(c); + let base = st.font.clone(); + // The font each character is drawn in: an inline family (`\f`) or the style's. + let font_of = |f: &CharFmt| match &f.font { + Some(fam) if !fam.trim().is_empty() && !fam.eq_ignore_ascii_case(&fmt_base(&base)) => { + crate::editor_glyphs::EditorFont { font: fam.clone(), big_font: String::new(), ..base.clone() } } - if let Some(p) = &cur { - flush(&mut job, &mut run, p); + _ => base.clone(), + }; + let size_of = |f: &CharFmt| f.height.map_or(px, |h| (px * (h / base_h) as f32).clamp(6.0, 120.0)); + let look = |i: usize| { + let f = fmt.fmt_at(i); + crate::bidi_edit::Look { + font: font_of(&f), + italic: f.italic, + bold: f.bold, + underline: f.underline, + size: size_of(&f), + color: f.color.map_or(default_color, color32), } - ui.fonts_mut(|f| f.layout_job(job)) }; let mut buf = st.fmt.text().to_string(); - let out = egui::TextEdit::multiline(&mut buf) - .id(id) - .desired_width(width) - .desired_rows(5) - .margin(egui::Margin::symmetric(4, 4)) - .lock_focus(true) - .char_limit(cadcraft_engine::mtext_edit::MAX_CHARS) - .layouter(&mut layouter) - .show(ui); - out.response.response.clone().accessible_name(crate::tl!("Text")); - // On opening, and while the text is empty, the editor takes the focus; a field of the toolbar - // the user clicked keeps it. - let free = ui.memory(|m| m.focused().is_none()); - if !out.response.has_focus() && (!st.focused || (buf.is_empty() && st.fmt.is_empty() && free)) { - out.response.request_focus(); - } - st.focused = true; - if out.response.changed() { + let out = crate::bidi_edit::show( + ui, + id, + &mut buf, + &mut st.edit, + line, + width, + if line { 1 } else { 5 }, + &look, + px, + cadcraft_engine::mtext_edit::MAX_CHARS, + ); + st.fx_at = out.caret; + let focused = ui.memory(|m| m.has_focus(id)); + // An empty editor takes the keyboard back, unless another field has it (the font list's + // search field while the list is open). + if !focused && (st.focus || (buf.is_empty() && st.fmt.is_empty() && ui.memory(|m| m.focused().is_none()))) { + ui.memory_mut(|m| m.request_focus(id)); + } + st.focus = false; + if out.changed { let typing = st.typing.clone(); st.fmt.set_text(&buf, &typing); } - if let Some(r) = out.cursor_range { - let (a, b) = (r.primary.index.0, r.secondary.index.0); - st.sel = (a, b); - if a == b { - if out.response.changed() { - st.typing_at = a; - } else if a != st.typing_at { - // The caret moved: typing continues the formatting of the character before it. - st.typing = st.fmt.fmt_at(a.saturating_sub(1)); - st.typing_at = a; - } + let (a, b) = (st.edit.cursor, st.edit.anchor); + st.sel = (a, b); + if a == b { + if out.changed { + st.typing_at = a; + } else if a != st.typing_at { + // The caret moved: typing continues the formatting of the character before it. + st.typing = st.fmt.fmt_at(a.saturating_sub(1)); + st.typing_at = a; } } } +/// The formula functions whose names start with the word before the caret, when the text is +/// a formula (`=...`) and the caret is not inside a quoted string: (the word's start, the +/// functions). +fn completion(st: &State) -> Option<(usize, Vec<&'static (&'static str, &'static str, &'static str)>)> { + let text = st.fmt.text(); + if !text.trim_start().starts_with('=') || st.edit.cursor != st.edit.anchor || st.fx_closed.as_deref() == Some(text) { + return None; + } + let chars: Vec = text.chars().collect(); + let at = st.edit.cursor.min(chars.len()); + if chars.get(..at)?.iter().filter(|c| **c == '"').count() % 2 == 1 { + return None; + } + let mut s = at; + while s > 0 && chars.get(s - 1).is_some_and(|c| c.is_ascii_alphanumeric() || *c == '_') { + s -= 1; + } + let word: String = chars.get(s..at)?.iter().collect::().to_ascii_uppercase(); + if word.is_empty() || !word.starts_with(|c: char| c.is_ascii_alphabetic()) { + return None; + } + let list: Vec<_> = cadcraft_engine::textformula::FUNCTIONS.iter().filter(|(n, _, _)| n.starts_with(&word) && *n != word).collect(); + (!list.is_empty()).then_some((s, list)) +} + +/// Put function `k` of the completion list in place of the word before the caret, with its +/// opening parenthesis (and the closing one when it takes no arguments). +fn accept_completion(st: &mut State, k: usize) { + let Some((start, list)) = completion(st) else { return }; + let Some((name, args, _)) = list.get(k).map(|f| **f) else { return }; + let mut chars: Vec = st.fmt.text().chars().collect(); + let at = st.edit.cursor.min(chars.len()); + let ins: Vec = format!("{name}({}", if args.is_empty() { ")" } else { "" }).chars().collect(); + let n = ins.len(); + chars.splice(start..at, ins); + let text: String = chars.iter().collect(); + let typing = st.typing.clone(); + st.fmt.set_text(&text, &typing); + st.edit.cursor = start + n; + st.edit.anchor = st.edit.cursor; + st.typing_at = st.edit.cursor; + st.fx_index = 0; +} + +/// The style font's family as an inline font switch would name it (`txt.shx` → `txt`). +fn fmt_base(f: &crate::editor_glyphs::EditorFont) -> String { + let n = f.font.trim(); + n.rsplit(['\\', '/']).next().unwrap_or(n).split('.').next().unwrap_or("").to_string() +} + #[cfg(test)] mod tests { use super::*; @@ -626,123 +1041,85 @@ mod tests { use crate::Services; - /// Clicking Diameter inserts U+2300 into both the formatted text and `to_contents()`, selects it, and leaves no unnamed widget. - #[test] - fn diameter_insertion_keeps_real_text_and_renders_without_optional_fonts() { - let state = State { + fn blank() -> State { + State { fmt: Formatted::default(), typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None, - focused: false, - target: None, - }; - let mut harness = Harness::builder().with_size(vec2(1100.0, 300.0)).with_context_setup(install_diameter_glyph).build_ui_state( - |ui, state| { - toolbar(ui, state, 2.5); - text_box(ui, state, 2.5, 20.0, 1000.0, &Tokens::get()); - }, - state, - ); - harness.run(); - harness.get_by_role_and_label(Role::Button, "Diameter").click(); - harness.run(); - assert_eq!(harness.state().fmt.text(), "⌀"); - assert_eq!(harness.state().fmt.to_contents(), "⌀"); - assert_eq!(harness.state().sel, (1, 1)); - assert!(harness.unnamed_widgets().is_empty()); + key: String::new(), + focus: false, + font: crate::editor_glyphs::EditorFont::default(), + edit: crate::bidi_edit::EditState::default(), + fx_index: 0, + fx_closed: None, + fx_at: egui::Pos2::ZERO, + undo: Vec::new(), + redo: Vec::new(), + undo_at: 0.0, + font_filter: String::new(), + } } - /// With the text empty, a click on the height field keeps the focus there; the editor doesn't - /// take it back. + /// Additional symbols ▸ Diameter inserts U+2300 into both the formatted text and + /// `to_contents()`, and leaves no unnamed widget. + /// The font list holds every font family and the usual ones, and typing narrows it. #[test] - fn an_empty_editor_leaves_the_focus_on_the_height_field() { - let state = State { - fmt: Formatted::default(), - typing: CharFmt::default(), - typing_at: 0, - top: 70.0, - sel: (0, 0), - caret: None, - focused: false, - target: None, - }; - let mut harness = Harness::builder().with_size(vec2(1100.0, 300.0)).build_ui_state( + fn the_font_list_narrows_to_what_is_typed() { + let installed = vec!["Segoe UI".to_string(), "Noto Sans Hebrew".to_string(), "Arial".to_string()]; + let all = super::font_families(installed.clone(), Some("My Font".into()), ""); + assert!(all.iter().any(|f| f == "Segoe UI") && all.iter().any(|f| f == "Calibri") && all.iter().any(|f| f == "My Font")); + assert_eq!(all.iter().filter(|f| f.eq_ignore_ascii_case("arial")).count(), 1, "no family twice"); + assert_eq!(super::font_families(installed.clone(), None, " heb "), vec!["Noto Sans Hebrew".to_string()]); + assert!(super::font_families(installed, None, "zzz").is_empty()); + } + + #[test] + fn diameter_insertion_keeps_real_text_and_renders_without_optional_fonts() { + let mut harness = Harness::builder().with_size(vec2(1100.0, 500.0)).with_context_setup(install_diameter_glyph).build_ui_state( |ui, state| { toolbar(ui, state, 2.5); - text_box(ui, state, 2.5, 20.0, 1000.0, &Tokens::get()); + text_box(ui, state, 2.5, 20.0, 1000.0, &Tokens::get(), false); }, - state, + blank(), ); harness.run(); - assert!(harness.ctx.memory(|m| m.has_focus(edit_id())), "the editor opens with the focus"); - harness.get_by_role_and_label(Role::SpinButton, "Text height").click(); + harness.get_by_role_and_label(Role::Button, "Additional symbols").click(); harness.run(); + harness.get_by_role_and_label(Role::Button, "Diameter").click(); harness.run(); - assert!(!harness.ctx.memory(|m| m.has_focus(edit_id())), "the height field keeps the focus"); + assert_eq!(harness.state().fmt.text(), "⌀"); + assert_eq!(harness.state().fmt.to_contents(), "⌀"); + assert!(harness.unnamed_widgets().is_empty(), "unnamed controls: {:?}", harness.unnamed_widgets()); } - /// The ten toolbar controls listed in the test are found by semantic name under the harness's default bundled fonts, and no toolbar widget is unnamed. + /// The toolbar's controls are found by name under the bundled fonts, and none is unnamed. #[test] fn the_whole_toolbar_uses_bundled_glyphs_and_names_its_controls() { - let mut state = State { - fmt: Formatted::default(), - typing: CharFmt::default(), - typing_at: 0, - top: 70.0, - sel: (0, 0), - caret: None, - focused: false, - target: None, - }; + let mut state = blank(); let mut harness = Harness::builder().with_size(vec2(1100.0, 120.0)).build_ui(move |ui| toolbar(ui, &mut state, 2.5)); harness.run(); - for name in ["Left", "Center", "Right", "Justify", "Bulleted list", "Numbered list", "Insert tab", "Diameter", "Text color", "Font"] { + for name in [ + "Align left", + "Center", + "Align right", + "Justify", + "Bulleted list", + "Numbered list", + "Insert tab", + "Additional symbols", + "Text color", + "Font", + "Text height", + ] { assert!(harness.query_by_label(name).is_some(), "missing semantic control {name}"); } assert!(harness.unnamed_widgets().is_empty(), "unnamed controls: {:?}", harness.unnamed_widgets()); } - /// Strict bundled-font and accessibility regression for the glyph-only Diameter button: the - /// test context uses egui's bundled faces only (no `theme::install_fonts` system prepend), - /// and the harness panics on a missing glyph by default. The sign must be painted, not - /// shaped from U+2300. - #[test] - fn diameter_button_is_painted_and_named_under_bundled_fonts() { - let ctx = egui::Context::default(); - ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(120.0, 60.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - diameter_button(ui); - }); - out.textures_delta.clear(); - let mut text = String::new(); - let (mut circle, mut slash) = (false, false); - for shape in &out.shapes { - match &shape.shape { - Shape::Circle(_) => circle = true, - Shape::LineSegment { .. } => slash = true, - Shape::Text(t) => text.push_str(&t.galley.job.text), - _ => {} - } - } - assert!(circle, "the diameter sign's circle is painted"); - assert!(slash, "the diameter sign's slash is painted"); - assert!(!text.contains('\u{2300}'), "U+2300 must not be shaped from a font: {text:?}"); - - let mut harness = Harness::builder().with_size(vec2(240.0, 80.0)).build_ui(|ui| { - diameter_button(ui); - }); - harness.run(); - let button = harness.get_by_label("Diameter"); - assert_eq!(button.accesskit_node().role(), Role::Button); - assert!(harness.unnamed_widgets().is_empty(), "unnamed controls: {:?}", harness.unnamed_widgets()); - } - - /// The height DragValue has no visible caption, so its AccessKit label must be set explicitly. - /// Bundled fonts only: no system face can mask a missing glyph in the harness. + /// The height field has no visible caption, so its accessibility label is set explicitly. #[test] fn height_field_is_named_for_accessibility_under_bundled_fonts() { let mut harness = Harness::builder().with_size(vec2(360.0, 80.0)).build_ui(|ui| { @@ -755,6 +1132,24 @@ mod tests { assert!(harness.unnamed_widgets().is_empty(), "unnamed controls: {:?}", harness.unnamed_widgets()); } + /// A narrow window (400 pixels and less) never orders the bounds the wrong way round, which + /// would panic (#2034 review); the width stays within the canvas. + #[test] + fn the_editor_width_fits_narrow_canvases() { + for canvas in [0.0_f32, 50.0, 300.0, 400.0, 421.0, 800.0, 2000.0, f32::NAN] { + for text in [-1.0, 0.0, 10.0, 370.0, 390.0, 5000.0, f64::NAN, f64::INFINITY] { + let w = editor_width(text, canvas); + assert!(w.is_finite() && w > 0.0, "{canvas} {text}: {w}"); + if canvas.is_finite() && canvas >= 140.0 { + assert!(w <= canvas * 0.9 + 1e-3, "{canvas} {text}: {w}"); + } + } + } + assert_eq!(editor_width(0.0, 2000.0), 380.0); + assert_eq!(editor_width(1000.0, 2000.0), 1000.0); + assert_eq!(editor_width(500.0, 400.0), 360.0); + } + #[test] fn editor_opens_only_for_mtext_text_entry_and_finishes_with_formatted_contents() { let ctx = egui::Context::default(); @@ -785,101 +1180,4 @@ mod tests { let found = d.model.iter().any(|e| matches!(&e.kind, cadcraft_engine::doc::EntityKind::MText(m) if m.contents == contents)); assert!(found, "{contents}"); } - - /// #842: TEXTEDIT on an existing MTEXT (what a double-click starts) opens it in the editor - /// with its text and formats; finishing writes the edited contents back to that MTEXT. - /// TEXTEDIT moving on to another MTEXT between two frames (Enter keeps the first, a point picks - /// the next) opens the next one with its own text, never the first one's. - #[test] - fn textedit_on_the_next_mtext_does_not_keep_the_first_ones_text() { - let ctx = egui::Context::default(); - let mut app = CadApp::new(Session::new(), Services::default()); - let frame = |app: &mut CadApp| { - let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }; - for _ in 0..2 { - let mut out = ctx.run_ui(input.clone(), |ui| show(app, ui.ctx())); - out.textures_delta.clear(); - } - }; - app.run("mtext", serde_json::json!({ "at": [0, 20], "text": "first one", "height": 2.5, "width": 20 })).unwrap(); - app.run("mtext", serde_json::json!({ "at": [0, 60], "text": "second one", "height": 2.5, "width": 20 })).unwrap(); - app.start("textedit"); - app.session.input(cadcraft_engine::Input::Point(cadcraft_geom::Vec2::new(1.0, 19.0))).unwrap(); - frame(&mut app); - assert_eq!(ctx.data_mut(|d| d.get_temp::(state_id())).expect("editor open").fmt.text(), "first one"); - // Both inputs between two frames: the first MTEXT kept as it is, then the second picked. - app.session.input(cadcraft_engine::Input::Enter).unwrap(); - app.session.input(cadcraft_engine::Input::Point(cadcraft_geom::Vec2::new(1.0, 59.0))).unwrap(); - assert!(app.session.editing_mtext().is_some_and(|m| m.contents.contains("second")), "TEXTEDIT is on the second MTEXT"); - frame(&mut app); - assert_eq!(ctx.data_mut(|d| d.get_temp::(state_id())).expect("editor open").fmt.text(), "second one"); - } - - #[test] - fn textedit_opens_an_existing_mtext_with_its_contents() { - let ctx = egui::Context::default(); - let mut app = CadApp::new(Session::new(), Services::default()); - let frame = |app: &mut CadApp| { - let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }; - for _ in 0..2 { - let mut out = ctx.run_ui(input.clone(), |ui| show(app, ui.ctx())); - out.textures_delta.clear(); - } - }; - app.run("mtext", serde_json::json!({ "at": [0, 20], "text": "{\\fArial|b1;first}\\Psecond", "height": 2.5, "width": 20 })).unwrap(); - let h = app.session.doc().unwrap().model.last().unwrap().handle; - app.start("textedit"); - let at = cadcraft_geom::Vec2::new(1.0, 19.0); - app.session.input(cadcraft_engine::Input::Point(at)).unwrap(); - let m = app.session.editing_mtext().expect("an MTEXT to edit"); - assert!(m.contents.contains("second"), "{}", m.contents); - frame(&mut app); - let st = ctx.data_mut(|d| d.get_temp::(state_id())).expect("editor open"); - assert_eq!(st.fmt.text(), "first\nsecond"); - assert!(st.fmt.fmt_at(0).bold && !st.fmt.fmt_at(7).bold, "formats kept"); - let mut st = st; - st.fmt.set_text("first\nsecond\nthird", &CharFmt::default()); - app.session.input(cadcraft_engine::Input::Text(st.fmt.to_contents())).unwrap(); - frame(&mut app); - assert!(ctx.data_mut(|d| d.get_temp::(state_id())).is_none(), "editor closed"); - match &app.session.doc().unwrap().entity(h).unwrap().kind { - cadcraft_engine::doc::EntityKind::MText(m) => assert!(m.contents.contains("third") && m.contents.contains("b1"), "{}", m.contents), - _ => panic!(), - } - } - - /// A multileader's text with a relative height code (`\H2x;`) opens in the editor at twice - /// its text height, so saving it back keeps the bigger letters. - #[test] - fn a_relative_height_in_a_multileaders_text_is_kept() { - let ctx = egui::Context::default(); - let mut app = CadApp::new(Session::new(), Services::default()); - let frame = |app: &mut CadApp| { - let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }; - for _ in 0..2 { - let mut out = ctx.run_ui(input.clone(), |ui| show(app, ui.ctx())); - out.textures_delta.clear(); - } - }; - app.run("mleader", serde_json::json!({ "points": [[16, -10], [20, -5]], "text": "{\\H2x;big} small" })).unwrap(); - let (at, height) = app - .session - .doc() - .unwrap() - .model - .iter() - .find_map(|e| { - if let cadcraft_engine::doc::EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| (t.insert.xy(), t.height)) } else { None } - }) - .unwrap(); - app.start("textedit"); - app.session.input(cadcraft_engine::Input::Point(at + cadcraft_geom::Vec2::new(0.5, -0.05))).unwrap(); - assert!(app.session.editing_mtext().is_some(), "the multileader's text is being edited"); - frame(&mut app); - let st = ctx.data_mut(|d| d.get_temp::(state_id())).expect("editor open"); - assert_eq!(st.fmt.text(), "big small"); - let big = st.fmt.fmt_at(0).height.expect("the relative height is kept"); - assert!((big - 2.0 * height).abs() < 1e-9, "{big} for a {height} text"); - assert_eq!(st.fmt.fmt_at(5).height, None, "the rest keeps the text's height"); - } } diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index 826bf3448f..dd272220d1 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -464,6 +464,37 @@ fn reset_ui(app: &mut CadApp) { app.options = UiOptions::default(); } +/// Fonts for font lists, refreshed when the font set changes: (text style font names — the +/// user's folders' fonts first —, family names of every font, the user's first). +pub fn font_choices() -> (Vec, Vec) { + thread_local! { + static CACHE: std::cell::RefCell, Vec)>> = const { std::cell::RefCell::new(None) }; + } + let generation = cadcraft_fonts::ttf::generation(); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + if let Some((g, names, families)) = c.as_ref() + && *g == generation + { + return (names.clone(), families.clone()); + } + let fonts = cadcraft_fonts::ttf::installed(); + let mut names = vec![cadcraft_fonts::BUILTIN_FONT.to_string()]; + names.extend(fonts.iter().map(|f| f.name.clone())); + // Every font's family: the user's folders' first, then the installed ones. + let mut families: Vec = Vec::new(); + for f in fonts.iter() { + if let Some(fam) = &f.family + && !families.iter().any(|x| x.eq_ignore_ascii_case(fam)) + { + families.push(fam.clone()); + } + } + *c = Some((generation, names.clone(), families.clone())); + (names, families) + }) +} + impl CadApp { /// The user profile kept across restarts, as JSON for the host's storage ([`PROFILE_KEY`]): /// the engine's profile variables, the user's aliases (ALIASEDIT, not drawing data) and the diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 22b2a1709a..ca121bfc71 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -45,6 +45,7 @@ mod status_bar_toggles; mod style_dialogs; mod system_cursor; mod text_double_click; +mod text_editing; mod toolsets_gear; mod toolsets_parametric; mod viewport_double_click_selection; diff --git a/crates/ui-egui/tests/it/text_double_click.rs b/crates/ui-egui/tests/it/text_double_click.rs index faf3da714a..04446b8b39 100644 --- a/crates/ui-egui/tests/it/text_double_click.rs +++ b/crates/ui-egui/tests/it/text_double_click.rs @@ -56,15 +56,16 @@ fn double_click_on_text_starts_textedit_for_that_object() { let mut h = harness(); double_click(&mut h, at); let s = &h.state().session; - assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("textedit"), "object {i}"); + assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("textedit.object"), "object {i}"); + assert!(s.text_editor().is_some(), "object {i}: the in-place editor opens"); let p = s.current_prompt().unwrap(); assert_eq!(p.message, "Enter new text", "object {i}: the clicked text is already picked"); assert_eq!(p.default.as_deref(), Some(old), "object {i}"); h.state_mut().session.input(Input::Text(new.into())).unwrap(); h.run_steps(2); assert_eq!(text_at(&h, i), new); - // TEXTEDIT goes on asking for objects (its Multiple mode), as AutoCAD's does. - assert_eq!(h.state().session.current_prompt().unwrap().message, "Select an annotation object"); + // A double-click edits that one object: the command ends with it. + assert!(h.state().session.running.is_none(), "object {i}"); } } @@ -83,17 +84,17 @@ fn double_clicked_text_takes_ime_composition_and_commit() { if !drawable { h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu); } - // Composition is shown, not saved; the commit is inserted exactly once (#1761). + assert!(h.state().session.text_editor().is_some(), "the in-place editor has the keyboard"); + // Composition is shown in the editor, not saved; the commit is inserted exactly once and + // replaces the text the editor opened with selected (#1761). h.event(Event::Ime(ImeEvent::Preedit { text: "zhong".into(), active_range_chars: None })); h.run_steps(1); - assert_eq!(h.state().cmd.preedit, "zhong"); - assert!(h.state().cmd.buffer.is_empty()); + assert_eq!(text_at(&h, 0), "HELLO"); + assert!(h.state().cmd.buffer.is_empty(), "nothing reaches the command line"); h.event(Event::Ime(ImeEvent::Commit("中文".into()))); h.run_steps(1); - assert!(h.state().cmd.preedit.is_empty()); - assert_eq!(h.state().cmd.buffer, "中文"); h.key_press(Key::Enter); - h.run_steps(1); + h.run_steps(2); assert_eq!(text_at(&h, 0), "中文"); } @@ -106,6 +107,20 @@ fn double_click_elsewhere_starts_no_command() { } } +#[test] +fn double_click_on_a_block_reference_opens_the_block_editor() { + let mut h = harness(); + { + let app = h.state_mut(); + let c = app.run("circle", json!({ "center": [30, 20], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string(); + app.run("block", json!({ "name": "Wheel", "base": [30, 20], "handles": [c] })).unwrap(); + app.run("insert", json!({ "name": "Wheel", "at": [30, 20] })).unwrap(); + } + h.run_steps(3); + double_click(&mut h, Vec2::new(32.0, 20.0)); + assert!(h.state().session.state().unwrap().block_edit.is_some(), "the Block Editor is open"); +} + /// #1081: double-clicking a multileader's text edits it, as for TEXT and MTEXT. #[test] fn double_click_on_a_multileaders_text_starts_textedit() { @@ -123,7 +138,7 @@ fn double_click_on_a_multileaders_text_starts_textedit() { .unwrap(); double_click(&mut h, at + Vec2::new(1.0, -0.05)); let s = &h.state().session; - assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("textedit")); + assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("textedit.object")); let p = s.current_prompt().unwrap(); assert_eq!(p.message, "Enter new text"); assert_eq!(p.default.as_deref(), Some("example text")); diff --git a/crates/ui-egui/tests/it/text_editing.rs b/crates/ui-egui/tests/it/text_editing.rs new file mode 100644 index 0000000000..2c0670abb7 --- /dev/null +++ b/crates/ui-egui/tests/it/text_editing.rs @@ -0,0 +1,118 @@ +//! The in-place text editor on existing objects: one line of text finishes with Enter, a table +//! cell moves on with Tab, a dimension keeps `<>` for its measured value. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::{EditorKind, Input, Session}; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::{Event, Key, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +fn harness(setup: impl FnOnce(&mut CadApp)) -> Harness<'static, CadApp> { + let mut app = CadApp::new(Session::default(), Services::default()); + app.run("new", json!({})).unwrap(); + app.ui.start_tab = false; + app.ui.in_window_menu = false; + setup(&mut app); + let mut h = Harness::builder().with_size(vec2(1280.0, 860.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); + h.run_steps(5); + h +} + +fn handle(v: &Value) -> String { + v["handle"].as_str().unwrap().to_string() +} + +fn entity(h: &Harness<'_, CadApp>, hex: &str) -> EntityKind { + let doc = h.state().session.doc().unwrap(); + doc.model.iter().find(|e| e.handle.hex() == hex).unwrap().kind.clone() +} + +fn key(h: &mut Harness<'_, CadApp>, key: Key, modifiers: Modifiers) { + h.event(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + h.event(Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }); + h.run_steps(3); +} + +fn type_text(h: &mut Harness<'_, CadApp>, text: &str) { + h.event(Event::Text(text.into())); + h.run_steps(3); +} + +#[test] +fn one_line_of_text_is_edited_in_place_and_enter_finishes() { + let mut t = String::new(); + let mut h = harness(|app| { + t = handle(&app.run("text", json!({ "at": [0, 0], "text": "Plan", "height": 2.0 })).unwrap()); + app.start("textedit.object"); + app.session.input(Input::Point(cadcraft_geom::Vec2::new(0.5, 0.5))).unwrap(); + }); + assert_eq!(h.state().session.text_editor().map(|e| e.kind), Some(EditorKind::Line)); + // The text opens selected: End goes past it, then the typing adds to it. + key(&mut h, Key::End, Modifiers::NONE); + type_text(&mut h, " B"); + key(&mut h, Key::Enter, Modifiers::NONE); + assert!(h.state().session.running.is_none(), "{}", h.state().session.prompt_text()); + assert!(matches!(entity(&h, &t), EntityKind::Text(x) if x.value == "Plan B")); +} + +#[test] +fn tab_keeps_a_cell_and_moves_to_the_next() { + let mut t = String::new(); + let mut h = harness(|app| { + t = handle(&app.run("table", json!({ "at": [0, 10], "rows": 2, "cols": 2, "colWidth": 6, "rowHeight": 2 })).unwrap()); + app.start("tabledit.cell"); + app.session.input(Input::Point(cadcraft_geom::Vec2::new(3.0, 9.0))).unwrap(); + }); + type_text(&mut h, "A"); + key(&mut h, Key::Tab, Modifiers::NONE); + assert!(matches!(h.state().session.text_editor().map(|e| e.kind), Some(EditorKind::TableCell { name }) if name == "B1")); + type_text(&mut h, "B"); + key(&mut h, Key::Enter, Modifiers::COMMAND); + assert!(h.state().session.running.is_none(), "{}", h.state().session.prompt_text()); + let EntityKind::Table(tb) = entity(&h, &t) else { panic!() }; + assert_eq!((tb.cells[0][0].text.as_str(), tb.cells[0][1].text.as_str()), ("A", "B")); +} + +/// While a formula's function list is open, Tab puts the function in and stays in the cell. +#[test] +fn tab_completes_a_formula_in_a_cell_before_moving_on() { + let mut t = String::new(); + let mut h = harness(|app| { + t = handle(&app.run("table", json!({ "at": [0, 10], "rows": 2, "cols": 2, "colWidth": 6, "rowHeight": 2 })).unwrap()); + app.start("tabledit.cell"); + app.session.input(Input::Point(cadcraft_geom::Vec2::new(3.0, 9.0))).unwrap(); + }); + type_text(&mut h, "=ROUN"); + key(&mut h, Key::Tab, Modifiers::NONE); + assert!(matches!(h.state().session.text_editor().map(|e| e.kind), Some(EditorKind::TableCell { name }) if name == "A1")); + type_text(&mut h, "2.5,0)"); + key(&mut h, Key::Enter, Modifiers::COMMAND); + let EntityKind::Table(tb) = entity(&h, &t) else { panic!() }; + assert_eq!(tb.cells[0][0].formula.as_deref(), Some("=ROUND(2.5,0)")); +} + +#[test] +fn a_dimension_shows_its_measured_value_and_keeps_the_placeholder() { + let mut d = String::new(); + let mut h = harness(|app| { + d = handle(&app.run("dimlinear", json!({ "p1": [0, 0], "p2": [25, 0], "at": [12, 4] })).unwrap()); + let doc = app.session.doc().unwrap(); + let Some(EntityKind::Dimension(dm)) = doc.model.iter().find(|e| e.handle.hex() == d).map(|e| e.kind.clone()) else { panic!() }; + let at = cadcraft_render::dimension_in(doc, &dm).text_pos; + app.start("textedit.object"); + app.session.input(Input::Point(at)).unwrap(); + }); + assert!(h.query_by_label_contains("<> = 25").is_some(), "the measured value is shown"); + key(&mut h, Key::Home, Modifiers::NONE); + type_text(&mut h, "L="); + key(&mut h, Key::Enter, Modifiers::COMMAND); + assert!(matches!(entity(&h, &d), EntityKind::Dimension(x) if x.text == "L=<>"), "{:?}", entity(&h, &d)); +}